/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1
# groupcompress, a bzr plugin providing new compression logic.
2
# Copyright (C) 2008 Canonical Limited.
3
# 
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License version 2 as published
6
# by the Free Software Foundation.
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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
16
# 
17
18
"""Core compression logic for compressing streams of related files."""
19
0.17.13 by Robert Collins
Do not output copy instructions which take more to encode than a fresh insert. (But do not refer to those insertions when finding ranges to copy: they are not interesting).
20
from itertools import izip
0.17.5 by Robert Collins
nograph tests completely passing.
21
from cStringIO import StringIO
22
import zlib
23
0.17.4 by Robert Collins
Annotate.
24
from bzrlib import (
25
    annotate,
0.17.5 by Robert Collins
nograph tests completely passing.
26
    debug,
0.17.4 by Robert Collins
Annotate.
27
    diff,
0.17.5 by Robert Collins
nograph tests completely passing.
28
    errors,
0.17.4 by Robert Collins
Annotate.
29
    graph as _mod_graph,
0.20.2 by John Arbash Meinel
Teach groupcompress about 'chunked' encoding
30
    osutils,
0.17.4 by Robert Collins
Annotate.
31
    pack,
32
    patiencediff,
33
    )
34
from bzrlib.graph import Graph
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
35
from bzrlib.knit import _DirectPackAccess
0.17.2 by Robert Collins
Core proof of concept working.
36
from bzrlib.osutils import (
37
    contains_whitespace,
38
    contains_linebreaks,
39
    sha_string,
40
    sha_strings,
41
    split_lines,
42
    )
0.17.21 by Robert Collins
Update groupcompress to bzrlib 1.10.
43
from bzrlib.btree_index import BTreeBuilder
0.17.24 by Robert Collins
Add a group cache to decompression, 5 times faster than knit at decompression when accessing everything in a group.
44
from bzrlib.lru_cache import LRUSizeCache
0.18.6 by John Arbash Meinel
Use the new EquivalenceTable to track the lines.
45
from bzrlib.plugins.groupcompress import equivalence_table
0.17.9 by Robert Collins
Initial stab at repository format support.
46
from bzrlib.tsort import topo_sort
0.17.2 by Robert Collins
Core proof of concept working.
47
from bzrlib.versionedfile import (
0.17.5 by Robert Collins
nograph tests completely passing.
48
    adapter_registry,
49
    AbsentContentFactory,
0.17.2 by Robert Collins
Core proof of concept working.
50
    FulltextContentFactory,
51
    VersionedFiles,
52
    )
53
54
0.17.5 by Robert Collins
nograph tests completely passing.
55
def parse(line_list):
0.17.2 by Robert Collins
Core proof of concept working.
56
    result = []
0.17.5 by Robert Collins
nograph tests completely passing.
57
    lines = iter(line_list)
0.17.2 by Robert Collins
Core proof of concept working.
58
    next = lines.next
0.17.5 by Robert Collins
nograph tests completely passing.
59
    label_line = lines.next()
60
    sha1_line = lines.next()
61
    if (not label_line.startswith('label: ') or
62
        not sha1_line.startswith('sha1: ')):
63
        raise AssertionError("bad text record %r" % lines)
64
    label = tuple(label_line[7:-1].split('\x00'))
65
    sha1 = sha1_line[6:-1]
0.17.2 by Robert Collins
Core proof of concept working.
66
    for header in lines:
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
67
        op = header[0]
68
        numbers = header[2:]
69
        numbers = [int(n) for n in header[2:].split(',')]
70
        if op == 'c':
71
            result.append((op, numbers[0], numbers[1], None))
72
        else:
73
            contents = [next() for i in xrange(numbers[0])]
74
            result.append((op, None, numbers[0], contents))
0.17.5 by Robert Collins
nograph tests completely passing.
75
    return label, sha1, result
0.17.2 by Robert Collins
Core proof of concept working.
76
77
def apply_delta(basis, delta):
78
    """Apply delta to this object to become new_version_id."""
79
    lines = []
80
    last_offset = 0
81
    # eq ranges occur where gaps occur
82
    # start, end refer to offsets in basis
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
83
    for op, start, count, delta_lines in delta:
84
        if op == 'c':
0.17.12 by Robert Collins
Encode copy ranges as bytes not lines, halves decode overhead.
85
            lines.append(basis[start:start+count])
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
86
        else:
87
            lines.extend(delta_lines)
0.17.2 by Robert Collins
Core proof of concept working.
88
    trim_encoding_newline(lines)
89
    return lines
90
91
92
def trim_encoding_newline(lines):
93
    if lines[-1] == '\n':
94
        del lines[-1]
95
    else:
96
        lines[-1] = lines[-1][:-1]
97
98
99
class GroupCompressor(object):
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
100
    """Produce a serialised group of compressed texts.
101
    
102
    It contains code very similar to SequenceMatcher because of having a similar
103
    task. However some key differences apply:
104
     - there is no junk, we want a minimal edit not a human readable diff.
105
     - we don't filter very common lines (because we don't know where a good
106
       range will start, and after the first text we want to be emitting minmal
107
       edits only.
108
     - we chain the left side, not the right side
109
     - we incrementally update the adjacency matrix as new lines are provided.
110
     - we look for matches in all of the left side, so the routine which does
111
       the analagous task of find_longest_match does not need to filter on the
112
       left side.
113
    """
0.17.2 by Robert Collins
Core proof of concept working.
114
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
115
    _equivalence_table_class = equivalence_table.EquivalenceTable
116
0.17.2 by Robert Collins
Core proof of concept working.
117
    def __init__(self, delta=True):
118
        """Create a GroupCompressor.
119
120
        :paeam delta: If False, do not compress records.
121
        """
122
        self._delta = delta
0.17.12 by Robert Collins
Encode copy ranges as bytes not lines, halves decode overhead.
123
        self.line_offsets = []
0.17.2 by Robert Collins
Core proof of concept working.
124
        self.endpoint = 0
125
        self.input_bytes = 0
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
126
        self.line_locations = self._equivalence_table_class([])
0.18.9 by John Arbash Meinel
If we are going to do it this way, we don't need to explicitly distinguish left and right
127
        self.lines = self.line_locations.lines
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
128
        self.labels_deltas = {}
0.17.2 by Robert Collins
Core proof of concept working.
129
0.17.15 by Robert Collins
Factor out a get_matching_blocks style function.
130
    def get_matching_blocks(self, lines):
131
        """Return an the ranges in lines which match self.lines.
132
133
        :param lines: lines to compress
134
        :return: A list of (old_start, new_start, length) tuples which reflect
135
            a region in self.lines that is present in lines.  The last element
136
            of the list is always (old_len, new_len, 0) to provide a end point
137
            for generating instructions from the matching blocks list.
138
        """
139
        result = []
140
        pos = 0
141
        line_locations = self.line_locations
0.18.11 by John Arbash Meinel
Convert back into grabbing a right-lines ahead of time.
142
        line_locations.set_right_lines(lines)
0.17.15 by Robert Collins
Factor out a get_matching_blocks style function.
143
        # We either copy a range (while there are reusable lines) or we 
144
        # insert new lines. To find reusable lines we traverse 
0.18.24 by John Arbash Meinel
Factor out the most compute intensive portion, with plans to turn it into a compiled func.
145
        locations = None
0.18.26 by John Arbash Meinel
Start with a copy implementation of the _get_longest_match function.
146
        max_pos = len(lines)
0.18.31 by John Arbash Meinel
We had a small bug when we had to rebuild the hash, as we would forget about the non-indexed entries.
147
        max_time = 0.0
148
        max_info = None
0.18.36 by John Arbash Meinel
Small tweak makes a big difference on inventory.py, minor otherwise.
149
        result_append = result.append
0.18.26 by John Arbash Meinel
Start with a copy implementation of the _get_longest_match function.
150
        while pos < max_pos:
0.18.35 by John Arbash Meinel
remove the timing calls
151
            block, pos, locations = _get_longest_match(line_locations, pos,
152
                                                       max_pos, locations)
0.18.25 by John Arbash Meinel
Factor the get_longest_match into a helper func
153
            if block is not None:
0.18.36 by John Arbash Meinel
Small tweak makes a big difference on inventory.py, minor otherwise.
154
                result_append(block)
155
        result_append((len(self.lines), len(lines), 0))
0.17.15 by Robert Collins
Factor out a get_matching_blocks style function.
156
        return result
157
0.17.2 by Robert Collins
Core proof of concept working.
158
    def compress(self, key, lines, expected_sha):
159
        """Compress lines with label key.
160
161
        :param key: A key tuple. It is stored in the output
0.17.26 by Robert Collins
Working better --gc-plain-chk.
162
            for identification of the text during decompression. If the last
163
            element is 'None' it is replaced with the sha1 of the text -
164
            e.g. sha1:xxxxxxx.
0.17.2 by Robert Collins
Core proof of concept working.
165
        :param lines: The lines to be compressed. Must be split
166
            on \n, with the \n preserved.'
167
        :param expected_sha: If non-None, the sha the lines are blieved to
168
            have. During compression the sha is calculated; a mismatch will
169
            cause an error.
170
        :return: The sha1 of lines, and the number of bytes accumulated in
171
            the group output so far.
172
        """
173
        sha1 = sha_strings(lines)
0.17.26 by Robert Collins
Working better --gc-plain-chk.
174
        if key[-1] is None:
175
            key = key[:-1] + ('sha1:' + sha1,)
0.17.2 by Robert Collins
Core proof of concept working.
176
        label = '\x00'.join(key)
177
        # setup good encoding for trailing \n support.
178
        if not lines or lines[-1].endswith('\n'):
179
            lines.append('\n')
180
        else:
181
            lines[-1] = lines[-1] + '\n'
182
        new_lines = []
183
        new_lines.append('label: %s\n' % label)
184
        new_lines.append('sha1: %s\n' % sha1)
0.17.13 by Robert Collins
Do not output copy instructions which take more to encode than a fresh insert. (But do not refer to those insertions when finding ranges to copy: they are not interesting).
185
        index_lines = [False, False]
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
186
        pos = 0
0.17.14 by Robert Collins
Cleaner code.
187
        range_len = 0
188
        range_start = 0
189
        flush_range = self.flush_range
190
        copy_ends = None
0.17.15 by Robert Collins
Factor out a get_matching_blocks style function.
191
        blocks = self.get_matching_blocks(lines)
192
        current_pos = 0
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
193
        # We either copy a range (while there are reusable lines) or we 
194
        # insert new lines. To find reusable lines we traverse 
0.17.15 by Robert Collins
Factor out a get_matching_blocks style function.
195
        for old_start, new_start, range_len in blocks:
196
            if new_start != current_pos:
197
                # non-matching region
0.19.1 by Robert Collins
Start to simplify flush_range.
198
                flush_range(current_pos, None, new_start - current_pos,
0.17.15 by Robert Collins
Factor out a get_matching_blocks style function.
199
                    lines, new_lines, index_lines)
200
            current_pos = new_start + range_len
201
            if not range_len:
202
                continue
0.19.1 by Robert Collins
Start to simplify flush_range.
203
            flush_range(new_start, old_start, range_len, lines,
204
                new_lines, index_lines)
0.18.9 by John Arbash Meinel
If we are going to do it this way, we don't need to explicitly distinguish left and right
205
        delta_start = (self.endpoint, len(self.lines))
0.17.13 by Robert Collins
Do not output copy instructions which take more to encode than a fresh insert. (But do not refer to those insertions when finding ranges to copy: they are not interesting).
206
        self.output_lines(new_lines, index_lines)
0.17.2 by Robert Collins
Core proof of concept working.
207
        trim_encoding_newline(lines)
208
        self.input_bytes += sum(map(len, lines))
0.18.9 by John Arbash Meinel
If we are going to do it this way, we don't need to explicitly distinguish left and right
209
        delta_end = (self.endpoint, len(self.lines))
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
210
        self.labels_deltas[key] = (delta_start, delta_end)
0.17.2 by Robert Collins
Core proof of concept working.
211
        return sha1, self.endpoint
212
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
213
    def extract(self, key):
0.17.12 by Robert Collins
Encode copy ranges as bytes not lines, halves decode overhead.
214
        """Extract a key previously added to the compressor.
215
        
216
        :param key: The key to extract.
217
        :return: An iterable over bytes and the sha1.
218
        """
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
219
        delta_details = self.labels_deltas[key]
220
        delta_lines = self.lines[delta_details[0][1]:delta_details[1][1]]
221
        label, sha1, delta = parse(delta_lines)
222
        if label != key:
223
            raise AssertionError("wrong key: %r, wanted %r" % (label, key))
0.17.12 by Robert Collins
Encode copy ranges as bytes not lines, halves decode overhead.
224
        # Perhaps we want to keep the line offsets too in memory at least?
225
        lines = apply_delta(''.join(self.lines), delta)
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
226
        sha1 = sha_strings(lines)
227
        return lines, sha1
228
0.19.1 by Robert Collins
Start to simplify flush_range.
229
    def flush_range(self, range_start, copy_start, range_len, lines, new_lines, index_lines):
0.17.14 by Robert Collins
Cleaner code.
230
        insert_instruction = "i,%d\n" % range_len
0.19.1 by Robert Collins
Start to simplify flush_range.
231
        if copy_start is not None:
0.17.14 by Robert Collins
Cleaner code.
232
            # range stops, flush and start a new copy range
233
            stop_byte = self.line_offsets[copy_start + range_len - 1]
234
            if copy_start == 0:
235
                start_byte = 0
236
            else:
237
                start_byte = self.line_offsets[copy_start - 1]
238
            bytes = stop_byte - start_byte
239
            copy_control_instruction = "c,%d,%d\n" % (start_byte, bytes)
240
            if (bytes + len(insert_instruction) >
241
                len(copy_control_instruction)):
242
                new_lines.append(copy_control_instruction)
243
                index_lines.append(False)
244
                return
245
        # not copying, or inserting is shorter than copying, so insert.
246
        new_lines.append(insert_instruction)
247
        new_lines.extend(lines[range_start:range_start+range_len])
248
        index_lines.append(False)
0.19.1 by Robert Collins
Start to simplify flush_range.
249
        index_lines.extend([copy_start is None]*range_len)
0.17.14 by Robert Collins
Cleaner code.
250
0.17.13 by Robert Collins
Do not output copy instructions which take more to encode than a fresh insert. (But do not refer to those insertions when finding ranges to copy: they are not interesting).
251
    def output_lines(self, new_lines, index_lines):
252
        """Output some lines.
253
254
        :param new_lines: The lines to output.
255
        :param index_lines: A boolean flag for each line - when True, index
256
            that line.
257
        """
0.18.31 by John Arbash Meinel
We had a small bug when we had to rebuild the hash, as we would forget about the non-indexed entries.
258
        # indexed_newlines = [idx for idx, val in enumerate(index_lines)
259
        #                          if val and new_lines[idx] == '\n']
260
        # if indexed_newlines:
261
        #     import pdb; pdb.set_trace()
0.17.12 by Robert Collins
Encode copy ranges as bytes not lines, halves decode overhead.
262
        endpoint = self.endpoint
0.18.9 by John Arbash Meinel
If we are going to do it this way, we don't need to explicitly distinguish left and right
263
        self.line_locations.extend_lines(new_lines, index_lines)
0.18.6 by John Arbash Meinel
Use the new EquivalenceTable to track the lines.
264
        for line in new_lines:
0.17.12 by Robert Collins
Encode copy ranges as bytes not lines, halves decode overhead.
265
            endpoint += len(line)
266
            self.line_offsets.append(endpoint)
267
        self.endpoint = endpoint
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
268
0.17.2 by Robert Collins
Core proof of concept working.
269
    def ratio(self):
270
        """Return the overall compression ratio."""
271
        return float(self.input_bytes) / float(self.endpoint)
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
272
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
273
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
274
def make_pack_factory(graph, delta, keylength):
275
    """Create a factory for creating a pack based groupcompress.
276
277
    This is only functional enough to run interface tests, it doesn't try to
278
    provide a full pack environment.
279
    
280
    :param graph: Store a graph.
281
    :param delta: Delta compress contents.
282
    :param keylength: How long should keys be.
283
    """
284
    def factory(transport):
285
        parents = graph or delta
286
        ref_length = 0
287
        if graph:
288
            ref_length += 1
0.17.7 by Robert Collins
Update for current index2 changes.
289
        graph_index = BTreeBuilder(reference_lists=ref_length,
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
290
            key_elements=keylength)
291
        stream = transport.open_write_stream('newpack')
292
        writer = pack.ContainerWriter(stream.write)
293
        writer.begin()
294
        index = _GCGraphIndex(graph_index, lambda:True, parents=parents,
0.17.9 by Robert Collins
Initial stab at repository format support.
295
            add_callback=graph_index.add_nodes)
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
296
        access = _DirectPackAccess({})
297
        access.set_writer(writer, graph_index, (transport, 'newpack'))
0.17.2 by Robert Collins
Core proof of concept working.
298
        result = GroupCompressVersionedFiles(index, access, delta)
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
299
        result.stream = stream
300
        result.writer = writer
301
        return result
302
    return factory
303
304
305
def cleanup_pack_group(versioned_files):
0.17.23 by Robert Collins
Only decompress as much of the zlib data as is needed to read the text recipe.
306
    versioned_files.writer.end()
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
307
    versioned_files.stream.close()
308
309
310
class GroupCompressVersionedFiles(VersionedFiles):
311
    """A group-compress based VersionedFiles implementation."""
312
0.17.2 by Robert Collins
Core proof of concept working.
313
    def __init__(self, index, access, delta=True):
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
314
        """Create a GroupCompressVersionedFiles object.
315
316
        :param index: The index object storing access and graph data.
317
        :param access: The access object storing raw data.
0.17.2 by Robert Collins
Core proof of concept working.
318
        :param delta: Whether to delta compress or just entropy compress.
319
        """
320
        self._index = index
321
        self._access = access
322
        self._delta = delta
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
323
        self._unadded_refs = {}
0.17.24 by Robert Collins
Add a group cache to decompression, 5 times faster than knit at decompression when accessing everything in a group.
324
        self._group_cache = LRUSizeCache(max_size=50*1024*1024)
0.17.2 by Robert Collins
Core proof of concept working.
325
326
    def add_lines(self, key, parents, lines, parent_texts=None,
327
        left_matching_blocks=None, nostore_sha=None, random_id=False,
328
        check_content=True):
329
        """Add a text to the store.
330
331
        :param key: The key tuple of the text to add.
332
        :param parents: The parents key tuples of the text to add.
333
        :param lines: A list of lines. Each line must be a bytestring. And all
334
            of them except the last must be terminated with \n and contain no
335
            other \n's. The last line may either contain no \n's or a single
336
            terminating \n. If the lines list does meet this constraint the add
337
            routine may error or may succeed - but you will be unable to read
338
            the data back accurately. (Checking the lines have been split
339
            correctly is expensive and extremely unlikely to catch bugs so it
340
            is not done at runtime unless check_content is True.)
341
        :param parent_texts: An optional dictionary containing the opaque 
342
            representations of some or all of the parents of version_id to
343
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
344
            returned by add_lines or data corruption can be caused.
345
        :param left_matching_blocks: a hint about which areas are common
346
            between the text and its left-hand-parent.  The format is
347
            the SequenceMatcher.get_matching_blocks format.
348
        :param nostore_sha: Raise ExistingContent and do not add the lines to
349
            the versioned file if the digest of the lines matches this.
350
        :param random_id: If True a random id has been selected rather than
351
            an id determined by some deterministic process such as a converter
352
            from a foreign VCS. When True the backend may choose not to check
353
            for uniqueness of the resulting key within the versioned file, so
354
            this should only be done when the result is expected to be unique
355
            anyway.
356
        :param check_content: If True, the lines supplied are verified to be
357
            bytestrings that are correctly formed lines.
358
        :return: The text sha1, the number of bytes in the text, and an opaque
359
                 representation of the inserted version which can be provided
360
                 back to future add_lines calls in the parent_texts dictionary.
361
        """
362
        self._index._check_write_ok()
363
        self._check_add(key, lines, random_id, check_content)
364
        if parents is None:
365
            # The caller might pass None if there is no graph data, but kndx
366
            # indexes can't directly store that, so we give them
367
            # an empty tuple instead.
368
            parents = ()
369
        # double handling for now. Make it work until then.
370
        bytes = ''.join(lines)
371
        record = FulltextContentFactory(key, parents, None, bytes)
0.17.5 by Robert Collins
nograph tests completely passing.
372
        sha1 = list(self._insert_record_stream([record], random_id=random_id))[0]
0.17.2 by Robert Collins
Core proof of concept working.
373
        return sha1, len(bytes), None
374
0.17.4 by Robert Collins
Annotate.
375
    def annotate(self, key):
376
        """See VersionedFiles.annotate."""
377
        graph = Graph(self)
0.17.5 by Robert Collins
nograph tests completely passing.
378
        parent_map = self.get_parent_map([key])
379
        if not parent_map:
380
            raise errors.RevisionNotPresent(key, self)
381
        if parent_map[key] is not None:
382
            search = graph._make_breadth_first_searcher([key])
383
            keys = set()
384
            while True:
385
                try:
386
                    present, ghosts = search.next_with_ghosts()
387
                except StopIteration:
388
                    break
389
                keys.update(present)
390
            parent_map = self.get_parent_map(keys)
391
        else:
392
            keys = [key]
393
            parent_map = {key:()}
0.17.4 by Robert Collins
Annotate.
394
        head_cache = _mod_graph.FrozenHeadsCache(graph)
395
        parent_cache = {}
396
        reannotate = annotate.reannotate
397
        for record in self.get_record_stream(keys, 'topological', True):
398
            key = record.key
0.20.2 by John Arbash Meinel
Teach groupcompress about 'chunked' encoding
399
            chunks = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
0.17.4 by Robert Collins
Annotate.
400
            parent_lines = [parent_cache[parent] for parent in parent_map[key]]
401
            parent_cache[key] = list(
402
                reannotate(parent_lines, fulltext, key, None, head_cache))
403
        return parent_cache[key]
404
0.17.5 by Robert Collins
nograph tests completely passing.
405
    def check(self, progress_bar=None):
406
        """See VersionedFiles.check()."""
407
        keys = self.keys()
408
        for record in self.get_record_stream(keys, 'unordered', True):
409
            record.get_bytes_as('fulltext')
410
0.17.2 by Robert Collins
Core proof of concept working.
411
    def _check_add(self, key, lines, random_id, check_content):
412
        """check that version_id and lines are safe to add."""
413
        version_id = key[-1]
0.17.26 by Robert Collins
Working better --gc-plain-chk.
414
        if version_id is not None:
415
            if contains_whitespace(version_id):
416
                raise InvalidRevisionId(version_id, self)
0.17.2 by Robert Collins
Core proof of concept working.
417
        self.check_not_reserved_id(version_id)
418
        # TODO: If random_id==False and the key is already present, we should
419
        # probably check that the existing content is identical to what is
420
        # being inserted, and otherwise raise an exception.  This would make
421
        # the bundle code simpler.
422
        if check_content:
423
            self._check_lines_not_unicode(lines)
424
            self._check_lines_are_lines(lines)
425
0.17.5 by Robert Collins
nograph tests completely passing.
426
    def get_parent_map(self, keys):
427
        """Get a map of the parents of keys.
428
429
        :param keys: The keys to look up parents for.
430
        :return: A mapping from keys to parents. Absent keys are absent from
431
            the mapping.
432
        """
433
        result = {}
434
        sources = [self._index]
435
        source_results = []
436
        missing = set(keys)
437
        for source in sources:
438
            if not missing:
439
                break
440
            new_result = source.get_parent_map(missing)
441
            source_results.append(new_result)
442
            result.update(new_result)
443
            missing.difference_update(set(new_result))
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
444
        if self._unadded_refs:
445
            for key in missing:
446
                if key in self._unadded_refs:
447
                    result[key] = self._unadded_refs[key]
0.17.5 by Robert Collins
nograph tests completely passing.
448
        return result
449
450
    def get_record_stream(self, keys, ordering, include_delta_closure):
451
        """Get a stream of records for keys.
452
453
        :param keys: The keys to include.
454
        :param ordering: Either 'unordered' or 'topological'. A topologically
455
            sorted stream has compression parents strictly before their
456
            children.
457
        :param include_delta_closure: If True then the closure across any
458
            compression parents will be included (in the opaque data).
459
        :return: An iterator of ContentFactory objects, each of which is only
460
            valid until the iterator is advanced.
461
        """
462
        # keys might be a generator
463
        keys = set(keys)
464
        if not keys:
465
            return
466
        if not self._index.has_graph:
467
            # Cannot topological order when no graph has been stored.
468
            ordering = 'unordered'
469
        # Cheap: iterate
470
        locations = self._index.get_build_details(keys)
471
        if ordering == 'topological':
472
            # would be better to not globally sort initially but instead
473
            # start with one key, recurse to its oldest parent, then grab
474
            # everything in the same group, etc.
475
            parent_map = dict((key, details[2]) for key, details in
476
                locations.iteritems())
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
477
            local = frozenset(keys).intersection(set(self._unadded_refs))
478
            for key in local:
479
                parent_map[key] = self._unadded_refs[key]
480
                locations[key] = None
0.17.5 by Robert Collins
nograph tests completely passing.
481
            present_keys = topo_sort(parent_map)
482
            # Now group by source:
483
        else:
484
            present_keys = locations.keys()
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
485
            local = frozenset(keys).intersection(set(self._unadded_refs))
486
            for key in local:
487
                present_keys.append(key)
488
                locations[key] = None
0.17.5 by Robert Collins
nograph tests completely passing.
489
        absent_keys = keys.difference(set(locations))
490
        for key in absent_keys:
491
            yield AbsentContentFactory(key)
492
        for key in present_keys:
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
493
            if key in self._unadded_refs:
494
                lines, sha1 = self._compressor.extract(key)
495
                parents = self._unadded_refs[key]
496
            else:
497
                index_memo, _, parents, (method, _) = locations[key]
498
                read_memo = index_memo[0:3]
0.17.24 by Robert Collins
Add a group cache to decompression, 5 times faster than knit at decompression when accessing everything in a group.
499
                # get the group:
500
                try:
501
                    plain = self._group_cache[read_memo]
502
                except KeyError:
503
                    # read the group
504
                    zdata = self._access.get_raw_records([read_memo]).next()
505
                    # decompress - whole thing - this is not a bug, as it
506
                    # permits caching. We might want to store the partially
507
                    # decompresed group and decompress object, so that recent
508
                    # texts are not penalised by big groups.
509
                    decomp = zlib.decompressobj()
510
                    plain = decomp.decompress(zdata) #, index_memo[4])
511
                    self._group_cache[read_memo] = plain
0.17.23 by Robert Collins
Only decompress as much of the zlib data as is needed to read the text recipe.
512
                # cheapo debugging:
513
                # print len(zdata), len(plain)
0.17.24 by Robert Collins
Add a group cache to decompression, 5 times faster than knit at decompression when accessing everything in a group.
514
                # parse - requires split_lines, better to have byte offsets
515
                # here (but not by much - we only split the region for the
516
                # recipe, and we often want to end up with lines anyway.
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
517
                delta_lines = split_lines(plain[index_memo[3]:index_memo[4]])
518
                label, sha1, delta = parse(delta_lines)
519
                if label != key:
520
                    raise AssertionError("wrong key: %r, wanted %r" % (label, key))
0.17.24 by Robert Collins
Add a group cache to decompression, 5 times faster than knit at decompression when accessing everything in a group.
521
                lines = apply_delta(plain, delta)
0.17.5 by Robert Collins
nograph tests completely passing.
522
            bytes = ''.join(lines)
523
            yield FulltextContentFactory(key, parents, sha1, bytes)
524
            
525
    def get_sha1s(self, keys):
526
        """See VersionedFiles.get_sha1s()."""
527
        result = {}
528
        for record in self.get_record_stream(keys, 'unordered', True):
529
            if record.sha1 != None:
530
                result[record.key] = record.sha1
531
            else:
532
                if record.storage_kind != 'absent':
533
                    result[record.key] == sha_string(record.get_bytes_as(
534
                        'fulltext'))
535
        return result
536
0.17.2 by Robert Collins
Core proof of concept working.
537
    def insert_record_stream(self, stream):
538
        """Insert a record stream into this container.
539
540
        :param stream: A stream of records to insert. 
541
        :return: None
542
        :seealso VersionedFiles.get_record_stream:
543
        """
0.17.5 by Robert Collins
nograph tests completely passing.
544
        for _ in self._insert_record_stream(stream):
545
            pass
0.17.2 by Robert Collins
Core proof of concept working.
546
0.17.5 by Robert Collins
nograph tests completely passing.
547
    def _insert_record_stream(self, stream, random_id=False):
0.17.2 by Robert Collins
Core proof of concept working.
548
        """Internal core to insert a record stream into this container.
549
550
        This helper function has a different interface than insert_record_stream
551
        to allow add_lines to be minimal, but still return the needed data.
552
553
        :param stream: A stream of records to insert. 
554
        :return: An iterator over the sha1 of the inserted records.
555
        :seealso insert_record_stream:
556
        :seealso add_lines:
557
        """
0.17.5 by Robert Collins
nograph tests completely passing.
558
        def get_adapter(adapter_key):
559
            try:
560
                return adapters[adapter_key]
561
            except KeyError:
562
                adapter_factory = adapter_registry.get(adapter_key)
563
                adapter = adapter_factory(self)
564
                adapters[adapter_key] = adapter
565
                return adapter
566
        adapters = {}
0.17.2 by Robert Collins
Core proof of concept working.
567
        # This will go up to fulltexts for gc to gc fetching, which isn't
568
        # ideal.
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
569
        self._compressor = GroupCompressor(self._delta)
570
        self._unadded_refs = {}
0.17.5 by Robert Collins
nograph tests completely passing.
571
        keys_to_add = []
572
        basis_end = 0
0.17.6 by Robert Collins
Cap group size at 20MB internal buffer. (Probably way too big).
573
        groups = 1
574
        def flush():
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
575
            compressed = zlib.compress(''.join(self._compressor.lines))
0.17.6 by Robert Collins
Cap group size at 20MB internal buffer. (Probably way too big).
576
            index, start, length = self._access.add_raw_records(
577
                [(None, len(compressed))], compressed)[0]
578
            nodes = []
579
            for key, reads, refs in keys_to_add:
580
                nodes.append((key, "%d %d %s" % (start, length, reads), refs))
581
            self._index.add_records(nodes, random_id=random_id)
0.17.2 by Robert Collins
Core proof of concept working.
582
        for record in stream:
0.17.5 by Robert Collins
nograph tests completely passing.
583
            # Raise an error when a record is missing.
584
            if record.storage_kind == 'absent':
585
                raise errors.RevisionNotPresent([record.key], self)
0.20.2 by John Arbash Meinel
Teach groupcompress about 'chunked' encoding
586
            elif record.storage_kind in ('chunked', 'fulltext'):
587
                lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
0.17.5 by Robert Collins
nograph tests completely passing.
588
            else:
589
                adapter_key = record.storage_kind, 'fulltext'
590
                adapter = get_adapter(adapter_key)
591
                bytes = adapter.get_bytes(record,
592
                    record.get_bytes_as(record.storage_kind))
0.20.2 by John Arbash Meinel
Teach groupcompress about 'chunked' encoding
593
                lines = osutils.split_lines(bytes)
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
594
            found_sha1, end_point = self._compressor.compress(record.key,
0.20.2 by John Arbash Meinel
Teach groupcompress about 'chunked' encoding
595
                lines, record.sha1)
0.17.26 by Robert Collins
Working better --gc-plain-chk.
596
            if record.key[-1] is None:
597
                key = record.key[:-1] + ('sha1:' + found_sha1,)
598
            else:
599
                key = record.key
600
            self._unadded_refs[key] = record.parents
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
601
            yield found_sha1
0.17.26 by Robert Collins
Working better --gc-plain-chk.
602
            keys_to_add.append((key, '%d %d' % (basis_end, end_point),
0.17.5 by Robert Collins
nograph tests completely passing.
603
                (record.parents,)))
604
            basis_end = end_point
0.17.6 by Robert Collins
Cap group size at 20MB internal buffer. (Probably way too big).
605
            if basis_end > 1024 * 1024 * 20:
606
                flush()
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
607
                self._compressor = GroupCompressor(self._delta)
608
                self._unadded_refs = {}
0.17.6 by Robert Collins
Cap group size at 20MB internal buffer. (Probably way too big).
609
                keys_to_add = []
610
                basis_end = 0
611
                groups += 1
0.17.8 by Robert Collins
Flush pending updates at the end of _insert_record_stream
612
        if len(keys_to_add):
613
            flush()
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
614
        self._compressor = None
615
        self._unadded_refs = {}
0.17.5 by Robert Collins
nograph tests completely passing.
616
617
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
618
        """Iterate over the lines in the versioned files from keys.
619
620
        This may return lines from other keys. Each item the returned
621
        iterator yields is a tuple of a line and a text version that that line
622
        is present in (not introduced in).
623
624
        Ordering of results is in whatever order is most suitable for the
625
        underlying storage format.
626
627
        If a progress bar is supplied, it may be used to indicate progress.
628
        The caller is responsible for cleaning up progress bars (because this
629
        is an iterator).
630
631
        NOTES:
632
         * Lines are normalised by the underlying store: they will all have \n
633
           terminators.
634
         * Lines are returned in arbitrary order.
635
636
        :return: An iterator over (line, key).
637
        """
638
        if pb is None:
639
            pb = progress.DummyProgress()
640
        keys = set(keys)
641
        total = len(keys)
642
        # we don't care about inclusions, the caller cares.
643
        # but we need to setup a list of records to visit.
644
        # we need key, position, length
645
        for key_idx, record in enumerate(self.get_record_stream(keys,
646
            'unordered', True)):
647
            # XXX: todo - optimise to use less than full texts.
648
            key = record.key
649
            pb.update('Walking content.', key_idx, total)
650
            if record.storage_kind == 'absent':
651
                raise errors.RevisionNotPresent(record.key, self)
652
            lines = split_lines(record.get_bytes_as('fulltext'))
653
            for line in lines:
654
                yield line, key
655
        pb.update('Walking content.', total, total)
656
657
    def keys(self):
658
        """See VersionedFiles.keys."""
659
        if 'evil' in debug.debug_flags:
660
            trace.mutter_callsite(2, "keys scales with size of history")
661
        sources = [self._index]
662
        result = set()
663
        for source in sources:
664
            result.update(source.keys())
665
        return result
666
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
667
668
class _GCGraphIndex(object):
669
    """Mapper from GroupCompressVersionedFiles needs into GraphIndex storage."""
670
0.17.9 by Robert Collins
Initial stab at repository format support.
671
    def __init__(self, graph_index, is_locked, parents=True,
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
672
        add_callback=None):
673
        """Construct a _GCGraphIndex on a graph_index.
674
675
        :param graph_index: An implementation of bzrlib.index.GraphIndex.
676
        :param is_locked: A callback to check whether the object should answer
677
            queries.
678
        :param parents: If True, record knits parents, if not do not record 
679
            parents.
680
        :param add_callback: If not None, allow additions to the index and call
681
            this callback with a list of added GraphIndex nodes:
682
            [(node, value, node_refs), ...]
683
        :param is_locked: A callback, returns True if the index is locked and
684
            thus usable.
685
        """
686
        self._add_callback = add_callback
687
        self._graph_index = graph_index
688
        self._parents = parents
689
        self.has_graph = parents
690
        self._is_locked = is_locked
691
0.17.5 by Robert Collins
nograph tests completely passing.
692
    def add_records(self, records, random_id=False):
693
        """Add multiple records to the index.
694
        
695
        This function does not insert data into the Immutable GraphIndex
696
        backing the KnitGraphIndex, instead it prepares data for insertion by
697
        the caller and checks that it is safe to insert then calls
698
        self._add_callback with the prepared GraphIndex nodes.
699
700
        :param records: a list of tuples:
701
                         (key, options, access_memo, parents).
702
        :param random_id: If True the ids being added were randomly generated
703
            and no check for existence will be performed.
704
        """
705
        if not self._add_callback:
706
            raise errors.ReadOnlyError(self)
707
        # we hope there are no repositories with inconsistent parentage
708
        # anymore.
709
710
        changed = False
711
        keys = {}
712
        for (key, value, refs) in records:
713
            if not self._parents:
714
                if refs:
715
                    for ref in refs:
716
                        if ref:
717
                            raise KnitCorrupt(self,
718
                                "attempt to add node with parents "
719
                                "in parentless index.")
720
                    refs = ()
721
                    changed = True
722
            keys[key] = (value, refs)
723
        # check for dups
724
        if not random_id:
725
            present_nodes = self._get_entries(keys)
726
            for (index, key, value, node_refs) in present_nodes:
727
                if node_refs != keys[key][1]:
728
                    raise errors.KnitCorrupt(self, "inconsistent details in add_records"
729
                        ": %s %s" % ((value, node_refs), keys[key]))
730
                del keys[key]
731
                changed = True
732
        if changed:
733
            result = []
734
            if self._parents:
735
                for key, (value, node_refs) in keys.iteritems():
736
                    result.append((key, value, node_refs))
737
            else:
738
                for key, (value, node_refs) in keys.iteritems():
739
                    result.append((key, value))
740
            records = result
741
        self._add_callback(records)
742
        
743
    def _check_read(self):
744
        """raise if reads are not permitted."""
745
        if not self._is_locked():
746
            raise errors.ObjectNotLocked(self)
747
0.17.2 by Robert Collins
Core proof of concept working.
748
    def _check_write_ok(self):
749
        """Assert if writes are not permitted."""
750
        if not self._is_locked():
751
            raise errors.ObjectNotLocked(self)
752
0.17.5 by Robert Collins
nograph tests completely passing.
753
    def _get_entries(self, keys, check_present=False):
754
        """Get the entries for keys.
755
        
756
        :param keys: An iterable of index key tuples.
757
        """
758
        keys = set(keys)
759
        found_keys = set()
760
        if self._parents:
761
            for node in self._graph_index.iter_entries(keys):
762
                yield node
763
                found_keys.add(node[1])
764
        else:
765
            # adapt parentless index to the rest of the code.
766
            for node in self._graph_index.iter_entries(keys):
767
                yield node[0], node[1], node[2], ()
768
                found_keys.add(node[1])
769
        if check_present:
770
            missing_keys = keys.difference(found_keys)
771
            if missing_keys:
772
                raise RevisionNotPresent(missing_keys.pop(), self)
773
774
    def get_parent_map(self, keys):
775
        """Get a map of the parents of keys.
776
777
        :param keys: The keys to look up parents for.
778
        :return: A mapping from keys to parents. Absent keys are absent from
779
            the mapping.
780
        """
781
        self._check_read()
782
        nodes = self._get_entries(keys)
783
        result = {}
784
        if self._parents:
785
            for node in nodes:
786
                result[node[1]] = node[3][0]
787
        else:
788
            for node in nodes:
789
                result[node[1]] = None
790
        return result
791
792
    def get_build_details(self, keys):
793
        """Get the various build details for keys.
794
795
        Ghosts are omitted from the result.
796
797
        :param keys: An iterable of keys.
798
        :return: A dict of key:
799
            (index_memo, compression_parent, parents, record_details).
800
            index_memo
801
                opaque structure to pass to read_records to extract the raw
802
                data
803
            compression_parent
804
                Content that this record is built upon, may be None
805
            parents
806
                Logical parents of this node
807
            record_details
808
                extra information about the content which needs to be passed to
809
                Factory.parse_record
810
        """
811
        self._check_read()
812
        result = {}
813
        entries = self._get_entries(keys, False)
814
        for entry in entries:
815
            key = entry[1]
816
            if not self._parents:
817
                parents = None
818
            else:
819
                parents = entry[3][0]
820
            value = entry[2]
821
            method = 'group'
822
            result[key] = (self._node_to_position(entry),
823
                                  None, parents, (method, None))
824
        return result
825
    
826
    def keys(self):
827
        """Get all the keys in the collection.
828
        
829
        The keys are not ordered.
830
        """
831
        self._check_read()
832
        return [node[1] for node in self._graph_index.iter_all_entries()]
833
    
834
    def _node_to_position(self, node):
835
        """Convert an index value to position details."""
836
        bits = node[2].split(' ')
837
        # It would be nice not to read the entire gzip.
838
        start = int(bits[0])
839
        stop = int(bits[1])
840
        basis_end = int(bits[2])
841
        delta_end = int(bits[3])
842
        return node[0], start, stop, basis_end, delta_end
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
843
844
0.18.26 by John Arbash Meinel
Start with a copy implementation of the _get_longest_match function.
845
def _get_longest_match(equivalence_table, pos, max_pos, locations):
0.18.25 by John Arbash Meinel
Factor the get_longest_match into a helper func
846
    """Get the longest possible match for the current position."""
847
    range_start = pos
848
    range_len = 0
849
    copy_ends = None
0.18.26 by John Arbash Meinel
Start with a copy implementation of the _get_longest_match function.
850
    while pos < max_pos:
0.18.25 by John Arbash Meinel
Factor the get_longest_match into a helper func
851
        if locations is None:
852
            locations = equivalence_table.get_idx_matches(pos)
853
        if locations is None:
854
            # No more matches, just return whatever we have, but we know that
855
            # this last position is not going to match anything
856
            pos += 1
857
            break
858
        else:
859
            if copy_ends is None:
860
                # We are starting a new range
861
                copy_ends = [loc + 1 for loc in locations]
862
                range_len = 1
863
                locations = None # Consumed
864
            else:
865
                # We are currently in the middle of a match
866
                next_locations = set(copy_ends).intersection(locations)
867
                if len(next_locations):
868
                    # range continues
869
                    copy_ends = [loc + 1 for loc in next_locations]
870
                    range_len += 1
871
                    locations = None # Consumed
872
                else:
873
                    # But we are done with this match, we should be
874
                    # starting a new one, though. We will pass back 'locations'
875
                    # so that we don't have to do another lookup.
876
                    break
877
        pos += 1
878
    if copy_ends is None:
879
        return None, pos, locations
880
    return ((min(copy_ends) - range_len, range_start, range_len)), pos, locations
881
882
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
883
try:
884
    from bzrlib.plugins.groupcompress import _groupcompress_c
885
except ImportError:
886
    pass
887
else:
888
    GroupCompressor._equivalence_table_class = _groupcompress_c.EquivalenceTable
0.18.29 by John Arbash Meinel
Implement _get_longest_match in Pyrex.
889
    _get_longest_match = _groupcompress_c._get_longest_match