/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1
# Copyright (C) 2008, 2009 Canonical Ltd
2
#
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
3
# This program is free software; you can redistribute it and/or modify
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
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
#
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
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.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
12
#
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
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
3735.36.3 by John Arbash Meinel
Add the new address for FSF to the new files.
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
16
17
"""Core compression logic for compressing streams of related files."""
18
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
19
import time
0.17.5 by Robert Collins
nograph tests completely passing.
20
import zlib
0.17.44 by John Arbash Meinel
Use the bit field to allow both lzma groups and zlib groups.
21
try:
22
    import pylzma
23
except ImportError:
24
    pylzma = None
0.17.5 by Robert Collins
nograph tests completely passing.
25
0.17.4 by Robert Collins
Annotate.
26
from bzrlib import (
27
    annotate,
0.17.5 by Robert Collins
nograph tests completely passing.
28
    debug,
29
    errors,
0.17.4 by Robert Collins
Annotate.
30
    graph as _mod_graph,
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
31
    knit,
0.20.2 by John Arbash Meinel
Teach groupcompress about 'chunked' encoding
32
    osutils,
0.17.4 by Robert Collins
Annotate.
33
    pack,
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
34
    trace,
0.17.4 by Robert Collins
Annotate.
35
    )
36
from bzrlib.graph import Graph
0.17.21 by Robert Collins
Update groupcompress to bzrlib 1.10.
37
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.
38
from bzrlib.lru_cache import LRUSizeCache
0.17.9 by Robert Collins
Initial stab at repository format support.
39
from bzrlib.tsort import topo_sort
0.17.2 by Robert Collins
Core proof of concept working.
40
from bzrlib.versionedfile import (
0.17.5 by Robert Collins
nograph tests completely passing.
41
    adapter_registry,
42
    AbsentContentFactory,
0.20.5 by John Arbash Meinel
Finish the Fulltext => Chunked conversions so that we work in the more-efficient Chunks.
43
    ChunkedContentFactory,
0.17.2 by Robert Collins
Core proof of concept working.
44
    FulltextContentFactory,
45
    VersionedFiles,
46
    )
47
0.17.44 by John Arbash Meinel
Use the bit field to allow both lzma groups and zlib groups.
48
_USE_LZMA = False and (pylzma is not None)
0.17.2 by Robert Collins
Core proof of concept working.
49
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
50
# osutils.sha_string('')
51
_null_sha1 = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'
52
53
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
54
def sort_gc_optimal(parent_map):
3735.31.14 by John Arbash Meinel
Change the gc-optimal to 'groupcompress'
55
    """Sort and group the keys in parent_map into groupcompress order.
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
56
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
57
    groupcompress is defined (currently) as reverse-topological order, grouped
58
    by the key prefix.
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
59
60
    :return: A sorted-list of keys
61
    """
3735.31.14 by John Arbash Meinel
Change the gc-optimal to 'groupcompress'
62
    # groupcompress ordering is approximately reverse topological,
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
63
    # properly grouped by file-id.
0.20.23 by John Arbash Meinel
Add a progress indicator for chk pages.
64
    per_prefix_map = {}
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
65
    for item in parent_map.iteritems():
66
        key = item[0]
67
        if isinstance(key, str) or len(key) == 1:
0.20.23 by John Arbash Meinel
Add a progress indicator for chk pages.
68
            prefix = ''
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
69
        else:
0.20.23 by John Arbash Meinel
Add a progress indicator for chk pages.
70
            prefix = key[0]
71
        try:
72
            per_prefix_map[prefix].append(item)
73
        except KeyError:
74
            per_prefix_map[prefix] = [item]
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
75
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
76
    present_keys = []
0.20.11 by John Arbash Meinel
start experimenting with gc-optimal ordering.
77
    for prefix in sorted(per_prefix_map):
78
        present_keys.extend(reversed(topo_sort(per_prefix_map[prefix])))
79
    return present_keys
80
81
3735.32.9 by John Arbash Meinel
Use a 32kB extension, since that is the max window size for zlib.
82
# The max zlib window size is 32kB, so if we set 'max_size' output of the
83
# decompressor to the requested bytes + 32kB, then we should guarantee
84
# num_bytes coming out.
85
_ZLIB_DECOMP_WINDOW = 32*1024
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
86
87
class GroupCompressBlock(object):
88
    """An object which maintains the internal structure of the compressed data.
89
90
    This tracks the meta info (start of text, length, type, etc.)
91
    """
92
0.25.5 by John Arbash Meinel
Now using a zlib compressed format.
93
    # Group Compress Block v1 Zlib
94
    GCB_HEADER = 'gcb1z\n'
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
95
    # Group Compress Block v1 Lzma
0.17.44 by John Arbash Meinel
Use the bit field to allow both lzma groups and zlib groups.
96
    GCB_LZ_HEADER = 'gcb1l\n'
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
97
    GCB_KNOWN_HEADERS = (GCB_HEADER, GCB_LZ_HEADER)
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
98
99
    def __init__(self):
100
        # map by key? or just order in file?
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
101
        self._compressor_name = None
3735.32.5 by John Arbash Meinel
Change the parsing code to start out just holding the compressed bytes.
102
        self._z_content = None
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
103
        self._z_content_decompressor = None
3735.32.5 by John Arbash Meinel
Change the parsing code to start out just holding the compressed bytes.
104
        self._z_content_length = None
105
        self._content_length = None
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
106
        self._content = None
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
107
        self._content_chunks = None
3735.32.5 by John Arbash Meinel
Change the parsing code to start out just holding the compressed bytes.
108
109
    def __len__(self):
3735.38.4 by John Arbash Meinel
Another disk format change.
110
        # This is the maximum number of bytes this object will reference if
111
        # everything is decompressed. However, if we decompress less than
112
        # everything... (this would cause some problems for LRUSizeCache)
113
        return self._content_length + self._z_content_length
0.17.48 by John Arbash Meinel
if _NO_LABELS is set, don't bother parsing the mini header.
114
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
115
    def _ensure_content(self, num_bytes=None):
116
        """Make sure that content has been expanded enough.
117
118
        :param num_bytes: Ensure that we have extracted at least num_bytes of
119
            content. If None, consume everything
120
        """
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
121
        # TODO: If we re-use the same content block at different times during
122
        #       get_record_stream(), it is possible that the first pass will
123
        #       get inserted, triggering an extract/_ensure_content() which
124
        #       will get rid of _z_content. And then the next use of the block
125
        #       will try to access _z_content (to send it over the wire), and
126
        #       fail because it is already extracted. Consider never releasing
127
        #       _z_content because of this.
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
128
        if num_bytes is None:
129
            num_bytes = self._content_length
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
130
        elif (self._content_length is not None
131
              and num_bytes > self._content_length):
132
            raise AssertionError(
133
                'requested num_bytes (%d) > content length (%d)'
134
                % (num_bytes, self._content_length))
135
        # Expand the content if required
3735.32.6 by John Arbash Meinel
A bit of reworking changes things so content is expanded at extract() time.
136
        if self._content is None:
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
137
            if self._content_chunks is not None:
138
                self._content = ''.join(self._content_chunks)
139
                self._content_chunks = None
140
        if self._content is None:
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
141
            if self._z_content is None:
142
                raise AssertionError('No content to decompress')
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
143
            if self._z_content == '':
144
                self._content = ''
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
145
            elif self._compressor_name == 'lzma':
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
146
                # We don't do partial lzma decomp yet
3735.2.160 by John Arbash Meinel
Fix a trivial typo
147
                self._content = pylzma.decompress(self._z_content)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
148
            elif self._compressor_name == 'zlib':
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
149
                # Start a zlib decompressor
3735.32.27 by John Arbash Meinel
Have _LazyGroupContentManager pre-extract everything it holds.
150
                if num_bytes is None:
151
                    self._content = zlib.decompress(self._z_content)
152
                else:
153
                    self._z_content_decompressor = zlib.decompressobj()
154
                    # Seed the decompressor with the uncompressed bytes, so
155
                    # that the rest of the code is simplified
156
                    self._content = self._z_content_decompressor.decompress(
157
                        self._z_content, num_bytes + _ZLIB_DECOMP_WINDOW)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
158
            else:
3735.2.182 by Matt Nordhoff
Improve an assertion message slightly, and fix typos in 2 others
159
                raise AssertionError('Unknown compressor: %r'
3735.2.183 by John Arbash Meinel
Fix the compressor name.
160
                                     % self._compressor_name)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
161
        # Any bytes remaining to be decompressed will be in the decompressors
162
        # 'unconsumed_tail'
163
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
164
        # Do we have enough bytes already?
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
165
        if num_bytes is not None and len(self._content) >= num_bytes:
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
166
            return
3735.32.27 by John Arbash Meinel
Have _LazyGroupContentManager pre-extract everything it holds.
167
        if num_bytes is None and self._z_content_decompressor is None:
168
            # We must have already decompressed everything
169
            return
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
170
        # If we got this far, and don't have a decompressor, something is wrong
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
171
        if self._z_content_decompressor is None:
172
            raise AssertionError(
3735.2.182 by Matt Nordhoff
Improve an assertion message slightly, and fix typos in 2 others
173
                'No decompressor to decompress %d bytes' % num_bytes)
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
174
        remaining_decomp = self._z_content_decompressor.unconsumed_tail
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
175
        if num_bytes is None:
176
            if remaining_decomp:
177
                # We don't know how much is left, but we'll decompress it all
178
                self._content += self._z_content_decompressor.decompress(
179
                    remaining_decomp)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
180
                # Note: There's what I consider a bug in zlib.decompressobj
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
181
                #       If you pass back in the entire unconsumed_tail, only
182
                #       this time you don't pass a max-size, it doesn't
183
                #       change the unconsumed_tail back to None/''.
184
                #       However, we know we are done with the whole stream
185
                self._z_content_decompressor = None
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
186
            # XXX: Why is this the only place in this routine we set this?
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
187
            self._content_length = len(self._content)
188
        else:
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
189
            if not remaining_decomp:
190
                raise AssertionError('Nothing left to decompress')
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
191
            needed_bytes = num_bytes - len(self._content)
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
192
            # We always set max_size to 32kB over the minimum needed, so that
193
            # zlib will give us as much as we really want.
194
            # TODO: If this isn't good enough, we could make a loop here,
195
            #       that keeps expanding the request until we get enough
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
196
            self._content += self._z_content_decompressor.decompress(
197
                remaining_decomp, needed_bytes + _ZLIB_DECOMP_WINDOW)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
198
            if len(self._content) < num_bytes:
199
                raise AssertionError('%d bytes wanted, only %d available'
200
                                     % (num_bytes, len(self._content)))
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
201
            if not self._z_content_decompressor.unconsumed_tail:
202
                # The stream is finished
203
                self._z_content_decompressor = None
3735.32.6 by John Arbash Meinel
A bit of reworking changes things so content is expanded at extract() time.
204
3735.38.4 by John Arbash Meinel
Another disk format change.
205
    def _parse_bytes(self, bytes, pos):
3735.32.5 by John Arbash Meinel
Change the parsing code to start out just holding the compressed bytes.
206
        """Read the various lengths from the header.
207
208
        This also populates the various 'compressed' buffers.
209
210
        :return: The position in bytes just after the last newline
211
        """
3735.38.4 by John Arbash Meinel
Another disk format change.
212
        # At present, we have 2 integers for the compressed and uncompressed
213
        # content. In base10 (ascii) 14 bytes can represent > 1TB, so to avoid
214
        # checking too far, cap the search to 14 bytes.
215
        pos2 = bytes.index('\n', pos, pos + 14)
216
        self._z_content_length = int(bytes[pos:pos2])
217
        pos = pos2 + 1
218
        pos2 = bytes.index('\n', pos, pos + 14)
219
        self._content_length = int(bytes[pos:pos2])
220
        pos = pos2 + 1
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
221
        if len(bytes) != (pos + self._z_content_length):
222
            # XXX: Define some GCCorrupt error ?
223
            raise AssertionError('Invalid bytes: (%d) != %d + %d' %
224
                                 (len(bytes), pos, self._z_content_length))
3735.38.4 by John Arbash Meinel
Another disk format change.
225
        self._z_content = bytes[pos:]
3735.32.5 by John Arbash Meinel
Change the parsing code to start out just holding the compressed bytes.
226
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
227
    @classmethod
228
    def from_bytes(cls, bytes):
229
        out = cls()
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
230
        if bytes[:6] not in cls.GCB_KNOWN_HEADERS:
231
            raise ValueError('bytes did not start with any of %r'
232
                             % (cls.GCB_KNOWN_HEADERS,))
233
        # XXX: why not testing the whole header ?
0.17.44 by John Arbash Meinel
Use the bit field to allow both lzma groups and zlib groups.
234
        if bytes[4] == 'z':
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
235
            out._compressor_name = 'zlib'
0.17.45 by John Arbash Meinel
Just make sure we have the right decompressor
236
        elif bytes[4] == 'l':
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
237
            out._compressor_name = 'lzma'
0.17.45 by John Arbash Meinel
Just make sure we have the right decompressor
238
        else:
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
239
            raise ValueError('unknown compressor: %r' % (bytes,))
3735.38.4 by John Arbash Meinel
Another disk format change.
240
        out._parse_bytes(bytes, 6)
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
241
        return out
242
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
243
    def extract(self, key, start, end, sha1=None):
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
244
        """Extract the text for a specific key.
245
246
        :param key: The label used for this content
247
        :param sha1: TODO (should we validate only when sha1 is supplied?)
248
        :return: The bytes for the content
249
        """
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
250
        if start == end == 0:
3735.2.158 by John Arbash Meinel
Remove support for passing None for end in GroupCompressBlock.extract.
251
            return ''
252
        self._ensure_content(end)
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
253
        # The bytes are 'f' or 'd' for the type, then a variable-length
254
        # base128 integer for the content size, then the actual content
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
255
        # We know that the variable-length integer won't be longer than 5
256
        # bytes (it takes 5 bytes to encode 2^32)
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
257
        c = self._content[start]
258
        if c == 'f':
259
            type = 'fulltext'
0.17.36 by John Arbash Meinel
Adding a mini-len to the delta/fulltext bytes
260
        else:
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
261
            if c != 'd':
262
                raise ValueError('Unknown content control code: %s'
263
                                 % (c,))
264
            type = 'delta'
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
265
        content_len, len_len = decode_base128_int(
266
                            self._content[start + 1:start + 6])
267
        content_start = start + 1 + len_len
3735.2.158 by John Arbash Meinel
Remove support for passing None for end in GroupCompressBlock.extract.
268
        if end != content_start + content_len:
269
            raise ValueError('end != len according to field header'
270
                ' %s != %s' % (end, content_start + content_len))
0.17.36 by John Arbash Meinel
Adding a mini-len to the delta/fulltext bytes
271
        if c == 'f':
3735.40.19 by John Arbash Meinel
Implement apply_delta_to_source which doesn't have to malloc another string.
272
            bytes = self._content[content_start:end]
0.17.36 by John Arbash Meinel
Adding a mini-len to the delta/fulltext bytes
273
        elif c == 'd':
3735.40.19 by John Arbash Meinel
Implement apply_delta_to_source which doesn't have to malloc another string.
274
            bytes = apply_delta_to_source(self._content, content_start, end)
3735.2.158 by John Arbash Meinel
Remove support for passing None for end in GroupCompressBlock.extract.
275
        return bytes
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
276
4469.1.2 by John Arbash Meinel
The only caller already knows the content length, so make the api such that
277
    def set_chunked_content(self, content_chunks, length):
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
278
        """Set the content of this block to the given chunks."""
4469.1.3 by John Arbash Meinel
Notes on why we do it the way we do.
279
        # If we have lots of short lines, it is may be more efficient to join
280
        # the content ahead of time. If the content is <10MiB, we don't really
281
        # care about the extra memory consumption, so we can just pack it and
282
        # be done. However, timing showed 18s => 17.9s for repacking 1k revs of
283
        # mysql, which is below the noise margin
4469.1.2 by John Arbash Meinel
The only caller already knows the content length, so make the api such that
284
        self._content_length = length
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
285
        self._content_chunks = content_chunks
4469.1.2 by John Arbash Meinel
The only caller already knows the content length, so make the api such that
286
        self._content = None
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
287
        self._z_content = None
288
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
289
    def set_content(self, content):
290
        """Set the content of this block."""
291
        self._content_length = len(content)
292
        self._content = content
293
        self._z_content = None
294
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
295
    def _create_z_content_using_lzma(self):
296
        if self._content_chunks is not None:
297
            self._content = ''.join(self._content_chunks)
298
            self._content_chunks = None
299
        if self._content is None:
300
            raise AssertionError('Nothing to compress')
301
        self._z_content = pylzma.compress(self._content)
302
        self._z_content_length = len(self._z_content)
303
304
    def _create_z_content_from_chunks(self):
305
        compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION)
4469.1.3 by John Arbash Meinel
Notes on why we do it the way we do.
306
        compressed_chunks = map(compressor.compress, self._content_chunks)
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
307
        compressed_chunks.append(compressor.flush())
308
        self._z_content = ''.join(compressed_chunks)
309
        self._z_content_length = len(self._z_content)
310
311
    def _create_z_content(self):
312
        if self._z_content is not None:
313
            return
314
        if _USE_LZMA:
315
            self._create_z_content_using_lzma()
316
            return
317
        if self._content_chunks is not None:
318
            self._create_z_content_from_chunks()
319
            return
320
        self._z_content = zlib.compress(self._content)
321
        self._z_content_length = len(self._z_content)
322
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
323
    def to_bytes(self):
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
324
        """Encode the information into a byte stream."""
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
325
        self._create_z_content()
0.17.46 by John Arbash Meinel
Set the proper header when using/not using lzma
326
        if _USE_LZMA:
327
            header = self.GCB_LZ_HEADER
328
        else:
329
            header = self.GCB_HEADER
330
        chunks = [header,
3735.38.4 by John Arbash Meinel
Another disk format change.
331
                  '%d\n%d\n' % (self._z_content_length, self._content_length),
332
                  self._z_content,
0.25.7 by John Arbash Meinel
Have the GroupCompressBlock decide how to compress the header and content.
333
                 ]
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
334
        return ''.join(chunks)
335
4300.1.1 by John Arbash Meinel
Add the ability to convert a gc block into 'human readable' form.
336
    def _dump(self, include_text=False):
337
        """Take this block, and spit out a human-readable structure.
338
339
        :param include_text: Inserts also include text bits, chose whether you
340
            want this displayed in the dump or not.
341
        :return: A dump of the given block. The layout is something like:
342
            [('f', length), ('d', delta_length, text_length, [delta_info])]
343
            delta_info := [('i', num_bytes, text), ('c', offset, num_bytes),
344
            ...]
345
        """
346
        self._ensure_content()
347
        result = []
348
        pos = 0
349
        while pos < self._content_length:
350
            kind = self._content[pos]
351
            pos += 1
352
            if kind not in ('f', 'd'):
353
                raise ValueError('invalid kind character: %r' % (kind,))
354
            content_len, len_len = decode_base128_int(
355
                                self._content[pos:pos + 5])
356
            pos += len_len
357
            if content_len + pos > self._content_length:
358
                raise ValueError('invalid content_len %d for record @ pos %d'
359
                                 % (content_len, pos - len_len - 1))
360
            if kind == 'f': # Fulltext
4398.5.6 by John Arbash Meinel
A bit more debugging information from gcblock._dump(True)
361
                if include_text:
362
                    text = self._content[pos:pos+content_len]
363
                    result.append(('f', content_len, text))
364
                else:
365
                    result.append(('f', content_len))
4300.1.1 by John Arbash Meinel
Add the ability to convert a gc block into 'human readable' form.
366
            elif kind == 'd': # Delta
367
                delta_content = self._content[pos:pos+content_len]
368
                delta_info = []
369
                # The first entry in a delta is the decompressed length
370
                decomp_len, delta_pos = decode_base128_int(delta_content)
371
                result.append(('d', content_len, decomp_len, delta_info))
372
                measured_len = 0
373
                while delta_pos < content_len:
374
                    c = ord(delta_content[delta_pos])
375
                    delta_pos += 1
376
                    if c & 0x80: # Copy
377
                        (offset, length,
378
                         delta_pos) = decode_copy_instruction(delta_content, c,
379
                                                              delta_pos)
4398.5.6 by John Arbash Meinel
A bit more debugging information from gcblock._dump(True)
380
                        if include_text:
381
                            text = self._content[offset:offset+length]
382
                            delta_info.append(('c', offset, length, text))
383
                        else:
384
                            delta_info.append(('c', offset, length))
4300.1.1 by John Arbash Meinel
Add the ability to convert a gc block into 'human readable' form.
385
                        measured_len += length
386
                    else: # Insert
387
                        if include_text:
388
                            txt = delta_content[delta_pos:delta_pos+c]
389
                        else:
390
                            txt = ''
391
                        delta_info.append(('i', c, txt))
392
                        measured_len += c
393
                        delta_pos += c
394
                if delta_pos != content_len:
395
                    raise ValueError('Delta consumed a bad number of bytes:'
396
                                     ' %d != %d' % (delta_pos, content_len))
397
                if measured_len != decomp_len:
398
                    raise ValueError('Delta claimed fulltext was %d bytes, but'
399
                                     ' extraction resulted in %d bytes'
400
                                     % (decomp_len, measured_len))
401
            pos += content_len
402
        return result
403
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
404
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
405
class _LazyGroupCompressFactory(object):
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
406
    """Yield content from a GroupCompressBlock on demand."""
407
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
408
    def __init__(self, key, parents, manager, start, end, first):
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
409
        """Create a _LazyGroupCompressFactory
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
410
411
        :param key: The key of just this record
412
        :param parents: The parents of this key (possibly None)
413
        :param gc_block: A GroupCompressBlock object
414
        :param start: Offset of the first byte for this record in the
415
            uncompressd content
416
        :param end: Offset of the byte just after the end of this record
417
            (ie, bytes = content[start:end])
418
        :param first: Is this the first Factory for the given block?
419
        """
420
        self.key = key
421
        self.parents = parents
422
        self.sha1 = None
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
423
        # Note: This attribute coupled with Manager._factories creates a
424
        #       reference cycle. Perhaps we would rather use a weakref(), or
425
        #       find an appropriate time to release the ref. After the first
426
        #       get_bytes_as call? After Manager.get_record_stream() returns
427
        #       the object?
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
428
        self._manager = manager
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
429
        self._bytes = None
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
430
        self.storage_kind = 'groupcompress-block'
431
        if not first:
432
            self.storage_kind = 'groupcompress-block-ref'
433
        self._first = first
434
        self._start = start
435
        self._end = end
436
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
437
    def __repr__(self):
438
        return '%s(%s, first=%s)' % (self.__class__.__name__,
439
            self.key, self._first)
440
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
441
    def get_bytes_as(self, storage_kind):
442
        if storage_kind == self.storage_kind:
443
            if self._first:
444
                # wire bytes, something...
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
445
                return self._manager._wire_bytes()
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
446
            else:
447
                return ''
448
        if storage_kind in ('fulltext', 'chunked'):
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
449
            if self._bytes is None:
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
450
                # Grab and cache the raw bytes for this entry
451
                # and break the ref-cycle with _manager since we don't need it
452
                # anymore
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
453
                self._manager._prepare_for_extract()
454
                block = self._manager._block
3735.34.2 by John Arbash Meinel
Merge brisbane-core tip, resolve differences.
455
                self._bytes = block.extract(self.key, self._start, self._end)
3735.37.5 by John Arbash Meinel
Restore the refcycle reduction code.
456
                # There are code paths that first extract as fulltext, and then
457
                # extract as storage_kind (smart fetch). So we don't break the
458
                # refcycle here, but instead in manager.get_record_stream()
3735.2.163 by John Arbash Meinel
Merge bzr.dev 4187, and revert the change to fix refcycle issues.
459
                # self._manager = None
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
460
            if storage_kind == 'fulltext':
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
461
                return self._bytes
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
462
            else:
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
463
                return [self._bytes]
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
464
        raise errors.UnavailableRepresentation(self.key, storage_kind,
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
465
                                               self.storage_kind)
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
466
467
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
468
class _LazyGroupContentManager(object):
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
469
    """This manages a group of _LazyGroupCompressFactory objects."""
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
470
471
    def __init__(self, block):
472
        self._block = block
473
        # We need to preserve the ordering
474
        self._factories = []
3735.32.27 by John Arbash Meinel
Have _LazyGroupContentManager pre-extract everything it holds.
475
        self._last_byte = 0
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
476
477
    def add_factory(self, key, parents, start, end):
478
        if not self._factories:
479
            first = True
480
        else:
481
            first = False
482
        # Note that this creates a reference cycle....
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
483
        factory = _LazyGroupCompressFactory(key, parents, self,
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
484
            start, end, first=first)
3735.36.13 by John Arbash Meinel
max() shows up under lsprof as more expensive than creating an object.
485
        # max() works here, but as a function call, doing a compare seems to be
486
        # significantly faster, timeit says 250ms for max() and 100ms for the
487
        # comparison
488
        if end > self._last_byte:
489
            self._last_byte = end
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
490
        self._factories.append(factory)
491
492
    def get_record_stream(self):
493
        """Get a record for all keys added so far."""
494
        for factory in self._factories:
495
            yield factory
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
496
            # Break the ref-cycle
3735.34.2 by John Arbash Meinel
Merge brisbane-core tip, resolve differences.
497
            factory._bytes = None
3735.37.5 by John Arbash Meinel
Restore the refcycle reduction code.
498
            factory._manager = None
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
499
        # TODO: Consider setting self._factories = None after the above loop,
500
        #       as it will break the reference cycle
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
501
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
502
    def _trim_block(self, last_byte):
503
        """Create a new GroupCompressBlock, with just some of the content."""
504
        # None of the factories need to be adjusted, because the content is
505
        # located in an identical place. Just that some of the unreferenced
506
        # trailing bytes are stripped
507
        trace.mutter('stripping trailing bytes from groupcompress block'
508
                     ' %d => %d', self._block._content_length, last_byte)
509
        new_block = GroupCompressBlock()
510
        self._block._ensure_content(last_byte)
511
        new_block.set_content(self._block._content[:last_byte])
512
        self._block = new_block
513
514
    def _rebuild_block(self):
515
        """Create a new GroupCompressBlock with only the referenced texts."""
516
        compressor = GroupCompressor()
517
        tstart = time.time()
518
        old_length = self._block._content_length
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
519
        end_point = 0
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
520
        for factory in self._factories:
521
            bytes = factory.get_bytes_as('fulltext')
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
522
            (found_sha1, start_point, end_point,
523
             type) = compressor.compress(factory.key, bytes, factory.sha1)
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
524
            # Now update this factory with the new offsets, etc
525
            factory.sha1 = found_sha1
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
526
            factory._start = start_point
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
527
            factory._end = end_point
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
528
        self._last_byte = end_point
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
529
        new_block = compressor.flush()
530
        # TODO: Should we check that new_block really *is* smaller than the old
531
        #       block? It seems hard to come up with a method that it would
532
        #       expand, since we do full compression again. Perhaps based on a
533
        #       request that ends up poorly ordered?
534
        delta = time.time() - tstart
535
        self._block = new_block
536
        trace.mutter('creating new compressed block on-the-fly in %.3fs'
537
                     ' %d bytes => %d bytes', delta, old_length,
538
                     self._block._content_length)
539
3735.32.27 by John Arbash Meinel
Have _LazyGroupContentManager pre-extract everything it holds.
540
    def _prepare_for_extract(self):
541
        """A _LazyGroupCompressFactory is about to extract to fulltext."""
542
        # We expect that if one child is going to fulltext, all will be. This
543
        # helps prevent all of them from extracting a small amount at a time.
544
        # Which in itself isn't terribly expensive, but resizing 2MB 32kB at a
545
        # time (self._block._content) is a little expensive.
546
        self._block._ensure_content(self._last_byte)
547
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
548
    def _check_rebuild_block(self):
549
        """Check to see if our block should be repacked."""
550
        total_bytes_used = 0
551
        last_byte_used = 0
552
        for factory in self._factories:
553
            total_bytes_used += factory._end - factory._start
554
            last_byte_used = max(last_byte_used, factory._end)
555
        # If we are using most of the bytes from the block, we have nothing
556
        # else to check (currently more that 1/2)
557
        if total_bytes_used * 2 >= self._block._content_length:
558
            return
559
        # Can we just strip off the trailing bytes? If we are going to be
560
        # transmitting more than 50% of the front of the content, go ahead
561
        if total_bytes_used * 2 > last_byte_used:
562
            self._trim_block(last_byte_used)
563
            return
564
565
        # We are using a small amount of the data, and it isn't just packed
566
        # nicely at the front, so rebuild the content.
567
        # Note: This would be *nicer* as a strip-data-from-group, rather than
568
        #       building it up again from scratch
569
        #       It might be reasonable to consider the fulltext sizes for
570
        #       different bits when deciding this, too. As you may have a small
571
        #       fulltext, and a trivial delta, and you are just trading around
572
        #       for another fulltext. If we do a simple 'prune' you may end up
573
        #       expanding many deltas into fulltexts, as well.
574
        #       If we build a cheap enough 'strip', then we could try a strip,
575
        #       if that expands the content, we then rebuild.
576
        self._rebuild_block()
577
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
578
    def _wire_bytes(self):
579
        """Return a byte stream suitable for transmitting over the wire."""
3735.32.24 by John Arbash Meinel
_wire_bytes() now strips groups as necessary, as does _insert_record_stream
580
        self._check_rebuild_block()
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
581
        # The outer block starts with:
582
        #   'groupcompress-block\n'
583
        #   <length of compressed key info>\n
584
        #   <length of uncompressed info>\n
585
        #   <length of gc block>\n
586
        #   <header bytes>
587
        #   <gc-block>
588
        lines = ['groupcompress-block\n']
589
        # The minimal info we need is the key, the start offset, and the
590
        # parents. The length and type are encoded in the record itself.
591
        # However, passing in the other bits makes it easier.  The list of
592
        # keys, and the start offset, the length
593
        # 1 line key
594
        # 1 line with parents, '' for ()
595
        # 1 line for start offset
596
        # 1 line for end byte
597
        header_lines = []
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
598
        for factory in self._factories:
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
599
            key_bytes = '\x00'.join(factory.key)
600
            parents = factory.parents
601
            if parents is None:
602
                parent_bytes = 'None:'
603
            else:
604
                parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
605
            record_header = '%s\n%s\n%d\n%d\n' % (
606
                key_bytes, parent_bytes, factory._start, factory._end)
607
            header_lines.append(record_header)
3735.37.5 by John Arbash Meinel
Restore the refcycle reduction code.
608
            # TODO: Can we break the refcycle at this point and set
609
            #       factory._manager = None?
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
610
        header_bytes = ''.join(header_lines)
611
        del header_lines
612
        header_bytes_len = len(header_bytes)
613
        z_header_bytes = zlib.compress(header_bytes)
614
        del header_bytes
615
        z_header_bytes_len = len(z_header_bytes)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
616
        block_bytes = self._block.to_bytes()
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
617
        lines.append('%d\n%d\n%d\n' % (z_header_bytes_len, header_bytes_len,
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
618
                                       len(block_bytes)))
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
619
        lines.append(z_header_bytes)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
620
        lines.append(block_bytes)
621
        del z_header_bytes, block_bytes
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
622
        return ''.join(lines)
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
623
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
624
    @classmethod
3735.32.18 by John Arbash Meinel
We now support generating a network stream.
625
    def from_bytes(cls, bytes):
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
626
        # TODO: This does extra string copying, probably better to do it a
627
        #       different way
628
        (storage_kind, z_header_len, header_len,
629
         block_len, rest) = bytes.split('\n', 4)
630
        del bytes
631
        if storage_kind != 'groupcompress-block':
632
            raise ValueError('Unknown storage kind: %s' % (storage_kind,))
633
        z_header_len = int(z_header_len)
634
        if len(rest) < z_header_len:
635
            raise ValueError('Compressed header len shorter than all bytes')
636
        z_header = rest[:z_header_len]
637
        header_len = int(header_len)
638
        header = zlib.decompress(z_header)
639
        if len(header) != header_len:
640
            raise ValueError('invalid length for decompressed bytes')
641
        del z_header
642
        block_len = int(block_len)
643
        if len(rest) != z_header_len + block_len:
644
            raise ValueError('Invalid length for block')
645
        block_bytes = rest[z_header_len:]
646
        del rest
647
        # So now we have a valid GCB, we just need to parse the factories that
648
        # were sent to us
649
        header_lines = header.split('\n')
650
        del header
651
        last = header_lines.pop()
652
        if last != '':
653
            raise ValueError('header lines did not end with a trailing'
654
                             ' newline')
655
        if len(header_lines) % 4 != 0:
656
            raise ValueError('The header was not an even multiple of 4 lines')
657
        block = GroupCompressBlock.from_bytes(block_bytes)
658
        del block_bytes
659
        result = cls(block)
660
        for start in xrange(0, len(header_lines), 4):
661
            # intern()?
662
            key = tuple(header_lines[start].split('\x00'))
663
            parents_line = header_lines[start+1]
664
            if parents_line == 'None:':
665
                parents = None
666
            else:
667
                parents = tuple([tuple(segment.split('\x00'))
668
                                 for segment in parents_line.split('\t')
669
                                  if segment])
670
            start_offset = int(header_lines[start+2])
671
            end_offset = int(header_lines[start+3])
672
            result.add_factory(key, parents, start_offset, end_offset)
673
        return result
674
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
675
3735.32.18 by John Arbash Meinel
We now support generating a network stream.
676
def network_block_to_records(storage_kind, bytes, line_end):
677
    if storage_kind != 'groupcompress-block':
678
        raise ValueError('Unknown storage kind: %s' % (storage_kind,))
679
    manager = _LazyGroupContentManager.from_bytes(bytes)
680
    return manager.get_record_stream()
681
682
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
683
class _CommonGroupCompressor(object):
684
685
    def __init__(self):
686
        """Create a GroupCompressor."""
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
687
        self.chunks = []
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
688
        self._last = None
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
689
        self.endpoint = 0
690
        self.input_bytes = 0
691
        self.labels_deltas = {}
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
692
        self._delta_index = None # Set by the children
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
693
        self._block = GroupCompressBlock()
694
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
695
    def compress(self, key, bytes, expected_sha, nostore_sha=None, soft=False):
696
        """Compress lines with label key.
697
698
        :param key: A key tuple. It is stored in the output
699
            for identification of the text during decompression. If the last
700
            element is 'None' it is replaced with the sha1 of the text -
701
            e.g. sha1:xxxxxxx.
702
        :param bytes: The bytes to be compressed
703
        :param expected_sha: If non-None, the sha the lines are believed to
704
            have. During compression the sha is calculated; a mismatch will
705
            cause an error.
706
        :param nostore_sha: If the computed sha1 sum matches, we will raise
707
            ExistingContent rather than adding the text.
708
        :param soft: Do a 'soft' compression. This means that we require larger
709
            ranges to match to be considered for a copy command.
710
711
        :return: The sha1 of lines, the start and end offsets in the delta, and
712
            the type ('fulltext' or 'delta').
713
714
        :seealso VersionedFiles.add_lines:
715
        """
716
        if not bytes: # empty, like a dir entry, etc
717
            if nostore_sha == _null_sha1:
718
                raise errors.ExistingContent()
719
            return _null_sha1, 0, 0, 'fulltext'
720
        # we assume someone knew what they were doing when they passed it in
721
        if expected_sha is not None:
722
            sha1 = expected_sha
723
        else:
724
            sha1 = osutils.sha_string(bytes)
725
        if nostore_sha is not None:
726
            if sha1 == nostore_sha:
727
                raise errors.ExistingContent()
728
        if key[-1] is None:
729
            key = key[:-1] + ('sha1:' + sha1,)
730
731
        start, end, type = self._compress(key, bytes, len(bytes) / 2, soft)
732
        return sha1, start, end, type
733
734
    def _compress(self, key, bytes, max_delta_size, soft=False):
735
        """Compress lines with label key.
736
737
        :param key: A key tuple. It is stored in the output for identification
738
            of the text during decompression.
739
740
        :param bytes: The bytes to be compressed
741
742
        :param max_delta_size: The size above which we issue a fulltext instead
743
            of a delta.
744
745
        :param soft: Do a 'soft' compression. This means that we require larger
746
            ranges to match to be considered for a copy command.
747
748
        :return: The sha1 of lines, the start and end offsets in the delta, and
749
            the type ('fulltext' or 'delta').
750
        """
751
        raise NotImplementedError(self._compress)
752
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
753
    def extract(self, key):
754
        """Extract a key previously added to the compressor.
755
756
        :param key: The key to extract.
757
        :return: An iterable over bytes and the sha1.
758
        """
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
759
        (start_byte, start_chunk, end_byte, end_chunk) = self.labels_deltas[key]
760
        delta_chunks = self.chunks[start_chunk:end_chunk]
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
761
        stored_bytes = ''.join(delta_chunks)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
762
        if stored_bytes[0] == 'f':
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
763
            fulltext_len, offset = decode_base128_int(stored_bytes[1:10])
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
764
            data_len = fulltext_len + 1 + offset
765
            if  data_len != len(stored_bytes):
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
766
                raise ValueError('Index claimed fulltext len, but stored bytes'
767
                                 ' claim %s != %s'
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
768
                                 % (len(stored_bytes), data_len))
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
769
            bytes = stored_bytes[offset + 1:]
770
        else:
771
            # XXX: This is inefficient at best
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
772
            source = ''.join(self.chunks[:start_chunk])
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
773
            if stored_bytes[0] != 'd':
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
774
                raise ValueError('Unknown content kind, bytes claim %s'
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
775
                                 % (stored_bytes[0],))
776
            delta_len, offset = decode_base128_int(stored_bytes[1:10])
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
777
            data_len = delta_len + 1 + offset
778
            if data_len != len(stored_bytes):
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
779
                raise ValueError('Index claimed delta len, but stored bytes'
780
                                 ' claim %s != %s'
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
781
                                 % (len(stored_bytes), data_len))
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
782
            bytes = apply_delta(source, stored_bytes[offset + 1:])
783
        bytes_sha1 = osutils.sha_string(bytes)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
784
        return bytes, bytes_sha1
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
785
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
786
    def flush(self):
787
        """Finish this group, creating a formatted stream.
788
789
        After calling this, the compressor should no longer be used
790
        """
4398.6.2 by John Arbash Meinel
Add a TODO, marking the code that causes us to peak at 2x memory consumption
791
        # TODO: this causes us to 'bloat' to 2x the size of content in the
792
        #       group. This has an impact for 'commit' of large objects.
793
        #       One possibility is to use self._content_chunks, and be lazy and
794
        #       only fill out self._content as a full string when we actually
795
        #       need it. That would at least drop the peak memory consumption
796
        #       for 'commit' down to ~1x the size of the largest file, at a
797
        #       cost of increased complexity within this code. 2x is still <<
798
        #       3x the size of the largest file, so we are doing ok.
4469.1.2 by John Arbash Meinel
The only caller already knows the content length, so make the api such that
799
        self._block.set_chunked_content(self.chunks, self.endpoint)
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
800
        self.chunks = None
801
        self._delta_index = None
802
        return self._block
803
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
804
    def pop_last(self):
805
        """Call this if you want to 'revoke' the last compression.
806
807
        After this, the data structures will be rolled back, but you cannot do
808
        more compression.
809
        """
810
        self._delta_index = None
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
811
        del self.chunks[self._last[0]:]
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
812
        self.endpoint = self._last[1]
813
        self._last = None
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
814
815
    def ratio(self):
816
        """Return the overall compression ratio."""
817
        return float(self.input_bytes) / float(self.endpoint)
818
819
820
class PythonGroupCompressor(_CommonGroupCompressor):
821
3735.40.2 by John Arbash Meinel
Add a groupcompress.encode_copy_instruction function.
822
    def __init__(self):
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
823
        """Create a GroupCompressor.
824
825
        Used only if the pyrex version is not available.
826
        """
827
        super(PythonGroupCompressor, self).__init__()
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
828
        self._delta_index = LinesDeltaIndex([])
829
        # The actual content is managed by LinesDeltaIndex
830
        self.chunks = self._delta_index.lines
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
831
832
    def _compress(self, key, bytes, max_delta_size, soft=False):
833
        """see _CommonGroupCompressor._compress"""
834
        input_len = len(bytes)
3735.40.2 by John Arbash Meinel
Add a groupcompress.encode_copy_instruction function.
835
        new_lines = osutils.split_lines(bytes)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
836
        out_lines, index_lines = self._delta_index.make_delta(
837
            new_lines, bytes_length=input_len, soft=soft)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
838
        delta_length = sum(map(len, out_lines))
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
839
        if delta_length > max_delta_size:
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
840
            # The delta is longer than the fulltext, insert a fulltext
841
            type = 'fulltext'
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
842
            out_lines = ['f', encode_base128_int(input_len)]
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
843
            out_lines.extend(new_lines)
844
            index_lines = [False, False]
845
            index_lines.extend([True] * len(new_lines))
846
        else:
847
            # this is a worthy delta, output it
848
            type = 'delta'
849
            out_lines[0] = 'd'
850
            # Update the delta_length to include those two encoded integers
851
            out_lines[1] = encode_base128_int(delta_length)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
852
        # Before insertion
853
        start = self.endpoint
854
        chunk_start = len(self.chunks)
4241.17.2 by John Arbash Meinel
PythonGroupCompressor needs to support pop_last() properly.
855
        self._last = (chunk_start, self.endpoint)
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
856
        self._delta_index.extend_lines(out_lines, index_lines)
857
        self.endpoint = self._delta_index.endpoint
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
858
        self.input_bytes += input_len
859
        chunk_end = len(self.chunks)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
860
        self.labels_deltas[key] = (start, chunk_start,
861
                                   self.endpoint, chunk_end)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
862
        return start, self.endpoint, type
863
864
865
class PyrexGroupCompressor(_CommonGroupCompressor):
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
866
    """Produce a serialised group of compressed texts.
0.23.6 by John Arbash Meinel
Start stripping out the actual GroupCompressor
867
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
868
    It contains code very similar to SequenceMatcher because of having a similar
869
    task. However some key differences apply:
870
     - there is no junk, we want a minimal edit not a human readable diff.
871
     - we don't filter very common lines (because we don't know where a good
872
       range will start, and after the first text we want to be emitting minmal
873
       edits only.
874
     - we chain the left side, not the right side
875
     - we incrementally update the adjacency matrix as new lines are provided.
876
     - we look for matches in all of the left side, so the routine which does
877
       the analagous task of find_longest_match does not need to filter on the
878
       left side.
879
    """
0.17.2 by Robert Collins
Core proof of concept working.
880
3735.32.19 by John Arbash Meinel
Get rid of the 'delta' flag to GroupCompressor. It didn't do anything anyway.
881
    def __init__(self):
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
882
        super(PyrexGroupCompressor, self).__init__()
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
883
        self._delta_index = DeltaIndex()
0.23.6 by John Arbash Meinel
Start stripping out the actual GroupCompressor
884
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
885
    def _compress(self, key, bytes, max_delta_size, soft=False):
886
        """see _CommonGroupCompressor._compress"""
0.23.52 by John Arbash Meinel
Use the max_delta flag.
887
        input_len = len(bytes)
0.23.12 by John Arbash Meinel
Add a 'len:' field to the data.
888
        # By having action/label/sha1/len, we can parse the group if the index
889
        # was ever destroyed, we have the key in 'label', we know the final
890
        # bytes are valid from sha1, and we know where to find the end of this
891
        # record because of 'len'. (the delta record itself will store the
892
        # total length for the expanded record)
0.23.13 by John Arbash Meinel
Factor out the ability to have/not have labels.
893
        # 'len: %d\n' costs approximately 1% increase in total data
894
        # Having the labels at all costs us 9-10% increase, 38% increase for
895
        # inventory pages, and 5.8% increase for text pages
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
896
        # new_chunks = ['label:%s\nsha1:%s\n' % (label, sha1)]
0.23.33 by John Arbash Meinel
Fix a bug when handling multiple large-range copies.
897
        if self._delta_index._source_offset != self.endpoint:
898
            raise AssertionError('_source_offset != endpoint'
899
                ' somehow the DeltaIndex got out of sync with'
900
                ' the output lines')
0.23.52 by John Arbash Meinel
Use the max_delta flag.
901
        delta = self._delta_index.make_delta(bytes, max_delta_size)
902
        if (delta is None):
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
903
            type = 'fulltext'
0.17.36 by John Arbash Meinel
Adding a mini-len to the delta/fulltext bytes
904
            enc_length = encode_base128_int(len(bytes))
905
            len_mini_header = 1 + len(enc_length)
906
            self._delta_index.add_source(bytes, len_mini_header)
907
            new_chunks = ['f', enc_length, bytes]
0.23.9 by John Arbash Meinel
We now basically have full support for using diff-delta as the compressor.
908
        else:
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
909
            type = 'delta'
0.17.36 by John Arbash Meinel
Adding a mini-len to the delta/fulltext bytes
910
            enc_length = encode_base128_int(len(delta))
911
            len_mini_header = 1 + len(enc_length)
912
            new_chunks = ['d', enc_length, delta]
3735.38.5 by John Arbash Meinel
A bit of testing showed that _FAST=True was actually *slower*.
913
            self._delta_index.add_delta_source(delta, len_mini_header)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
914
        # Before insertion
915
        start = self.endpoint
916
        chunk_start = len(self.chunks)
917
        # Now output these bytes
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
918
        self._output_chunks(new_chunks)
0.23.6 by John Arbash Meinel
Start stripping out the actual GroupCompressor
919
        self.input_bytes += input_len
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
920
        chunk_end = len(self.chunks)
921
        self.labels_deltas[key] = (start, chunk_start,
922
                                   self.endpoint, chunk_end)
0.23.29 by John Arbash Meinel
Forgot to add the delta bytes to the index objects.
923
        if not self._delta_index._source_offset == self.endpoint:
924
            raise AssertionError('the delta index is out of sync'
925
                'with the output lines %s != %s'
926
                % (self._delta_index._source_offset, self.endpoint))
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
927
        return start, self.endpoint, type
0.17.2 by Robert Collins
Core proof of concept working.
928
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
929
    def _output_chunks(self, new_chunks):
0.23.9 by John Arbash Meinel
We now basically have full support for using diff-delta as the compressor.
930
        """Output some chunks.
931
932
        :param new_chunks: The chunks to output.
933
        """
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
934
        self._last = (len(self.chunks), self.endpoint)
0.17.12 by Robert Collins
Encode copy ranges as bytes not lines, halves decode overhead.
935
        endpoint = self.endpoint
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
936
        self.chunks.extend(new_chunks)
0.23.9 by John Arbash Meinel
We now basically have full support for using diff-delta as the compressor.
937
        endpoint += sum(map(len, new_chunks))
0.17.12 by Robert Collins
Encode copy ranges as bytes not lines, halves decode overhead.
938
        self.endpoint = endpoint
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
939
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
940
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
941
def make_pack_factory(graph, delta, keylength, inconsistency_fatal=True):
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
942
    """Create a factory for creating a pack based groupcompress.
943
944
    This is only functional enough to run interface tests, it doesn't try to
945
    provide a full pack environment.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
946
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
947
    :param graph: Store a graph.
948
    :param delta: Delta compress contents.
949
    :param keylength: How long should keys be.
950
    """
951
    def factory(transport):
3735.32.2 by John Arbash Meinel
The 'delta' flag has no effect on the content (all GC is delta'd),
952
        parents = graph
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
953
        ref_length = 0
954
        if graph:
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
955
            ref_length = 1
0.17.7 by Robert Collins
Update for current index2 changes.
956
        graph_index = BTreeBuilder(reference_lists=ref_length,
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
957
            key_elements=keylength)
958
        stream = transport.open_write_stream('newpack')
959
        writer = pack.ContainerWriter(stream.write)
960
        writer.begin()
961
        index = _GCGraphIndex(graph_index, lambda:True, parents=parents,
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
962
            add_callback=graph_index.add_nodes,
963
            inconsistency_fatal=inconsistency_fatal)
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
964
        access = knit._DirectPackAccess({})
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
965
        access.set_writer(writer, graph_index, (transport, 'newpack'))
0.17.2 by Robert Collins
Core proof of concept working.
966
        result = GroupCompressVersionedFiles(index, access, delta)
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
967
        result.stream = stream
968
        result.writer = writer
969
        return result
970
    return factory
971
972
973
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.
974
    versioned_files.writer.end()
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
975
    versioned_files.stream.close()
976
977
978
class GroupCompressVersionedFiles(VersionedFiles):
979
    """A group-compress based VersionedFiles implementation."""
980
0.17.2 by Robert Collins
Core proof of concept working.
981
    def __init__(self, index, access, delta=True):
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
982
        """Create a GroupCompressVersionedFiles object.
983
984
        :param index: The index object storing access and graph data.
985
        :param access: The access object storing raw data.
0.17.2 by Robert Collins
Core proof of concept working.
986
        :param delta: Whether to delta compress or just entropy compress.
987
        """
988
        self._index = index
989
        self._access = access
990
        self._delta = delta
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
991
        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.
992
        self._group_cache = LRUSizeCache(max_size=50*1024*1024)
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
993
        self._fallback_vfs = []
0.17.2 by Robert Collins
Core proof of concept working.
994
995
    def add_lines(self, key, parents, lines, parent_texts=None,
996
        left_matching_blocks=None, nostore_sha=None, random_id=False,
997
        check_content=True):
998
        """Add a text to the store.
999
1000
        :param key: The key tuple of the text to add.
1001
        :param parents: The parents key tuples of the text to add.
1002
        :param lines: A list of lines. Each line must be a bytestring. And all
1003
            of them except the last must be terminated with \n and contain no
1004
            other \n's. The last line may either contain no \n's or a single
1005
            terminating \n. If the lines list does meet this constraint the add
1006
            routine may error or may succeed - but you will be unable to read
1007
            the data back accurately. (Checking the lines have been split
1008
            correctly is expensive and extremely unlikely to catch bugs so it
1009
            is not done at runtime unless check_content is True.)
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1010
        :param parent_texts: An optional dictionary containing the opaque
0.17.2 by Robert Collins
Core proof of concept working.
1011
            representations of some or all of the parents of version_id to
1012
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
1013
            returned by add_lines or data corruption can be caused.
1014
        :param left_matching_blocks: a hint about which areas are common
1015
            between the text and its left-hand-parent.  The format is
1016
            the SequenceMatcher.get_matching_blocks format.
1017
        :param nostore_sha: Raise ExistingContent and do not add the lines to
1018
            the versioned file if the digest of the lines matches this.
1019
        :param random_id: If True a random id has been selected rather than
1020
            an id determined by some deterministic process such as a converter
1021
            from a foreign VCS. When True the backend may choose not to check
1022
            for uniqueness of the resulting key within the versioned file, so
1023
            this should only be done when the result is expected to be unique
1024
            anyway.
1025
        :param check_content: If True, the lines supplied are verified to be
1026
            bytestrings that are correctly formed lines.
1027
        :return: The text sha1, the number of bytes in the text, and an opaque
1028
                 representation of the inserted version which can be provided
1029
                 back to future add_lines calls in the parent_texts dictionary.
1030
        """
1031
        self._index._check_write_ok()
1032
        self._check_add(key, lines, random_id, check_content)
1033
        if parents is None:
1034
            # The caller might pass None if there is no graph data, but kndx
1035
            # indexes can't directly store that, so we give them
1036
            # an empty tuple instead.
1037
            parents = ()
1038
        # double handling for now. Make it work until then.
0.20.5 by John Arbash Meinel
Finish the Fulltext => Chunked conversions so that we work in the more-efficient Chunks.
1039
        length = sum(map(len, lines))
1040
        record = ChunkedContentFactory(key, parents, None, lines)
3735.31.12 by John Arbash Meinel
Push nostore_sha down through the stack.
1041
        sha1 = list(self._insert_record_stream([record], random_id=random_id,
1042
                                               nostore_sha=nostore_sha))[0]
0.20.5 by John Arbash Meinel
Finish the Fulltext => Chunked conversions so that we work in the more-efficient Chunks.
1043
        return sha1, length, None
0.17.2 by Robert Collins
Core proof of concept working.
1044
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
1045
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
4398.9.1 by Matt Nordhoff
Update _add_text docstrings that still referred to add_text.
1046
        """See VersionedFiles._add_text()."""
4398.8.4 by John Arbash Meinel
Implement add_text for GroupCompressVersionedFiles
1047
        self._index._check_write_ok()
1048
        self._check_add(key, None, random_id, check_content=False)
1049
        if text.__class__ is not str:
1050
            raise errors.BzrBadParameterUnicode("text")
1051
        if parents is None:
1052
            # The caller might pass None if there is no graph data, but kndx
1053
            # indexes can't directly store that, so we give them
1054
            # an empty tuple instead.
1055
            parents = ()
1056
        # double handling for now. Make it work until then.
1057
        length = len(text)
1058
        record = FulltextContentFactory(key, parents, None, text)
1059
        sha1 = list(self._insert_record_stream([record], random_id=random_id,
1060
                                               nostore_sha=nostore_sha))[0]
1061
        return sha1, length, None
1062
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1063
    def add_fallback_versioned_files(self, a_versioned_files):
1064
        """Add a source of texts for texts not present in this knit.
1065
1066
        :param a_versioned_files: A VersionedFiles object.
1067
        """
1068
        self._fallback_vfs.append(a_versioned_files)
1069
0.17.4 by Robert Collins
Annotate.
1070
    def annotate(self, key):
1071
        """See VersionedFiles.annotate."""
4454.3.58 by John Arbash Meinel
Enable the new annotator for gc format repos.
1072
        ann = annotate.Annotator(self)
1073
        return ann.annotate_flat(key)
0.17.4 by Robert Collins
Annotate.
1074
4454.3.65 by John Arbash Meinel
Tests that VF implementations support .get_annotator()
1075
    def get_annotator(self):
1076
        return annotate.Annotator(self)
1077
4332.3.28 by Robert Collins
Start checking file texts in a single pass.
1078
    def check(self, progress_bar=None, keys=None):
0.17.5 by Robert Collins
nograph tests completely passing.
1079
        """See VersionedFiles.check()."""
4332.3.28 by Robert Collins
Start checking file texts in a single pass.
1080
        if keys is None:
1081
            keys = self.keys()
1082
            for record in self.get_record_stream(keys, 'unordered', True):
1083
                record.get_bytes_as('fulltext')
1084
        else:
1085
            return self.get_record_stream(keys, 'unordered', True)
0.17.5 by Robert Collins
nograph tests completely passing.
1086
0.17.2 by Robert Collins
Core proof of concept working.
1087
    def _check_add(self, key, lines, random_id, check_content):
1088
        """check that version_id and lines are safe to add."""
1089
        version_id = key[-1]
0.17.26 by Robert Collins
Working better --gc-plain-chk.
1090
        if version_id is not None:
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1091
            if osutils.contains_whitespace(version_id):
3735.31.1 by John Arbash Meinel
Bring the groupcompress plugin into the brisbane-core branch.
1092
                raise errors.InvalidRevisionId(version_id, self)
0.17.2 by Robert Collins
Core proof of concept working.
1093
        self.check_not_reserved_id(version_id)
1094
        # TODO: If random_id==False and the key is already present, we should
1095
        # probably check that the existing content is identical to what is
1096
        # being inserted, and otherwise raise an exception.  This would make
1097
        # the bundle code simpler.
1098
        if check_content:
1099
            self._check_lines_not_unicode(lines)
1100
            self._check_lines_are_lines(lines)
1101
4593.5.20 by John Arbash Meinel
Expose KnownGraph off of VersionedFiles
1102
    def get_known_graph_ancestry(self, keys):
1103
        """Get a KnownGraph instance with the ancestry of keys."""
1104
        parent_map, missing_keys = self._index._graph_index.find_ancestry(keys,
1105
                                                                          0)
1106
        kg = _mod_graph.KnownGraph(parent_map)
1107
        return kg
1108
0.17.5 by Robert Collins
nograph tests completely passing.
1109
    def get_parent_map(self, keys):
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1110
        """Get a map of the graph parents of keys.
0.17.5 by Robert Collins
nograph tests completely passing.
1111
1112
        :param keys: The keys to look up parents for.
1113
        :return: A mapping from keys to parents. Absent keys are absent from
1114
            the mapping.
1115
        """
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1116
        return self._get_parent_map_with_sources(keys)[0]
1117
1118
    def _get_parent_map_with_sources(self, keys):
1119
        """Get a map of the parents of keys.
1120
1121
        :param keys: The keys to look up parents for.
1122
        :return: A tuple. The first element is a mapping from keys to parents.
1123
            Absent keys are absent from the mapping. The second element is a
1124
            list with the locations each key was found in. The first element
1125
            is the in-this-knit parents, the second the first fallback source,
1126
            and so on.
1127
        """
0.17.5 by Robert Collins
nograph tests completely passing.
1128
        result = {}
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1129
        sources = [self._index] + self._fallback_vfs
0.17.5 by Robert Collins
nograph tests completely passing.
1130
        source_results = []
1131
        missing = set(keys)
1132
        for source in sources:
1133
            if not missing:
1134
                break
1135
            new_result = source.get_parent_map(missing)
1136
            source_results.append(new_result)
1137
            result.update(new_result)
1138
            missing.difference_update(set(new_result))
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1139
        return result, source_results
0.17.5 by Robert Collins
nograph tests completely passing.
1140
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
1141
    def _get_block(self, index_memo):
0.20.14 by John Arbash Meinel
Factor out _get_group_and_delta_lines.
1142
        read_memo = index_memo[0:3]
1143
        # get the group:
1144
        try:
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
1145
            block = self._group_cache[read_memo]
0.20.14 by John Arbash Meinel
Factor out _get_group_and_delta_lines.
1146
        except KeyError:
1147
            # read the group
1148
            zdata = self._access.get_raw_records([read_memo]).next()
1149
            # decompress - whole thing - this is not a bug, as it
1150
            # permits caching. We might want to store the partially
1151
            # decompresed group and decompress object, so that recent
1152
            # texts are not penalised by big groups.
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
1153
            block = GroupCompressBlock.from_bytes(zdata)
1154
            self._group_cache[read_memo] = block
0.20.14 by John Arbash Meinel
Factor out _get_group_and_delta_lines.
1155
        # cheapo debugging:
1156
        # print len(zdata), len(plain)
1157
        # parse - requires split_lines, better to have byte offsets
1158
        # here (but not by much - we only split the region for the
1159
        # recipe, and we often want to end up with lines anyway.
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
1160
        return block
0.20.14 by John Arbash Meinel
Factor out _get_group_and_delta_lines.
1161
0.20.18 by John Arbash Meinel
Implement new handling of get_bytes_as(), and get_missing_compression_parent_keys()
1162
    def get_missing_compression_parent_keys(self):
1163
        """Return the keys of missing compression parents.
1164
1165
        Missing compression parents occur when a record stream was missing
1166
        basis texts, or a index was scanned that had missing basis texts.
1167
        """
1168
        # GroupCompress cannot currently reference texts that are not in the
1169
        # group, so this is valid for now
1170
        return frozenset()
1171
0.17.5 by Robert Collins
nograph tests completely passing.
1172
    def get_record_stream(self, keys, ordering, include_delta_closure):
1173
        """Get a stream of records for keys.
1174
1175
        :param keys: The keys to include.
1176
        :param ordering: Either 'unordered' or 'topological'. A topologically
1177
            sorted stream has compression parents strictly before their
1178
            children.
1179
        :param include_delta_closure: If True then the closure across any
1180
            compression parents will be included (in the opaque data).
1181
        :return: An iterator of ContentFactory objects, each of which is only
1182
            valid until the iterator is advanced.
1183
        """
1184
        # keys might be a generator
0.22.6 by John Arbash Meinel
Clustering chk pages properly makes a big difference.
1185
        orig_keys = list(keys)
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1186
        keys = set(keys)
0.17.5 by Robert Collins
nograph tests completely passing.
1187
        if not keys:
1188
            return
0.20.23 by John Arbash Meinel
Add a progress indicator for chk pages.
1189
        if (not self._index.has_graph
3735.31.14 by John Arbash Meinel
Change the gc-optimal to 'groupcompress'
1190
            and ordering in ('topological', 'groupcompress')):
0.17.5 by Robert Collins
nograph tests completely passing.
1191
            # Cannot topological order when no graph has been stored.
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1192
            # but we allow 'as-requested' or 'unordered'
0.17.5 by Robert Collins
nograph tests completely passing.
1193
            ordering = 'unordered'
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1194
1195
        remaining_keys = keys
1196
        while True:
1197
            try:
1198
                keys = set(remaining_keys)
1199
                for content_factory in self._get_remaining_record_stream(keys,
1200
                        orig_keys, ordering, include_delta_closure):
1201
                    remaining_keys.discard(content_factory.key)
1202
                    yield content_factory
1203
                return
1204
            except errors.RetryWithNewPacks, e:
1205
                self._access.reload_or_raise(e)
1206
1207
    def _find_from_fallback(self, missing):
1208
        """Find whatever keys you can from the fallbacks.
1209
1210
        :param missing: A set of missing keys. This set will be mutated as keys
1211
            are found from a fallback_vfs
1212
        :return: (parent_map, key_to_source_map, source_results)
1213
            parent_map  the overall key => parent_keys
1214
            key_to_source_map   a dict from {key: source}
1215
            source_results      a list of (source: keys)
1216
        """
1217
        parent_map = {}
1218
        key_to_source_map = {}
1219
        source_results = []
1220
        for source in self._fallback_vfs:
1221
            if not missing:
1222
                break
1223
            source_parents = source.get_parent_map(missing)
1224
            parent_map.update(source_parents)
1225
            source_parents = list(source_parents)
1226
            source_results.append((source, source_parents))
1227
            key_to_source_map.update((key, source) for key in source_parents)
1228
            missing.difference_update(source_parents)
1229
        return parent_map, key_to_source_map, source_results
1230
1231
    def _get_ordered_source_keys(self, ordering, parent_map, key_to_source_map):
1232
        """Get the (source, [keys]) list.
1233
1234
        The returned objects should be in the order defined by 'ordering',
1235
        which can weave between different sources.
1236
        :param ordering: Must be one of 'topological' or 'groupcompress'
1237
        :return: List of [(source, [keys])] tuples, such that all keys are in
1238
            the defined order, regardless of source.
1239
        """
1240
        if ordering == 'topological':
1241
            present_keys = topo_sort(parent_map)
1242
        else:
1243
            # ordering == 'groupcompress'
1244
            # XXX: This only optimizes for the target ordering. We may need
1245
            #      to balance that with the time it takes to extract
1246
            #      ordering, by somehow grouping based on
1247
            #      locations[key][0:3]
1248
            present_keys = sort_gc_optimal(parent_map)
1249
        # Now group by source:
1250
        source_keys = []
1251
        current_source = None
1252
        for key in present_keys:
1253
            source = key_to_source_map.get(key, self)
1254
            if source is not current_source:
1255
                source_keys.append((source, []))
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
1256
                current_source = source
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1257
            source_keys[-1][1].append(key)
1258
        return source_keys
1259
1260
    def _get_as_requested_source_keys(self, orig_keys, locations, unadded_keys,
1261
                                      key_to_source_map):
1262
        source_keys = []
1263
        current_source = None
1264
        for key in orig_keys:
1265
            if key in locations or key in unadded_keys:
1266
                source = self
1267
            elif key in key_to_source_map:
1268
                source = key_to_source_map[key]
1269
            else: # absent
1270
                continue
1271
            if source is not current_source:
1272
                source_keys.append((source, []))
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
1273
                current_source = source
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1274
            source_keys[-1][1].append(key)
1275
        return source_keys
1276
1277
    def _get_io_ordered_source_keys(self, locations, unadded_keys,
1278
                                    source_result):
1279
        def get_group(key):
1280
            # This is the group the bytes are stored in, followed by the
1281
            # location in the group
1282
            return locations[key][0]
1283
        present_keys = sorted(locations.iterkeys(), key=get_group)
1284
        # We don't have an ordering for keys in the in-memory object, but
1285
        # lets process the in-memory ones first.
1286
        present_keys = list(unadded_keys) + present_keys
1287
        # Now grab all of the ones from other sources
1288
        source_keys = [(self, present_keys)]
1289
        source_keys.extend(source_result)
1290
        return source_keys
1291
1292
    def _get_remaining_record_stream(self, keys, orig_keys, ordering,
1293
                                     include_delta_closure):
1294
        """Get a stream of records for keys.
1295
1296
        :param keys: The keys to include.
1297
        :param ordering: one of 'unordered', 'topological', 'groupcompress' or
1298
            'as-requested'
1299
        :param include_delta_closure: If True then the closure across any
1300
            compression parents will be included (in the opaque data).
1301
        :return: An iterator of ContentFactory objects, each of which is only
1302
            valid until the iterator is advanced.
1303
        """
0.17.5 by Robert Collins
nograph tests completely passing.
1304
        # Cheap: iterate
1305
        locations = self._index.get_build_details(keys)
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1306
        unadded_keys = set(self._unadded_refs).intersection(keys)
1307
        missing = keys.difference(locations)
1308
        missing.difference_update(unadded_keys)
1309
        (fallback_parent_map, key_to_source_map,
1310
         source_result) = self._find_from_fallback(missing)
1311
        if ordering in ('topological', 'groupcompress'):
0.17.5 by Robert Collins
nograph tests completely passing.
1312
            # would be better to not globally sort initially but instead
1313
            # start with one key, recurse to its oldest parent, then grab
1314
            # everything in the same group, etc.
1315
            parent_map = dict((key, details[2]) for key, details in
1316
                locations.iteritems())
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1317
            for key in unadded_keys:
1318
                parent_map[key] = self._unadded_refs[key]
1319
            parent_map.update(fallback_parent_map)
1320
            source_keys = self._get_ordered_source_keys(ordering, parent_map,
1321
                                                        key_to_source_map)
0.22.6 by John Arbash Meinel
Clustering chk pages properly makes a big difference.
1322
        elif ordering == 'as-requested':
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1323
            source_keys = self._get_as_requested_source_keys(orig_keys,
1324
                locations, unadded_keys, key_to_source_map)
0.17.5 by Robert Collins
nograph tests completely passing.
1325
        else:
0.20.10 by John Arbash Meinel
Change the extraction ordering for 'unordered'.
1326
            # We want to yield the keys in a semi-optimal (read-wise) ordering.
1327
            # Otherwise we thrash the _group_cache and destroy performance
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1328
            source_keys = self._get_io_ordered_source_keys(locations,
1329
                unadded_keys, source_result)
1330
        for key in missing:
0.17.5 by Robert Collins
nograph tests completely passing.
1331
            yield AbsentContentFactory(key)
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
1332
        manager = None
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
1333
        last_read_memo = None
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
1334
        # TODO: This works fairly well at batching up existing groups into a
1335
        #       streamable format, and possibly allowing for taking one big
1336
        #       group and splitting it when it isn't fully utilized.
1337
        #       However, it doesn't allow us to find under-utilized groups and
1338
        #       combine them into a bigger group on the fly.
1339
        #       (Consider the issue with how chk_map inserts texts
1340
        #       one-at-a-time.) This could be done at insert_record_stream()
1341
        #       time, but it probably would decrease the number of
1342
        #       bytes-on-the-wire for fetch.
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1343
        for source, keys in source_keys:
1344
            if source is self:
1345
                for key in keys:
1346
                    if key in self._unadded_refs:
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
1347
                        if manager is not None:
1348
                            for factory in manager.get_record_stream():
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
1349
                                yield factory
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
1350
                            last_read_memo = manager = None
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1351
                        bytes, sha1 = self._compressor.extract(key)
1352
                        parents = self._unadded_refs[key]
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
1353
                        yield FulltextContentFactory(key, parents, sha1, bytes)
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1354
                    else:
1355
                        index_memo, _, parents, (method, _) = locations[key]
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
1356
                        read_memo = index_memo[0:3]
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
1357
                        if last_read_memo != read_memo:
1358
                            # We are starting a new block. If we have a
1359
                            # manager, we have found everything that fits for
1360
                            # now, so yield records
1361
                            if manager is not None:
1362
                                for factory in manager.get_record_stream():
1363
                                    yield factory
1364
                            # Now start a new manager
3735.34.1 by John Arbash Meinel
Some testing to see if we can decrease the peak memory consumption a bit.
1365
                            block = self._get_block(index_memo)
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
1366
                            manager = _LazyGroupContentManager(block)
1367
                            last_read_memo = read_memo
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
1368
                        start, end = index_memo[3:5]
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
1369
                        manager.add_factory(key, parents, start, end)
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
1370
            else:
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
1371
                if manager is not None:
1372
                    for factory in manager.get_record_stream():
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
1373
                        yield factory
3735.34.3 by John Arbash Meinel
Cleanup, in preparation for merging to brisbane-core.
1374
                    last_read_memo = manager = None
3735.31.18 by John Arbash Meinel
Implement stacking support across all ordering implementations.
1375
                for record in source.get_record_stream(keys, ordering,
1376
                                                       include_delta_closure):
1377
                    yield record
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
1378
        if manager is not None:
1379
            for factory in manager.get_record_stream():
3735.32.12 by John Arbash Meinel
Add groupcompress-block[-ref] as valid stream types.
1380
                yield factory
0.20.5 by John Arbash Meinel
Finish the Fulltext => Chunked conversions so that we work in the more-efficient Chunks.
1381
0.17.5 by Robert Collins
nograph tests completely passing.
1382
    def get_sha1s(self, keys):
1383
        """See VersionedFiles.get_sha1s()."""
1384
        result = {}
1385
        for record in self.get_record_stream(keys, 'unordered', True):
1386
            if record.sha1 != None:
1387
                result[record.key] = record.sha1
1388
            else:
1389
                if record.storage_kind != 'absent':
3735.40.2 by John Arbash Meinel
Add a groupcompress.encode_copy_instruction function.
1390
                    result[record.key] = osutils.sha_string(
1391
                        record.get_bytes_as('fulltext'))
0.17.5 by Robert Collins
nograph tests completely passing.
1392
        return result
1393
0.17.2 by Robert Collins
Core proof of concept working.
1394
    def insert_record_stream(self, stream):
1395
        """Insert a record stream into this container.
1396
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1397
        :param stream: A stream of records to insert.
0.17.2 by Robert Collins
Core proof of concept working.
1398
        :return: None
1399
        :seealso VersionedFiles.get_record_stream:
1400
        """
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1401
        # XXX: Setting random_id=True makes
1402
        # test_insert_record_stream_existing_keys fail for groupcompress and
1403
        # groupcompress-nograph, this needs to be revisited while addressing
1404
        # 'bzr branch' performance issues.
1405
        for _ in self._insert_record_stream(stream, random_id=False):
0.17.5 by Robert Collins
nograph tests completely passing.
1406
            pass
0.17.2 by Robert Collins
Core proof of concept working.
1407
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1408
    def _insert_record_stream(self, stream, random_id=False, nostore_sha=None,
1409
                              reuse_blocks=True):
0.17.2 by Robert Collins
Core proof of concept working.
1410
        """Internal core to insert a record stream into this container.
1411
1412
        This helper function has a different interface than insert_record_stream
1413
        to allow add_lines to be minimal, but still return the needed data.
1414
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1415
        :param stream: A stream of records to insert.
3735.31.12 by John Arbash Meinel
Push nostore_sha down through the stack.
1416
        :param nostore_sha: If the sha1 of a given text matches nostore_sha,
1417
            raise ExistingContent, rather than committing the new text.
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1418
        :param reuse_blocks: If the source is streaming from
1419
            groupcompress-blocks, just insert the blocks as-is, rather than
1420
            expanding the texts and inserting again.
0.17.2 by Robert Collins
Core proof of concept working.
1421
        :return: An iterator over the sha1 of the inserted records.
1422
        :seealso insert_record_stream:
1423
        :seealso add_lines:
1424
        """
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1425
        adapters = {}
0.17.5 by Robert Collins
nograph tests completely passing.
1426
        def get_adapter(adapter_key):
1427
            try:
1428
                return adapters[adapter_key]
1429
            except KeyError:
1430
                adapter_factory = adapter_registry.get(adapter_key)
1431
                adapter = adapter_factory(self)
1432
                adapters[adapter_key] = adapter
1433
                return adapter
0.17.2 by Robert Collins
Core proof of concept working.
1434
        # This will go up to fulltexts for gc to gc fetching, which isn't
1435
        # ideal.
3735.32.19 by John Arbash Meinel
Get rid of the 'delta' flag to GroupCompressor. It didn't do anything anyway.
1436
        self._compressor = GroupCompressor()
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
1437
        self._unadded_refs = {}
0.17.5 by Robert Collins
nograph tests completely passing.
1438
        keys_to_add = []
0.17.6 by Robert Collins
Cap group size at 20MB internal buffer. (Probably way too big).
1439
        def flush():
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
1440
            bytes = self._compressor.flush().to_bytes()
0.17.6 by Robert Collins
Cap group size at 20MB internal buffer. (Probably way too big).
1441
            index, start, length = self._access.add_raw_records(
0.25.7 by John Arbash Meinel
Have the GroupCompressBlock decide how to compress the header and content.
1442
                [(None, len(bytes))], bytes)[0]
0.17.6 by Robert Collins
Cap group size at 20MB internal buffer. (Probably way too big).
1443
            nodes = []
1444
            for key, reads, refs in keys_to_add:
1445
                nodes.append((key, "%d %d %s" % (start, length, reads), refs))
1446
            self._index.add_records(nodes, random_id=random_id)
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1447
            self._unadded_refs = {}
1448
            del keys_to_add[:]
3735.32.19 by John Arbash Meinel
Get rid of the 'delta' flag to GroupCompressor. It didn't do anything anyway.
1449
            self._compressor = GroupCompressor()
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1450
0.20.15 by John Arbash Meinel
Change so that regions that have lots of copies get converted back
1451
        last_prefix = None
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1452
        max_fulltext_len = 0
0.25.11 by John Arbash Meinel
Slightly different handling of large texts.
1453
        max_fulltext_prefix = None
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
1454
        insert_manager = None
1455
        block_start = None
1456
        block_length = None
3735.36.15 by John Arbash Meinel
Set 'combine_backing_indices=False' as the default for text and chk indices.
1457
        # XXX: TODO: remove this, it is just for safety checking for now
1458
        inserted_keys = set()
0.17.2 by Robert Collins
Core proof of concept working.
1459
        for record in stream:
0.17.5 by Robert Collins
nograph tests completely passing.
1460
            # Raise an error when a record is missing.
1461
            if record.storage_kind == 'absent':
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1462
                raise errors.RevisionNotPresent(record.key, self)
3735.36.15 by John Arbash Meinel
Set 'combine_backing_indices=False' as the default for text and chk indices.
1463
            if random_id:
1464
                if record.key in inserted_keys:
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1465
                    trace.note('Insert claimed random_id=True,'
1466
                               ' but then inserted %r two times', record.key)
3735.36.15 by John Arbash Meinel
Set 'combine_backing_indices=False' as the default for text and chk indices.
1467
                    continue
1468
                inserted_keys.add(record.key)
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1469
            if reuse_blocks:
1470
                # If the reuse_blocks flag is set, check to see if we can just
1471
                # copy a groupcompress block as-is.
1472
                if record.storage_kind == 'groupcompress-block':
1473
                    # Insert the raw block into the target repo
1474
                    insert_manager = record._manager
3735.2.163 by John Arbash Meinel
Merge bzr.dev 4187, and revert the change to fix refcycle issues.
1475
                    insert_manager._check_rebuild_block()
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1476
                    bytes = record._manager._block.to_bytes()
1477
                    _, start, length = self._access.add_raw_records(
1478
                        [(None, len(bytes))], bytes)[0]
1479
                    del bytes
1480
                    block_start = start
1481
                    block_length = length
1482
                if record.storage_kind in ('groupcompress-block',
1483
                                           'groupcompress-block-ref'):
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1484
                    if insert_manager is None:
1485
                        raise AssertionError('No insert_manager set')
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1486
                    value = "%d %d %d %d" % (block_start, block_length,
1487
                                             record._start, record._end)
1488
                    nodes = [(record.key, value, (record.parents,))]
3735.38.1 by John Arbash Meinel
Change the delta byte stream to remove the 'source length' entry.
1489
                    # TODO: Consider buffering up many nodes to be added, not
1490
                    #       sure how much overhead this has, but we're seeing
1491
                    #       ~23s / 120s in add_records calls
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
1492
                    self._index.add_records(nodes, random_id=random_id)
1493
                    continue
0.20.18 by John Arbash Meinel
Implement new handling of get_bytes_as(), and get_missing_compression_parent_keys()
1494
            try:
0.23.52 by John Arbash Meinel
Use the max_delta flag.
1495
                bytes = record.get_bytes_as('fulltext')
0.20.18 by John Arbash Meinel
Implement new handling of get_bytes_as(), and get_missing_compression_parent_keys()
1496
            except errors.UnavailableRepresentation:
0.17.5 by Robert Collins
nograph tests completely passing.
1497
                adapter_key = record.storage_kind, 'fulltext'
1498
                adapter = get_adapter(adapter_key)
0.20.21 by John Arbash Meinel
Merge the chk sorting code.
1499
                bytes = adapter.get_bytes(record)
0.20.13 by John Arbash Meinel
Play around a bit.
1500
            if len(record.key) > 1:
1501
                prefix = record.key[0]
0.25.11 by John Arbash Meinel
Slightly different handling of large texts.
1502
                soft = (prefix == last_prefix)
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1503
            else:
1504
                prefix = None
0.25.11 by John Arbash Meinel
Slightly different handling of large texts.
1505
                soft = False
1506
            if max_fulltext_len < len(bytes):
1507
                max_fulltext_len = len(bytes)
1508
                max_fulltext_prefix = prefix
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1509
            (found_sha1, start_point, end_point,
1510
             type) = self._compressor.compress(record.key,
1511
                                               bytes, record.sha1, soft=soft,
1512
                                               nostore_sha=nostore_sha)
1513
            # delta_ratio = float(len(bytes)) / (end_point - start_point)
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1514
            # Check if we want to continue to include that text
0.25.11 by John Arbash Meinel
Slightly different handling of large texts.
1515
            if (prefix == max_fulltext_prefix
1516
                and end_point < 2 * max_fulltext_len):
1517
                # As long as we are on the same file_id, we will fill at least
1518
                # 2 * max_fulltext_len
1519
                start_new_block = False
1520
            elif end_point > 4*1024*1024:
1521
                start_new_block = True
1522
            elif (prefix is not None and prefix != last_prefix
1523
                  and end_point > 2*1024*1024):
1524
                start_new_block = True
1525
            else:
1526
                start_new_block = False
0.25.10 by John Arbash Meinel
Play around with detecting compression breaks.
1527
            last_prefix = prefix
1528
            if start_new_block:
1529
                self._compressor.pop_last()
1530
                flush()
1531
                max_fulltext_len = len(bytes)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1532
                (found_sha1, start_point, end_point,
1533
                 type) = self._compressor.compress(record.key, bytes,
1534
                                                   record.sha1)
0.17.26 by Robert Collins
Working better --gc-plain-chk.
1535
            if record.key[-1] is None:
1536
                key = record.key[:-1] + ('sha1:' + found_sha1,)
1537
            else:
1538
                key = record.key
1539
            self._unadded_refs[key] = record.parents
0.17.3 by Robert Collins
new encoder, allows non monotonically increasing sequence matches for moar compression.
1540
            yield found_sha1
3735.2.164 by John Arbash Meinel
Fix a critical bug that caused problems with the index entries.
1541
            keys_to_add.append((key, '%d %d' % (start_point, end_point),
0.17.5 by Robert Collins
nograph tests completely passing.
1542
                (record.parents,)))
0.17.8 by Robert Collins
Flush pending updates at the end of _insert_record_stream
1543
        if len(keys_to_add):
1544
            flush()
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
1545
        self._compressor = None
0.17.5 by Robert Collins
nograph tests completely passing.
1546
1547
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1548
        """Iterate over the lines in the versioned files from keys.
1549
1550
        This may return lines from other keys. Each item the returned
1551
        iterator yields is a tuple of a line and a text version that that line
1552
        is present in (not introduced in).
1553
1554
        Ordering of results is in whatever order is most suitable for the
1555
        underlying storage format.
1556
1557
        If a progress bar is supplied, it may be used to indicate progress.
1558
        The caller is responsible for cleaning up progress bars (because this
1559
        is an iterator).
1560
1561
        NOTES:
1562
         * Lines are normalised by the underlying store: they will all have \n
1563
           terminators.
1564
         * Lines are returned in arbitrary order.
1565
1566
        :return: An iterator over (line, key).
1567
        """
1568
        keys = set(keys)
1569
        total = len(keys)
1570
        # we don't care about inclusions, the caller cares.
1571
        # but we need to setup a list of records to visit.
1572
        # we need key, position, length
1573
        for key_idx, record in enumerate(self.get_record_stream(keys,
1574
            'unordered', True)):
1575
            # XXX: todo - optimise to use less than full texts.
1576
            key = record.key
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
1577
            if pb is not None:
1578
                pb.update('Walking content', key_idx, total)
0.17.5 by Robert Collins
nograph tests completely passing.
1579
            if record.storage_kind == 'absent':
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1580
                raise errors.RevisionNotPresent(key, self)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1581
            lines = osutils.split_lines(record.get_bytes_as('fulltext'))
0.17.5 by Robert Collins
nograph tests completely passing.
1582
            for line in lines:
1583
                yield line, key
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
1584
        if pb is not None:
1585
            pb.update('Walking content', total, total)
0.17.5 by Robert Collins
nograph tests completely passing.
1586
1587
    def keys(self):
1588
        """See VersionedFiles.keys."""
1589
        if 'evil' in debug.debug_flags:
1590
            trace.mutter_callsite(2, "keys scales with size of history")
3735.31.7 by John Arbash Meinel
Start bringing in stacking support for Groupcompress repos.
1591
        sources = [self._index] + self._fallback_vfs
0.17.5 by Robert Collins
nograph tests completely passing.
1592
        result = set()
1593
        for source in sources:
1594
            result.update(source.keys())
1595
        return result
1596
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1597
1598
class _GCGraphIndex(object):
1599
    """Mapper from GroupCompressVersionedFiles needs into GraphIndex storage."""
1600
0.17.9 by Robert Collins
Initial stab at repository format support.
1601
    def __init__(self, graph_index, is_locked, parents=True,
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
1602
        add_callback=None, track_external_parent_refs=False,
1603
        inconsistency_fatal=True):
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1604
        """Construct a _GCGraphIndex on a graph_index.
1605
1606
        :param graph_index: An implementation of bzrlib.index.GraphIndex.
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1607
        :param is_locked: A callback, returns True if the index is locked and
1608
            thus usable.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1609
        :param parents: If True, record knits parents, if not do not record
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1610
            parents.
1611
        :param add_callback: If not None, allow additions to the index and call
1612
            this callback with a list of added GraphIndex nodes:
1613
            [(node, value, node_refs), ...]
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
1614
        :param track_external_parent_refs: As keys are added, keep track of the
1615
            keys they reference, so that we can query get_missing_parents(),
1616
            etc.
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
1617
        :param inconsistency_fatal: When asked to add records that are already
1618
            present, and the details are inconsistent with the existing
1619
            record, raise an exception instead of warning (and skipping the
1620
            record).
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1621
        """
1622
        self._add_callback = add_callback
1623
        self._graph_index = graph_index
1624
        self._parents = parents
1625
        self.has_graph = parents
1626
        self._is_locked = is_locked
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
1627
        self._inconsistency_fatal = inconsistency_fatal
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
1628
        if track_external_parent_refs:
1629
            self._key_dependencies = knit._KeyRefs()
1630
        else:
1631
            self._key_dependencies = None
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
1632
0.17.5 by Robert Collins
nograph tests completely passing.
1633
    def add_records(self, records, random_id=False):
1634
        """Add multiple records to the index.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1635
0.17.5 by Robert Collins
nograph tests completely passing.
1636
        This function does not insert data into the Immutable GraphIndex
1637
        backing the KnitGraphIndex, instead it prepares data for insertion by
1638
        the caller and checks that it is safe to insert then calls
1639
        self._add_callback with the prepared GraphIndex nodes.
1640
1641
        :param records: a list of tuples:
1642
                         (key, options, access_memo, parents).
1643
        :param random_id: If True the ids being added were randomly generated
1644
            and no check for existence will be performed.
1645
        """
1646
        if not self._add_callback:
1647
            raise errors.ReadOnlyError(self)
1648
        # we hope there are no repositories with inconsistent parentage
1649
        # anymore.
1650
1651
        changed = False
1652
        keys = {}
1653
        for (key, value, refs) in records:
1654
            if not self._parents:
1655
                if refs:
1656
                    for ref in refs:
1657
                        if ref:
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
1658
                            raise errors.KnitCorrupt(self,
0.17.5 by Robert Collins
nograph tests completely passing.
1659
                                "attempt to add node with parents "
1660
                                "in parentless index.")
1661
                    refs = ()
1662
                    changed = True
1663
            keys[key] = (value, refs)
1664
        # check for dups
1665
        if not random_id:
1666
            present_nodes = self._get_entries(keys)
1667
            for (index, key, value, node_refs) in present_nodes:
1668
                if node_refs != keys[key][1]:
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
1669
                    details = '%s %s %s' % (key, (value, node_refs), keys[key])
1670
                    if self._inconsistency_fatal:
1671
                        raise errors.KnitCorrupt(self, "inconsistent details"
1672
                                                 " in add_records: %s" %
1673
                                                 details)
1674
                    else:
1675
                        trace.warning("inconsistent details in skipped"
1676
                                      " record: %s", details)
0.17.5 by Robert Collins
nograph tests completely passing.
1677
                del keys[key]
1678
                changed = True
1679
        if changed:
1680
            result = []
1681
            if self._parents:
1682
                for key, (value, node_refs) in keys.iteritems():
1683
                    result.append((key, value, node_refs))
1684
            else:
1685
                for key, (value, node_refs) in keys.iteritems():
1686
                    result.append((key, value))
1687
            records = result
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
1688
        key_dependencies = self._key_dependencies
1689
        if key_dependencies is not None and self._parents:
1690
            for key, value, refs in records:
1691
                parents = refs[0]
1692
                key_dependencies.add_references(key, parents)
0.17.5 by Robert Collins
nograph tests completely passing.
1693
        self._add_callback(records)
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1694
0.17.5 by Robert Collins
nograph tests completely passing.
1695
    def _check_read(self):
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1696
        """Raise an exception if reads are not permitted."""
0.17.5 by Robert Collins
nograph tests completely passing.
1697
        if not self._is_locked():
1698
            raise errors.ObjectNotLocked(self)
1699
0.17.2 by Robert Collins
Core proof of concept working.
1700
    def _check_write_ok(self):
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1701
        """Raise an exception if writes are not permitted."""
0.17.2 by Robert Collins
Core proof of concept working.
1702
        if not self._is_locked():
1703
            raise errors.ObjectNotLocked(self)
1704
0.17.5 by Robert Collins
nograph tests completely passing.
1705
    def _get_entries(self, keys, check_present=False):
1706
        """Get the entries for keys.
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1707
1708
        Note: Callers are responsible for checking that the index is locked
1709
        before calling this method.
1710
0.17.5 by Robert Collins
nograph tests completely passing.
1711
        :param keys: An iterable of index key tuples.
1712
        """
1713
        keys = set(keys)
1714
        found_keys = set()
1715
        if self._parents:
1716
            for node in self._graph_index.iter_entries(keys):
1717
                yield node
1718
                found_keys.add(node[1])
1719
        else:
1720
            # adapt parentless index to the rest of the code.
1721
            for node in self._graph_index.iter_entries(keys):
1722
                yield node[0], node[1], node[2], ()
1723
                found_keys.add(node[1])
1724
        if check_present:
1725
            missing_keys = keys.difference(found_keys)
1726
            if missing_keys:
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
1727
                raise errors.RevisionNotPresent(missing_keys.pop(), self)
0.17.5 by Robert Collins
nograph tests completely passing.
1728
1729
    def get_parent_map(self, keys):
1730
        """Get a map of the parents of keys.
1731
1732
        :param keys: The keys to look up parents for.
1733
        :return: A mapping from keys to parents. Absent keys are absent from
1734
            the mapping.
1735
        """
1736
        self._check_read()
1737
        nodes = self._get_entries(keys)
1738
        result = {}
1739
        if self._parents:
1740
            for node in nodes:
1741
                result[node[1]] = node[3][0]
1742
        else:
1743
            for node in nodes:
1744
                result[node[1]] = None
1745
        return result
1746
4343.3.1 by John Arbash Meinel
Set 'supports_external_lookups=True' for dev6 repositories.
1747
    def get_missing_parents(self):
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
1748
        """Return the keys of missing parents."""
1749
        # Copied from _KnitGraphIndex.get_missing_parents
1750
        # We may have false positives, so filter those out.
1751
        self._key_dependencies.add_keys(
1752
            self.get_parent_map(self._key_dependencies.get_unsatisfied_refs()))
1753
        return frozenset(self._key_dependencies.get_unsatisfied_refs())
4343.3.1 by John Arbash Meinel
Set 'supports_external_lookups=True' for dev6 repositories.
1754
0.17.5 by Robert Collins
nograph tests completely passing.
1755
    def get_build_details(self, keys):
1756
        """Get the various build details for keys.
1757
1758
        Ghosts are omitted from the result.
1759
1760
        :param keys: An iterable of keys.
1761
        :return: A dict of key:
1762
            (index_memo, compression_parent, parents, record_details).
1763
            index_memo
1764
                opaque structure to pass to read_records to extract the raw
1765
                data
1766
            compression_parent
1767
                Content that this record is built upon, may be None
1768
            parents
1769
                Logical parents of this node
1770
            record_details
1771
                extra information about the content which needs to be passed to
1772
                Factory.parse_record
1773
        """
1774
        self._check_read()
1775
        result = {}
0.20.29 by Ian Clatworthy
groupcompress.py code cleanups
1776
        entries = self._get_entries(keys)
0.17.5 by Robert Collins
nograph tests completely passing.
1777
        for entry in entries:
1778
            key = entry[1]
1779
            if not self._parents:
1780
                parents = None
1781
            else:
1782
                parents = entry[3][0]
1783
            method = 'group'
1784
            result[key] = (self._node_to_position(entry),
1785
                                  None, parents, (method, None))
1786
        return result
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1787
0.17.5 by Robert Collins
nograph tests completely passing.
1788
    def keys(self):
1789
        """Get all the keys in the collection.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1790
0.17.5 by Robert Collins
nograph tests completely passing.
1791
        The keys are not ordered.
1792
        """
1793
        self._check_read()
1794
        return [node[1] for node in self._graph_index.iter_all_entries()]
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
1795
0.17.5 by Robert Collins
nograph tests completely passing.
1796
    def _node_to_position(self, node):
1797
        """Convert an index value to position details."""
1798
        bits = node[2].split(' ')
1799
        # It would be nice not to read the entire gzip.
1800
        start = int(bits[0])
1801
        stop = int(bits[1])
1802
        basis_end = int(bits[2])
1803
        delta_end = int(bits[3])
1804
        return node[0], start, stop, basis_end, delta_end
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
1805
4343.3.2 by John Arbash Meinel
All stacking tests seem to be passing for dev6 repos
1806
    def scan_unvalidated_index(self, graph_index):
1807
        """Inform this _GCGraphIndex that there is an unvalidated index.
1808
1809
        This allows this _GCGraphIndex to keep track of any missing
1810
        compression parents we may want to have filled in to make those
1811
        indices valid.
1812
1813
        :param graph_index: A GraphIndex
1814
        """
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
1815
        if self._key_dependencies is not None:
1816
            # Add parent refs from graph_index (and discard parent refs that
1817
            # the graph_index has).
1818
            add_refs = self._key_dependencies.add_references
1819
            for node in graph_index.iter_all_entries():
1820
                add_refs(node[1], node[3][0])
4343.3.2 by John Arbash Meinel
All stacking tests seem to be passing for dev6 repos
1821
1822
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
1823
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
1824
from bzrlib._groupcompress_py import (
1825
    apply_delta,
3735.40.19 by John Arbash Meinel
Implement apply_delta_to_source which doesn't have to malloc another string.
1826
    apply_delta_to_source,
3735.40.11 by John Arbash Meinel
Implement make_delta and apply_delta.
1827
    encode_base128_int,
1828
    decode_base128_int,
4300.1.1 by John Arbash Meinel
Add the ability to convert a gc block into 'human readable' form.
1829
    decode_copy_instruction,
3735.40.13 by John Arbash Meinel
Rename EquivalenceTable to LinesDeltaIndex.
1830
    LinesDeltaIndex,
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
1831
    )
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
1832
try:
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1833
    from bzrlib._groupcompress_pyx import (
1834
        apply_delta,
3735.40.19 by John Arbash Meinel
Implement apply_delta_to_source which doesn't have to malloc another string.
1835
        apply_delta_to_source,
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1836
        DeltaIndex,
3735.40.16 by John Arbash Meinel
Implement (de|en)code_base128_int in pyrex.
1837
        encode_base128_int,
1838
        decode_base128_int,
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1839
        )
3735.40.2 by John Arbash Meinel
Add a groupcompress.encode_copy_instruction function.
1840
    GroupCompressor = PyrexGroupCompressor
0.18.14 by John Arbash Meinel
A bit more work, not really usable yet.
1841
except ImportError:
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
1842
    GroupCompressor = PythonGroupCompressor
1843