/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5652.2.2 by Martin Pool
Rename _fallback_vfs to _immediate_fallbacks
1
# Copyright (C) 2006-2011 Canonical Ltd
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
16
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
17
"""Versioned text file storage api."""
18
6379.6.1 by Jelmer Vernooij
Import absolute_import in a few places.
19
from __future__ import absolute_import
20
3350.8.2 by Robert Collins
stacked get_parent_map.
21
from copy import copy
6631.3.1 by Martin
Run 2to3 map fixer and refactor after
22
import itertools
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
23
import os
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
24
import struct
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
25
from zlib import adler32
26
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
27
from .lazy_import import lazy_import
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
28
lazy_import(globals(), """
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
29
from breezy import (
4454.3.65 by John Arbash Meinel
Tests that VF implementations support .get_annotator()
30
    annotate,
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
31
    bencode,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
32
    errors,
4593.5.36 by John Arbash Meinel
a few more implementations of the interface.
33
    graph as _mod_graph,
3735.32.18 by John Arbash Meinel
We now support generating a network stream.
34
    groupcompress,
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
35
    index,
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
36
    knit,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
37
    osutils,
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
38
    multiparent,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
39
    tsort,
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
40
    revision,
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
41
    urlutils,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
42
    )
43
""")
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
44
from .registry import Registry
45
from .sixish import (
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
46
    BytesIO,
6634.1.1 by Martin
Remove direct use of future_builtins module
47
    zip,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
48
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
49
from .textmerge import TextMerge
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
50
51
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
52
adapter_registry = Registry()
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
53
adapter_registry.register_lazy(('knit-delta-gz', 'fulltext'), 'breezy.knit',
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
54
    'DeltaPlainToFullText')
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
55
adapter_registry.register_lazy(('knit-ft-gz', 'fulltext'), 'breezy.knit',
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
56
    'FTPlainToFullText')
57
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'knit-delta-gz'),
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
58
    'breezy.knit', 'DeltaAnnotatedToUnannotated')
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
59
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'fulltext'),
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
60
    'breezy.knit', 'DeltaAnnotatedToFullText')
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
61
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'knit-ft-gz'),
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
62
    'breezy.knit', 'FTAnnotatedToUnannotated')
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
63
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'fulltext'),
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
64
    'breezy.knit', 'FTAnnotatedToFullText')
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
65
# adapter_registry.register_lazy(('knit-annotated-ft-gz', 'chunked'),
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
66
#     'breezy.knit', 'FTAnnotatedToChunked')
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
67
68
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
69
class ContentFactory(object):
70
    """Abstract interface for insertion and retrieval from a VersionedFile.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
71
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
72
    :ivar sha1: None, or the sha1 of the content fulltext.
73
    :ivar storage_kind: The native storage kind of this factory. One of
74
        'mpdiff', 'knit-annotated-ft', 'knit-annotated-delta', 'knit-ft',
75
        'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
76
        'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'.
77
    :ivar key: The key of this content. Each key is a tuple with a single
78
        string in it.
79
    :ivar parents: A tuple of parent keys for self.key. If the object has
80
        no parent information, None (as opposed to () for an empty list of
81
        parents).
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
82
    """
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
83
84
    def __init__(self):
85
        """Create a ContentFactory."""
86
        self.sha1 = None
87
        self.storage_kind = None
88
        self.key = None
89
        self.parents = None
90
91
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
92
class ChunkedContentFactory(ContentFactory):
93
    """Static data content factory.
94
95
    This takes a 'chunked' list of strings. The only requirement on 'chunked' is
96
    that ''.join(lines) becomes a valid fulltext. A tuple of a single string
97
    satisfies this, as does a list of lines.
98
99
    :ivar sha1: None, or the sha1 of the content fulltext.
100
    :ivar storage_kind: The native storage kind of this factory. Always
3890.2.2 by John Arbash Meinel
Change the signature to report the storage kind as 'chunked'
101
        'chunked'
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
102
    :ivar key: The key of this content. Each key is a tuple with a single
103
        string in it.
104
    :ivar parents: A tuple of parent keys for self.key. If the object has
105
        no parent information, None (as opposed to () for an empty list of
106
        parents).
107
     """
108
109
    def __init__(self, key, parents, sha1, chunks):
110
        """Create a ContentFactory."""
111
        self.sha1 = sha1
3890.2.2 by John Arbash Meinel
Change the signature to report the storage kind as 'chunked'
112
        self.storage_kind = 'chunked'
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
113
        self.key = key
114
        self.parents = parents
115
        self._chunks = chunks
116
117
    def get_bytes_as(self, storage_kind):
118
        if storage_kind == 'chunked':
119
            return self._chunks
120
        elif storage_kind == 'fulltext':
121
            return ''.join(self._chunks)
122
        raise errors.UnavailableRepresentation(self.key, storage_kind,
123
            self.storage_kind)
124
125
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
126
class FulltextContentFactory(ContentFactory):
127
    """Static data content factory.
128
129
    This takes a fulltext when created and just returns that during
130
    get_bytes_as('fulltext').
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
131
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
132
    :ivar sha1: None, or the sha1 of the content fulltext.
133
    :ivar storage_kind: The native storage kind of this factory. Always
134
        'fulltext'.
135
    :ivar key: The key of this content. Each key is a tuple with a single
136
        string in it.
137
    :ivar parents: A tuple of parent keys for self.key. If the object has
138
        no parent information, None (as opposed to () for an empty list of
139
        parents).
140
     """
141
142
    def __init__(self, key, parents, sha1, text):
143
        """Create a ContentFactory."""
144
        self.sha1 = sha1
145
        self.storage_kind = 'fulltext'
146
        self.key = key
147
        self.parents = parents
148
        self._text = text
149
150
    def get_bytes_as(self, storage_kind):
151
        if storage_kind == self.storage_kind:
152
            return self._text
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
153
        elif storage_kind == 'chunked':
3976.2.1 by Robert Collins
Use a list not a tuple for chunks returned from FullTextContentFactory objects, because otherwise code tries to assign to tuples.
154
            return [self._text]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
155
        raise errors.UnavailableRepresentation(self.key, storage_kind,
156
            self.storage_kind)
157
158
159
class AbsentContentFactory(ContentFactory):
3350.3.12 by Robert Collins
Generate streams with absent records.
160
    """A placeholder content factory for unavailable texts.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
161
3350.3.12 by Robert Collins
Generate streams with absent records.
162
    :ivar sha1: None.
163
    :ivar storage_kind: 'absent'.
164
    :ivar key: The key of this content. Each key is a tuple with a single
165
        string in it.
166
    :ivar parents: None.
167
    """
168
169
    def __init__(self, key):
170
        """Create a ContentFactory."""
171
        self.sha1 = None
172
        self.storage_kind = 'absent'
173
        self.key = key
174
        self.parents = None
175
4537.2.1 by John Arbash Meinel
Add AbsentContentFactory.get_bytes_as()
176
    def get_bytes_as(self, storage_kind):
177
        raise ValueError('A request was made for key: %s, but that'
178
                         ' content is not available, and the calling'
179
                         ' code does not handle if it is missing.'
180
                         % (self.key,))
181
3350.3.12 by Robert Collins
Generate streams with absent records.
182
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
183
class AdapterFactory(ContentFactory):
184
    """A content factory to adapt between key prefix's."""
185
186
    def __init__(self, key, parents, adapted):
187
        """Create an adapter factory instance."""
188
        self.key = key
189
        self.parents = parents
190
        self._adapted = adapted
191
192
    def __getattr__(self, attr):
193
        """Return a member from the adapted object."""
194
        if attr in ('key', 'parents'):
195
            return self.__dict__[attr]
196
        else:
197
            return getattr(self._adapted, attr)
198
199
3350.3.14 by Robert Collins
Deprecate VersionedFile.join.
200
def filter_absent(record_stream):
201
    """Adapt a record stream to remove absent records."""
202
    for record in record_stream:
203
        if record.storage_kind != 'absent':
204
            yield record
205
206
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
207
class _MPDiffGenerator(object):
208
    """Pull out the functionality for generating mp_diffs."""
209
210
    def __init__(self, vf, keys):
211
        self.vf = vf
212
        # This is the order the keys were requested in
213
        self.ordered_keys = tuple(keys)
214
        # keys + their parents, what we need to compute the diffs
215
        self.needed_keys = ()
216
        # Map from key: mp_diff
217
        self.diffs = {}
218
        # Map from key: parents_needed (may have ghosts)
219
        self.parent_map = {}
220
        # Parents that aren't present
221
        self.ghost_parents = ()
222
        # Map from parent_key => number of children for this text
223
        self.refcounts = {}
224
        # Content chunks that are cached while we still need them
225
        self.chunks = {}
226
227
    def _find_needed_keys(self):
228
        """Find the set of keys we need to request.
229
230
        This includes all the original keys passed in, and the non-ghost
231
        parents of those keys.
232
233
        :return: (needed_keys, refcounts)
234
            needed_keys is the set of all texts we need to extract
235
            refcounts is a dict of {key: num_children} letting us know when we
236
                no longer need to cache a given parent text
237
        """
238
        # All the keys and their parents
239
        needed_keys = set(self.ordered_keys)
240
        parent_map = self.vf.get_parent_map(needed_keys)
241
        self.parent_map = parent_map
242
        # TODO: Should we be using a different construct here? I think this
243
        #       uses difference_update internally, and we expect the result to
244
        #       be tiny
245
        missing_keys = needed_keys.difference(parent_map)
246
        if missing_keys:
247
            raise errors.RevisionNotPresent(list(missing_keys)[0], self.vf)
248
        # Parents that might be missing. They are allowed to be ghosts, but we
249
        # should check for them
250
        refcounts = {}
251
        setdefault = refcounts.setdefault
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
252
        just_parents = set()
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
253
        for child_key, parent_keys in parent_map.iteritems():
254
            if not parent_keys:
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
255
                # parent_keys may be None if a given VersionedFile claims to
256
                # not support graph operations.
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
257
                continue
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
258
            just_parents.update(parent_keys)
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
259
            needed_keys.update(parent_keys)
260
            for p in parent_keys:
261
                refcounts[p] = setdefault(p, 0) + 1
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
262
        just_parents.difference_update(parent_map)
263
        # Remove any parents that are actually ghosts from the needed set
264
        self.present_parents = set(self.vf.get_parent_map(just_parents))
265
        self.ghost_parents = just_parents.difference(self.present_parents)
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
266
        needed_keys.difference_update(self.ghost_parents)
267
        self.needed_keys = needed_keys
268
        self.refcounts = refcounts
269
        return needed_keys, refcounts
270
271
    def _compute_diff(self, key, parent_lines, lines):
272
        """Compute a single mp_diff, and store it in self._diffs"""
273
        if len(parent_lines) > 0:
274
            # XXX: _extract_blocks is not usefully defined anywhere...
275
            #      It was meant to extract the left-parent diff without
276
            #      having to recompute it for Knit content (pack-0.92,
277
            #      etc). That seems to have regressed somewhere
278
            left_parent_blocks = self.vf._extract_blocks(key,
279
                parent_lines[0], lines)
280
        else:
281
            left_parent_blocks = None
282
        diff = multiparent.MultiParent.from_lines(lines,
283
                    parent_lines, left_parent_blocks)
284
        self.diffs[key] = diff
285
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
286
    def _process_one_record(self, key, this_chunks):
287
        parent_keys = None
288
        if key in self.parent_map:
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
289
            # This record should be ready to diff, since we requested
290
            # content in 'topological' order
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
291
            parent_keys = self.parent_map.pop(key)
5374.2.3 by John Arbash Meinel
Replace the generic VersionedFiles.make_mpdiffs interface.
292
            # If a VersionedFile claims 'no-graph' support, then it may return
293
            # None for any parent request, so we replace it with an empty tuple
294
            if parent_keys is None:
295
                parent_keys = ()
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
296
            parent_lines = []
297
            for p in parent_keys:
298
                # Alternatively we could check p not in self.needed_keys, but
299
                # ghost_parents should be tiny versus huge
300
                if p in self.ghost_parents:
301
                    continue
302
                refcount = self.refcounts[p]
303
                if refcount == 1: # Last child reference
304
                    self.refcounts.pop(p)
305
                    parent_chunks = self.chunks.pop(p)
306
                else:
307
                    self.refcounts[p] = refcount - 1
308
                    parent_chunks = self.chunks[p]
5374.2.4 by John Arbash Meinel
Cache the lines as extracted if they are used right now.
309
                p_lines = osutils.chunks_to_lines(parent_chunks)
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
310
                # TODO: Should we cache the line form? We did the
311
                #       computation to get it, but storing it this way will
312
                #       be less memory efficient...
5374.2.4 by John Arbash Meinel
Cache the lines as extracted if they are used right now.
313
                parent_lines.append(p_lines)
314
                del p_lines
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
315
            lines = osutils.chunks_to_lines(this_chunks)
5374.2.4 by John Arbash Meinel
Cache the lines as extracted if they are used right now.
316
            # Since we needed the lines, we'll go ahead and cache them this way
317
            this_chunks = lines
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
318
            self._compute_diff(key, parent_lines, lines)
5374.2.4 by John Arbash Meinel
Cache the lines as extracted if they are used right now.
319
            del lines
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
320
        # Is this content required for any more children?
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
321
        if key in self.refcounts:
322
            self.chunks[key] = this_chunks
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
323
324
    def _extract_diffs(self):
325
        needed_keys, refcounts = self._find_needed_keys()
326
        for record in self.vf.get_record_stream(needed_keys,
327
                                                'topological', True):
328
            if record.storage_kind == 'absent':
329
                raise errors.RevisionNotPresent(record.key, self.vf)
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
330
            self._process_one_record(record.key,
331
                                     record.get_bytes_as('chunked'))
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
332
        
333
    def compute_diffs(self):
334
        self._extract_diffs()
335
        dpop = self.diffs.pop
336
        return [dpop(k) for k in self.ordered_keys]
337
338
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
339
class VersionedFile(object):
340
    """Versioned text file storage.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
341
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
342
    A versioned file manages versions of line-based text files,
343
    keeping track of the originating version for each line.
344
345
    To clients the "lines" of the file are represented as a list of
346
    strings. These strings will typically have terminal newline
347
    characters, but this is not required.  In particular files commonly
348
    do not have a newline at the end of the file.
349
350
    Texts are identified by a version-id string.
351
    """
352
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
353
    @staticmethod
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
354
    def check_not_reserved_id(version_id):
355
        revision.check_not_reserved_id(version_id)
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
356
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
357
    def copy_to(self, name, transport):
358
        """Copy this versioned file to name on transport."""
359
        raise NotImplementedError(self.copy_to)
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
360
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
361
    def get_record_stream(self, versions, ordering, include_delta_closure):
362
        """Get a stream of records for versions.
363
364
        :param versions: The versions to include. Each version is a tuple
365
            (version,).
366
        :param ordering: Either 'unordered' or 'topological'. A topologically
367
            sorted stream has compression parents strictly before their
368
            children.
369
        :param include_delta_closure: If True then the closure across any
3350.3.22 by Robert Collins
Review feedback.
370
            compression parents will be included (in the data content of the
371
            stream, not in the emitted records). This guarantees that
372
            'fulltext' can be used successfully on every record.
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
373
        :return: An iterator of ContentFactory objects, each of which is only
374
            valid until the iterator is advanced.
375
        """
376
        raise NotImplementedError(self.get_record_stream)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
377
378
    def has_version(self, version_id):
379
        """Returns whether version is present."""
380
        raise NotImplementedError(self.has_version)
381
5195.3.26 by Parth Malwankar
reverted changes done to insert_record_stream API
382
    def insert_record_stream(self, stream):
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
383
        """Insert a record stream into this versioned file.
384
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
385
        :param stream: A stream of records to insert.
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
386
        :return: None
387
        :seealso VersionedFile.get_record_stream:
388
        """
389
        raise NotImplementedError
390
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
391
    def add_lines(self, version_id, parents, lines, parent_texts=None,
2805.6.7 by Robert Collins
Review feedback.
392
        left_matching_blocks=None, nostore_sha=None, random_id=False,
393
        check_content=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
394
        """Add a single text on top of the versioned file.
395
396
        Must raise RevisionAlreadyPresent if the new version is
397
        already present in file history.
398
399
        Must raise RevisionNotPresent if any of the given parents are
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
400
        not present in file history.
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
401
402
        :param lines: A list of lines. Each line must be a bytestring. And all
403
            of them except the last must be terminated with \n and contain no
404
            other \n's. The last line may either contain no \n's or a single
405
            terminated \n. If the lines list does meet this constraint the add
406
            routine may error or may succeed - but you will be unable to read
407
            the data back accurately. (Checking the lines have been split
2805.6.7 by Robert Collins
Review feedback.
408
            correctly is expensive and extremely unlikely to catch bugs so it
409
            is not done at runtime unless check_content is True.)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
410
        :param parent_texts: An optional dictionary containing the opaque
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
411
            representations of some or all of the parents of version_id to
412
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
413
            returned by add_lines or data corruption can be caused.
2520.4.148 by Aaron Bentley
Updates from review
414
        :param left_matching_blocks: a hint about which areas are common
415
            between the text and its left-hand-parent.  The format is
416
            the SequenceMatcher.get_matching_blocks format.
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
417
        :param nostore_sha: Raise ExistingContent and do not add the lines to
418
            the versioned file if the digest of the lines matches this.
2805.6.4 by Robert Collins
Don't check for existing versions when adding texts with random revision ids.
419
        :param random_id: If True a random id has been selected rather than
420
            an id determined by some deterministic process such as a converter
421
            from a foreign VCS. When True the backend may choose not to check
422
            for uniqueness of the resulting key within the versioned file, so
423
            this should only be done when the result is expected to be unique
424
            anyway.
2805.6.7 by Robert Collins
Review feedback.
425
        :param check_content: If True, the lines supplied are verified to be
426
            bytestrings that are correctly formed lines.
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
427
        :return: The text sha1, the number of bytes in the text, and an opaque
428
                 representation of the inserted version which can be provided
429
                 back to future add_lines calls in the parent_texts dictionary.
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
430
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
431
        self._check_write_ok()
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
432
        return self._add_lines(version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
433
            left_matching_blocks, nostore_sha, random_id, check_content)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
434
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
435
    def _add_lines(self, version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
436
        left_matching_blocks, nostore_sha, random_id, check_content):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
437
        """Helper to do the class specific add_lines."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
438
        raise NotImplementedError(self.add_lines)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
439
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
440
    def add_lines_with_ghosts(self, version_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
441
        parent_texts=None, nostore_sha=None, random_id=False,
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
442
        check_content=True, left_matching_blocks=None):
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
443
        """Add lines to the versioned file, allowing ghosts to be present.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
444
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
445
        This takes the same parameters as add_lines and returns the same.
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
446
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
447
        self._check_write_ok()
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
448
        return self._add_lines_with_ghosts(version_id, parents, lines,
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
449
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
450
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
451
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
452
        nostore_sha, random_id, check_content, left_matching_blocks):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
453
        """Helper to do class specific add_lines_with_ghosts."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
454
        raise NotImplementedError(self.add_lines_with_ghosts)
455
1563.2.19 by Robert Collins
stub out a check for knits.
456
    def check(self, progress_bar=None):
457
        """Check the versioned file for integrity."""
458
        raise NotImplementedError(self.check)
459
1666.1.6 by Robert Collins
Make knit the default format.
460
    def _check_lines_not_unicode(self, lines):
461
        """Check that lines being added to a versioned file are not unicode."""
462
        for line in lines:
463
            if line.__class__ is not str:
464
                raise errors.BzrBadParameterUnicode("lines")
465
466
    def _check_lines_are_lines(self, lines):
467
        """Check that the lines really are full lines without inline EOL."""
468
        for line in lines:
469
            if '\n' in line[:-1]:
470
                raise errors.BzrBadParameterContainsNewline("lines")
471
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
472
    def get_format_signature(self):
473
        """Get a text description of the data encoding in this file.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
474
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
475
        :since: 0.90
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
476
        """
477
        raise NotImplementedError(self.get_format_signature)
478
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
479
    def make_mpdiffs(self, version_ids):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
480
        """Create multiparent diffs for specified versions."""
5374.2.3 by John Arbash Meinel
Replace the generic VersionedFiles.make_mpdiffs interface.
481
        # XXX: Can't use _MPDiffGenerator just yet. This is because version_ids
482
        #      is a list of strings, not keys. And while self.get_record_stream
483
        #      is supported, it takes *keys*, while self.get_parent_map() takes
484
        #      strings... *sigh*
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
485
        knit_versions = set()
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
486
        knit_versions.update(version_ids)
487
        parent_map = self.get_parent_map(version_ids)
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
488
        for version_id in version_ids:
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
489
            try:
490
                knit_versions.update(parent_map[version_id])
491
            except KeyError:
3453.3.1 by Daniel Fischer
Raise the right exception in make_mpdiffs (bug #235687)
492
                raise errors.RevisionNotPresent(version_id, self)
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
493
        # We need to filter out ghosts, because we can't diff against them.
494
        knit_versions = set(self.get_parent_map(knit_versions).keys())
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
495
        lines = dict(zip(knit_versions,
496
            self._get_lf_split_line_list(knit_versions)))
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
497
        diffs = []
498
        for version_id in version_ids:
499
            target = lines[version_id]
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
500
            try:
501
                parents = [lines[p] for p in parent_map[version_id] if p in
502
                    knit_versions]
503
            except KeyError:
3453.3.2 by John Arbash Meinel
Add a test case for the first loop, unable to find a way to trigger the second loop
504
                # I don't know how this could ever trigger.
505
                # parent_map[version_id] was already triggered in the previous
506
                # for loop, and lines[p] has the 'if p in knit_versions' check,
507
                # so we again won't have a KeyError.
3453.3.1 by Daniel Fischer
Raise the right exception in make_mpdiffs (bug #235687)
508
                raise errors.RevisionNotPresent(version_id, self)
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
509
            if len(parents) > 0:
510
                left_parent_blocks = self._extract_blocks(version_id,
511
                                                          parents[0], target)
512
            else:
513
                left_parent_blocks = None
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
514
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
515
                         left_parent_blocks))
516
        return diffs
517
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
518
    def _extract_blocks(self, version_id, source, target):
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
519
        return None
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
520
2520.4.61 by Aaron Bentley
Do bulk insertion of records
521
    def add_mpdiffs(self, records):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
522
        """Add mpdiffs to this VersionedFile.
2520.4.126 by Aaron Bentley
Add more docs
523
524
        Records should be iterables of version, parents, expected_sha1,
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
525
        mpdiff. mpdiff should be a MultiParent instance.
2520.4.126 by Aaron Bentley
Add more docs
526
        """
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
527
        # Does this need to call self._check_write_ok()? (IanC 20070919)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
528
        vf_parents = {}
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
529
        mpvf = multiparent.MultiMemoryVersionedFile()
530
        versions = []
531
        for version, parent_ids, expected_sha1, mpdiff in records:
532
            versions.append(version)
533
            mpvf.add_diff(mpdiff, version, parent_ids)
534
        needed_parents = set()
2520.4.142 by Aaron Bentley
Clean up installation of inventory records
535
        for version, parent_ids, expected_sha1, mpdiff in records:
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
536
            needed_parents.update(p for p in parent_ids
537
                                  if not mpvf.has_version(p))
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
538
        present_parents = set(self.get_parent_map(needed_parents).keys())
539
        for parent_id, lines in zip(present_parents,
6631.2.1 by Martin
Run 2to3 zip fixer and refactor
540
                self._get_lf_split_line_list(present_parents)):
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
541
            mpvf.add_version(lines, parent_id, [])
6631.2.1 by Martin
Run 2to3 zip fixer and refactor
542
        for (version, parent_ids, expected_sha1, mpdiff), lines in zip(
543
                records, mpvf.get_line_list(versions)):
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
544
            if len(parent_ids) == 1:
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
545
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
546
                    mpvf.get_diff(parent_ids[0]).num_lines()))
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
547
            else:
548
                left_matching_blocks = None
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
549
            try:
550
                _, _, version_text = self.add_lines_with_ghosts(version,
551
                    parent_ids, lines, vf_parents,
552
                    left_matching_blocks=left_matching_blocks)
553
            except NotImplementedError:
554
                # The vf can't handle ghosts, so add lines normally, which will
555
                # (reasonably) fail if there are ghosts in the data.
556
                _, _, version_text = self.add_lines(version,
557
                    parent_ids, lines, vf_parents,
558
                    left_matching_blocks=left_matching_blocks)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
559
            vf_parents[version] = version_text
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
560
        sha1s = self.get_sha1s(versions)
561
        for version, parent_ids, expected_sha1, mpdiff in records:
562
            if expected_sha1 != sha1s[version]:
2520.4.71 by Aaron Bentley
Update test to accept VersionedFileInvalidChecksum instead of TestamentMismatch
563
                raise errors.VersionedFileInvalidChecksum(version)
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
564
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
565
    def get_text(self, version_id):
566
        """Return version contents as a text string.
567
568
        Raises RevisionNotPresent if version is not present in
569
        file history.
570
        """
571
        return ''.join(self.get_lines(version_id))
572
    get_string = get_text
573
1756.2.1 by Aaron Bentley
Implement get_texts
574
    def get_texts(self, version_ids):
575
        """Return the texts of listed versions as a list of strings.
576
577
        Raises RevisionNotPresent if version is not present in
578
        file history.
579
        """
580
        return [''.join(self.get_lines(v)) for v in version_ids]
581
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
582
    def get_lines(self, version_id):
583
        """Return version contents as a sequence of lines.
584
585
        Raises RevisionNotPresent if version is not present in
586
        file history.
587
        """
588
        raise NotImplementedError(self.get_lines)
589
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
590
    def _get_lf_split_line_list(self, version_ids):
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
591
        return [BytesIO(t).readlines() for t in self.get_texts(version_ids)]
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
592
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
593
    def get_ancestry(self, version_ids, topo_sorted=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
594
        """Return a list of all ancestors of given version(s). This
595
        will not include the null revision.
596
2490.2.32 by Aaron Bentley
Merge of not-sorting-ancestry branch
597
        This list will not be topologically sorted if topo_sorted=False is
598
        passed.
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
599
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
600
        Must raise RevisionNotPresent if any of the given versions are
601
        not present in file history."""
602
        if isinstance(version_ids, basestring):
603
            version_ids = [version_ids]
604
        raise NotImplementedError(self.get_ancestry)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
605
1594.2.8 by Robert Collins
add ghost aware apis to knits.
606
    def get_ancestry_with_ghosts(self, version_ids):
607
        """Return a list of all ancestors of given version(s). This
608
        will not include the null revision.
609
610
        Must raise RevisionNotPresent if any of the given versions are
611
        not present in file history.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
612
1594.2.8 by Robert Collins
add ghost aware apis to knits.
613
        Ghosts that are known about will be included in ancestry list,
614
        but are not explicitly marked.
615
        """
616
        raise NotImplementedError(self.get_ancestry_with_ghosts)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
617
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
618
    def get_parent_map(self, version_ids):
619
        """Get a map of the parents of version_ids.
620
621
        :param version_ids: The version ids to look up parents for.
622
        :return: A mapping from version id to parents.
623
        """
624
        raise NotImplementedError(self.get_parent_map)
625
1594.2.8 by Robert Collins
add ghost aware apis to knits.
626
    def get_parents_with_ghosts(self, version_id):
627
        """Return version names for parents of version_id.
628
629
        Will raise RevisionNotPresent if version_id is not present
630
        in the history.
631
632
        Ghosts that are known about will be included in the parent list,
633
        but are not explicitly marked.
634
        """
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
635
        try:
636
            return list(self.get_parent_map([version_id])[version_id])
637
        except KeyError:
638
            raise errors.RevisionNotPresent(version_id, self)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
639
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
640
    def annotate(self, version_id):
3316.2.13 by Robert Collins
* ``VersionedFile.annotate_iter`` is deprecated. While in principal this
641
        """Return a list of (version-id, line) tuples for version_id.
642
643
        :raise RevisionNotPresent: If the given version is
644
        not present in file history.
645
        """
646
        raise NotImplementedError(self.annotate)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
647
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
648
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
649
                                                pb=None):
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
650
        """Iterate over the lines in the versioned file from version_ids.
651
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
652
        This may return lines from other versions. Each item the returned
653
        iterator yields is a tuple of a line and a text version that that line
654
        is present in (not introduced in).
655
656
        Ordering of results is in whatever order is most suitable for the
657
        underlying storage format.
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
658
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
659
        If a progress bar is supplied, it may be used to indicate progress.
660
        The caller is responsible for cleaning up progress bars (because this
661
        is an iterator).
662
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
663
        NOTES: Lines are normalised: they will all have \n terminators.
664
               Lines are returned in arbitrary order.
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
665
666
        :return: An iterator over (line, version_id).
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
667
        """
668
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
669
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
670
    def plan_merge(self, ver_a, ver_b):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
671
        """Return pseudo-annotation indicating how the two versions merge.
672
673
        This is computed between versions a and b and their common
674
        base.
675
676
        Weave lines present in none of them are skipped entirely.
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
677
678
        Legend:
679
        killed-base Dead in base revision
680
        killed-both Killed in each revision
681
        killed-a    Killed in a
682
        killed-b    Killed in b
683
        unchanged   Alive in both a and b (possibly created in both)
684
        new-a       Created in a
685
        new-b       Created in b
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
686
        ghost-a     Killed in a, unborn in b
1664.2.5 by Aaron Bentley
Update plan-merge legend
687
        ghost-b     Killed in b, unborn in a
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
688
        irrelevant  Not in either revision
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
689
        """
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
690
        raise NotImplementedError(VersionedFile.plan_merge)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
691
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
692
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
1551.6.14 by Aaron Bentley
Tweaks from merge review
693
                    b_marker=TextMerge.B_MARKER):
1551.6.12 by Aaron Bentley
Indicate conflicts from merge_lines, insead of guessing
694
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
695
1664.2.7 by Aaron Bentley
Merge bzr.dev
696
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
697
class RecordingVersionedFilesDecorator(object):
698
    """A minimal versioned files that records calls made on it.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
699
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
700
    Only enough methods have been added to support tests using it to date.
701
702
    :ivar calls: A list of the calls made; can be reset at any time by
703
        assigning [] to it.
704
    """
705
706
    def __init__(self, backing_vf):
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
707
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
708
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
709
        :param backing_vf: The versioned file to answer all methods.
710
        """
711
        self._backing_vf = backing_vf
712
        self.calls = []
713
3350.8.2 by Robert Collins
stacked get_parent_map.
714
    def add_lines(self, key, parents, lines, parent_texts=None,
715
        left_matching_blocks=None, nostore_sha=None, random_id=False,
716
        check_content=True):
717
        self.calls.append(("add_lines", key, parents, lines, parent_texts,
718
            left_matching_blocks, nostore_sha, random_id, check_content))
719
        return self._backing_vf.add_lines(key, parents, lines, parent_texts,
720
            left_matching_blocks, nostore_sha, random_id, check_content)
721
3517.4.19 by Martin Pool
Update test for knit.check() to expect it to recurse into fallback vfs
722
    def check(self):
723
        self._backing_vf.check()
724
3350.8.2 by Robert Collins
stacked get_parent_map.
725
    def get_parent_map(self, keys):
726
        self.calls.append(("get_parent_map", copy(keys)))
727
        return self._backing_vf.get_parent_map(keys)
728
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
729
    def get_record_stream(self, keys, sort_order, include_delta_closure):
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
730
        self.calls.append(("get_record_stream", list(keys), sort_order,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
731
            include_delta_closure))
732
        return self._backing_vf.get_record_stream(keys, sort_order,
733
            include_delta_closure)
734
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
735
    def get_sha1s(self, keys):
736
        self.calls.append(("get_sha1s", copy(keys)))
737
        return self._backing_vf.get_sha1s(keys)
738
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
739
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
740
        self.calls.append(("iter_lines_added_or_present_in_keys", copy(keys)))
3350.8.14 by Robert Collins
Review feedback.
741
        return self._backing_vf.iter_lines_added_or_present_in_keys(keys, pb=pb)
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
742
3350.8.4 by Robert Collins
Vf.keys() stacking support.
743
    def keys(self):
744
        self.calls.append(("keys",))
745
        return self._backing_vf.keys()
746
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
747
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
748
class OrderingVersionedFilesDecorator(RecordingVersionedFilesDecorator):
749
    """A VF that records calls, and returns keys in specific order.
750
751
    :ivar calls: A list of the calls made; can be reset at any time by
752
        assigning [] to it.
753
    """
754
755
    def __init__(self, backing_vf, key_priority):
756
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
757
758
        :param backing_vf: The versioned file to answer all methods.
759
        :param key_priority: A dictionary defining what order keys should be
760
            returned from an 'unordered' get_record_stream request.
761
            Keys with lower priority are returned first, keys not present in
762
            the map get an implicit priority of 0, and are returned in
763
            lexicographical order.
764
        """
765
        RecordingVersionedFilesDecorator.__init__(self, backing_vf)
766
        self._key_priority = key_priority
767
768
    def get_record_stream(self, keys, sort_order, include_delta_closure):
769
        self.calls.append(("get_record_stream", list(keys), sort_order,
770
            include_delta_closure))
771
        if sort_order == 'unordered':
772
            def sort_key(key):
773
                return (self._key_priority.get(key, 0), key)
774
            # Use a defined order by asking for the keys one-by-one from the
775
            # backing_vf
776
            for key in sorted(keys, key=sort_key):
777
                for record in self._backing_vf.get_record_stream([key],
778
                                'unordered', include_delta_closure):
779
                    yield record
780
        else:
781
            for record in self._backing_vf.get_record_stream(keys, sort_order,
782
                            include_delta_closure):
783
                yield record
784
785
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
786
class KeyMapper(object):
3350.6.10 by Martin Pool
VersionedFiles review cleanups
787
    """KeyMappers map between keys and underlying partitioned storage."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
788
789
    def map(self, key):
790
        """Map key to an underlying storage identifier.
791
792
        :param key: A key tuple e.g. ('file-id', 'revision-id').
793
        :return: An underlying storage identifier, specific to the partitioning
794
            mechanism.
795
        """
796
        raise NotImplementedError(self.map)
797
798
    def unmap(self, partition_id):
799
        """Map a partitioned storage id back to a key prefix.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
800
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
801
        :param partition_id: The underlying partition id.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
802
        :return: As much of a key (or prefix) as is derivable from the partition
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
803
            id.
804
        """
805
        raise NotImplementedError(self.unmap)
806
807
808
class ConstantMapper(KeyMapper):
809
    """A key mapper that maps to a constant result."""
810
811
    def __init__(self, result):
812
        """Create a ConstantMapper which will return result for all maps."""
813
        self._result = result
814
815
    def map(self, key):
816
        """See KeyMapper.map()."""
817
        return self._result
818
819
820
class URLEscapeMapper(KeyMapper):
821
    """Base class for use with transport backed storage.
822
823
    This provides a map and unmap wrapper that respectively url escape and
824
    unescape their outputs and inputs.
825
    """
826
827
    def map(self, key):
828
        """See KeyMapper.map()."""
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
829
        return urlutils.quote(self._map(key))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
830
831
    def unmap(self, partition_id):
832
        """See KeyMapper.unmap()."""
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
833
        return self._unmap(urlutils.unquote(partition_id))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
834
835
836
class PrefixMapper(URLEscapeMapper):
837
    """A key mapper that extracts the first component of a key.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
838
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
839
    This mapper is for use with a transport based backend.
840
    """
841
842
    def _map(self, key):
843
        """See KeyMapper.map()."""
844
        return key[0]
845
846
    def _unmap(self, partition_id):
847
        """See KeyMapper.unmap()."""
848
        return (partition_id,)
849
850
851
class HashPrefixMapper(URLEscapeMapper):
852
    """A key mapper that combines the first component of a key with a hash.
853
854
    This mapper is for use with a transport based backend.
855
    """
856
857
    def _map(self, key):
858
        """See KeyMapper.map()."""
859
        prefix = self._escape(key[0])
860
        return "%02x/%s" % (adler32(prefix) & 0xff, prefix)
861
862
    def _escape(self, prefix):
863
        """No escaping needed here."""
864
        return prefix
865
866
    def _unmap(self, partition_id):
867
        """See KeyMapper.unmap()."""
868
        return (self._unescape(osutils.basename(partition_id)),)
869
870
    def _unescape(self, basename):
871
        """No unescaping needed for HashPrefixMapper."""
872
        return basename
873
874
875
class HashEscapedPrefixMapper(HashPrefixMapper):
876
    """Combines the escaped first component of a key with a hash.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
877
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
878
    This mapper is for use with a transport based backend.
879
    """
880
881
    _safe = "abcdefghijklmnopqrstuvwxyz0123456789-_@,."
882
883
    def _escape(self, prefix):
884
        """Turn a key element into a filesystem safe string.
885
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
886
        This is similar to a plain urlutils.quote, except
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
887
        it uses specific safe characters, so that it doesn't
888
        have to translate a lot of valid file ids.
889
        """
890
        # @ does not get escaped. This is because it is a valid
891
        # filesystem character we use all the time, and it looks
892
        # a lot better than seeing %40 all the time.
893
        r = [((c in self._safe) and c or ('%%%02x' % ord(c)))
894
             for c in prefix]
895
        return ''.join(r)
896
897
    def _unescape(self, basename):
898
        """Escaped names are easily unescaped by urlutils."""
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
899
        return urlutils.unquote(basename)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
900
901
902
def make_versioned_files_factory(versioned_file_factory, mapper):
903
    """Create a ThunkedVersionedFiles factory.
904
905
    This will create a callable which when called creates a
906
    ThunkedVersionedFiles on a transport, using mapper to access individual
907
    versioned files, and versioned_file_factory to create each individual file.
908
    """
909
    def factory(transport):
910
        return ThunkedVersionedFiles(transport, versioned_file_factory, mapper,
911
            lambda:True)
912
    return factory
913
914
915
class VersionedFiles(object):
916
    """Storage for many versioned files.
917
918
    This object allows a single keyspace for accessing the history graph and
919
    contents of named bytestrings.
920
921
    Currently no implementation allows the graph of different key prefixes to
922
    intersect, but the API does allow such implementations in the future.
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
923
924
    The keyspace is expressed via simple tuples. Any instance of VersionedFiles
925
    may have a different length key-size, but that size will be constant for
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
926
    all texts added to or retrieved from it. For instance, breezy uses
3350.6.7 by Robert Collins
Review feedback, making things more clear, adding documentation on what is used where.
927
    instances with a key-size of 2 for storing user files in a repository, with
928
    the first element the fileid, and the second the version of that file.
929
930
    The use of tuples allows a single code base to support several different
931
    uses with only the mapping logic changing from instance to instance.
5652.2.2 by Martin Pool
Rename _fallback_vfs to _immediate_fallbacks
932
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
933
    :ivar _immediate_fallback_vfs: For subclasses that support stacking,
5652.2.2 by Martin Pool
Rename _fallback_vfs to _immediate_fallbacks
934
        this is a list of other VersionedFiles immediately underneath this
935
        one.  They may in turn each have further fallbacks.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
936
    """
937
938
    def add_lines(self, key, parents, lines, parent_texts=None,
939
        left_matching_blocks=None, nostore_sha=None, random_id=False,
940
        check_content=True):
941
        """Add a text to the store.
942
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
943
        :param key: The key tuple of the text to add. If the last element is
944
            None, a CHK string will be generated during the addition.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
945
        :param parents: The parents key tuples of the text to add.
946
        :param lines: A list of lines. Each line must be a bytestring. And all
947
            of them except the last must be terminated with \n and contain no
948
            other \n's. The last line may either contain no \n's or a single
949
            terminating \n. If the lines list does meet this constraint the add
950
            routine may error or may succeed - but you will be unable to read
951
            the data back accurately. (Checking the lines have been split
952
            correctly is expensive and extremely unlikely to catch bugs so it
953
            is not done at runtime unless check_content is True.)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
954
        :param parent_texts: An optional dictionary containing the opaque
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
955
            representations of some or all of the parents of version_id to
956
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
957
            returned by add_lines or data corruption can be caused.
958
        :param left_matching_blocks: a hint about which areas are common
959
            between the text and its left-hand-parent.  The format is
960
            the SequenceMatcher.get_matching_blocks format.
961
        :param nostore_sha: Raise ExistingContent and do not add the lines to
962
            the versioned file if the digest of the lines matches this.
963
        :param random_id: If True a random id has been selected rather than
964
            an id determined by some deterministic process such as a converter
965
            from a foreign VCS. When True the backend may choose not to check
966
            for uniqueness of the resulting key within the versioned file, so
967
            this should only be done when the result is expected to be unique
968
            anyway.
969
        :param check_content: If True, the lines supplied are verified to be
970
            bytestrings that are correctly formed lines.
971
        :return: The text sha1, the number of bytes in the text, and an opaque
972
                 representation of the inserted version which can be provided
973
                 back to future add_lines calls in the parent_texts dictionary.
974
        """
975
        raise NotImplementedError(self.add_lines)
976
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
977
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
978
        """Add a text to the store.
979
5815.4.2 by Jelmer Vernooij
split out versionedfile-specific stuff from commitbuilder.
980
        This is a private function for use by VersionedFileCommitBuilder.
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
981
982
        :param key: The key tuple of the text to add. If the last element is
983
            None, a CHK string will be generated during the addition.
984
        :param parents: The parents key tuples of the text to add.
985
        :param text: A string containing the text to be committed.
986
        :param nostore_sha: Raise ExistingContent and do not add the lines to
987
            the versioned file if the digest of the lines matches this.
988
        :param random_id: If True a random id has been selected rather than
989
            an id determined by some deterministic process such as a converter
990
            from a foreign VCS. When True the backend may choose not to check
991
            for uniqueness of the resulting key within the versioned file, so
992
            this should only be done when the result is expected to be unique
993
            anyway.
994
        :param check_content: If True, the lines supplied are verified to be
995
            bytestrings that are correctly formed lines.
996
        :return: The text sha1, the number of bytes in the text, and an opaque
997
                 representation of the inserted version which can be provided
998
                 back to future _add_text calls in the parent_texts dictionary.
999
        """
1000
        # The default implementation just thunks over to .add_lines(),
1001
        # inefficient, but it works.
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
1002
        return self.add_lines(key, parents, osutils.split_lines(text),
1003
                              nostore_sha=nostore_sha,
1004
                              random_id=random_id,
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
1005
                              check_content=True)
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
1006
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1007
    def add_mpdiffs(self, records):
1008
        """Add mpdiffs to this VersionedFile.
1009
1010
        Records should be iterables of version, parents, expected_sha1,
1011
        mpdiff. mpdiff should be a MultiParent instance.
1012
        """
1013
        vf_parents = {}
1014
        mpvf = multiparent.MultiMemoryVersionedFile()
1015
        versions = []
1016
        for version, parent_ids, expected_sha1, mpdiff in records:
1017
            versions.append(version)
1018
            mpvf.add_diff(mpdiff, version, parent_ids)
1019
        needed_parents = set()
1020
        for version, parent_ids, expected_sha1, mpdiff in records:
1021
            needed_parents.update(p for p in parent_ids
1022
                                  if not mpvf.has_version(p))
1023
        # It seems likely that adding all the present parents as fulltexts can
1024
        # easily exhaust memory.
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
1025
        chunks_to_lines = osutils.chunks_to_lines
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
1026
        for record in self.get_record_stream(needed_parents, 'unordered',
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1027
            True):
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
1028
            if record.storage_kind == 'absent':
1029
                continue
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
1030
            mpvf.add_version(chunks_to_lines(record.get_bytes_as('chunked')),
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1031
                record.key, [])
6631.2.1 by Martin
Run 2to3 zip fixer and refactor
1032
        for (key, parent_keys, expected_sha1, mpdiff), lines in zip(
1033
                records, mpvf.get_line_list(versions)):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1034
            if len(parent_keys) == 1:
1035
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
1036
                    mpvf.get_diff(parent_keys[0]).num_lines()))
1037
            else:
1038
                left_matching_blocks = None
1039
            version_sha1, _, version_text = self.add_lines(key,
1040
                parent_keys, lines, vf_parents,
1041
                left_matching_blocks=left_matching_blocks)
1042
            if version_sha1 != expected_sha1:
1043
                raise errors.VersionedFileInvalidChecksum(version)
1044
            vf_parents[key] = version_text
1045
1046
    def annotate(self, key):
1047
        """Return a list of (version-key, line) tuples for the text of key.
1048
1049
        :raise RevisionNotPresent: If the key is not present.
1050
        """
1051
        raise NotImplementedError(self.annotate)
1052
1053
    def check(self, progress_bar=None):
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1054
        """Check this object for integrity.
1055
        
1056
        :param progress_bar: A progress bar to output as the check progresses.
1057
        :param keys: Specific keys within the VersionedFiles to check. When
1058
            this parameter is not None, check() becomes a generator as per
1059
            get_record_stream. The difference to get_record_stream is that
1060
            more or deeper checks will be performed.
1061
        :return: None, or if keys was supplied a generator as per
1062
            get_record_stream.
1063
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1064
        raise NotImplementedError(self.check)
1065
1066
    @staticmethod
1067
    def check_not_reserved_id(version_id):
1068
        revision.check_not_reserved_id(version_id)
1069
4744.2.5 by John Arbash Meinel
Change to a generic 'VersionedFiles.clear_cache()' api.
1070
    def clear_cache(self):
1071
        """Clear whatever caches this VersionedFile holds.
1072
1073
        This is generally called after an operation has been performed, when we
1074
        don't expect to be using this versioned file again soon.
1075
        """
1076
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1077
    def _check_lines_not_unicode(self, lines):
1078
        """Check that lines being added to a versioned file are not unicode."""
1079
        for line in lines:
1080
            if line.__class__ is not str:
1081
                raise errors.BzrBadParameterUnicode("lines")
1082
1083
    def _check_lines_are_lines(self, lines):
1084
        """Check that the lines really are full lines without inline EOL."""
1085
        for line in lines:
1086
            if '\n' in line[:-1]:
1087
                raise errors.BzrBadParameterContainsNewline("lines")
1088
4593.5.36 by John Arbash Meinel
a few more implementations of the interface.
1089
    def get_known_graph_ancestry(self, keys):
1090
        """Get a KnownGraph instance with the ancestry of keys."""
1091
        # most basic implementation is a loop around get_parent_map
1092
        pending = set(keys)
1093
        parent_map = {}
1094
        while pending:
1095
            this_parent_map = self.get_parent_map(pending)
1096
            parent_map.update(this_parent_map)
6631.3.1 by Martin
Run 2to3 map fixer and refactor after
1097
            pending = set(itertools.chain.from_iterable(
1098
                this_parent_map.itervalues()))
1099
            pending.difference_update(parent_map)
4593.5.36 by John Arbash Meinel
a few more implementations of the interface.
1100
        kg = _mod_graph.KnownGraph(parent_map)
1101
        return kg
1102
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1103
    def get_parent_map(self, keys):
1104
        """Get a map of the parents of keys.
1105
1106
        :param keys: The keys to look up parents for.
1107
        :return: A mapping from keys to parents. Absent keys are absent from
1108
            the mapping.
1109
        """
1110
        raise NotImplementedError(self.get_parent_map)
1111
1112
    def get_record_stream(self, keys, ordering, include_delta_closure):
1113
        """Get a stream of records for keys.
1114
1115
        :param keys: The keys to include.
1116
        :param ordering: Either 'unordered' or 'topological'. A topologically
1117
            sorted stream has compression parents strictly before their
1118
            children.
1119
        :param include_delta_closure: If True then the closure across any
1120
            compression parents will be included (in the opaque data).
1121
        :return: An iterator of ContentFactory objects, each of which is only
1122
            valid until the iterator is advanced.
1123
        """
1124
        raise NotImplementedError(self.get_record_stream)
1125
1126
    def get_sha1s(self, keys):
1127
        """Get the sha1's of the texts for the given keys.
1128
1129
        :param keys: The names of the keys to lookup
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1130
        :return: a dict from key to sha1 digest. Keys of texts which are not
3350.8.14 by Robert Collins
Review feedback.
1131
            present in the store are not present in the returned
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1132
            dictionary.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1133
        """
1134
        raise NotImplementedError(self.get_sha1s)
1135
6619.3.8 by Jelmer Vernooij
Cope with has_key -> contains rename.
1136
    __contains__ = index._has_key_from_parent_map
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
1137
4009.3.3 by Andrew Bennetts
Add docstrings.
1138
    def get_missing_compression_parent_keys(self):
1139
        """Return an iterable of keys of missing compression parents.
1140
1141
        Check this after calling insert_record_stream to find out if there are
1142
        any missing compression parents.  If there are, the records that
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
1143
        depend on them are not able to be inserted safely. The precise
1144
        behaviour depends on the concrete VersionedFiles class in use.
1145
1146
        Classes that do not support this will raise NotImplementedError.
4009.3.3 by Andrew Bennetts
Add docstrings.
1147
        """
1148
        raise NotImplementedError(self.get_missing_compression_parent_keys)
1149
5195.3.26 by Parth Malwankar
reverted changes done to insert_record_stream API
1150
    def insert_record_stream(self, stream):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1151
        """Insert a record stream into this container.
1152
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1153
        :param stream: A stream of records to insert.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1154
        :return: None
1155
        :seealso VersionedFile.get_record_stream:
1156
        """
1157
        raise NotImplementedError
1158
1159
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1160
        """Iterate over the lines in the versioned files from keys.
1161
1162
        This may return lines from other keys. Each item the returned
1163
        iterator yields is a tuple of a line and a text version that that line
1164
        is present in (not introduced in).
1165
1166
        Ordering of results is in whatever order is most suitable for the
1167
        underlying storage format.
1168
1169
        If a progress bar is supplied, it may be used to indicate progress.
1170
        The caller is responsible for cleaning up progress bars (because this
1171
        is an iterator).
1172
1173
        NOTES:
1174
         * Lines are normalised by the underlying store: they will all have \n
1175
           terminators.
1176
         * Lines are returned in arbitrary order.
1177
1178
        :return: An iterator over (line, key).
1179
        """
1180
        raise NotImplementedError(self.iter_lines_added_or_present_in_keys)
1181
1182
    def keys(self):
1183
        """Return a iterable of the keys for all the contained texts."""
1184
        raise NotImplementedError(self.keys)
1185
1186
    def make_mpdiffs(self, keys):
1187
        """Create multiparent diffs for specified keys."""
5374.2.3 by John Arbash Meinel
Replace the generic VersionedFiles.make_mpdiffs interface.
1188
        generator = _MPDiffGenerator(self, keys)
1189
        return generator.compute_diffs()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1190
5363.1.1 by Jelmer Vernooij
Provide VersionedFiles.get_annotator.
1191
    def get_annotator(self):
1192
        return annotate.Annotator(self)
1193
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
1194
    missing_keys = index._missing_keys_from_parent_map
1195
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1196
    def _extract_blocks(self, version_id, source, target):
1197
        return None
1198
5050.70.2 by Martin Pool
Search all fallbacks for get_known_graph_ancestry
1199
    def _transitive_fallbacks(self):
1200
        """Return the whole stack of fallback versionedfiles.
1201
1202
        This VersionedFiles may have a list of fallbacks, but it doesn't
1203
        necessarily know about the whole stack going down, and it can't know
1204
        at open time because they may change after the objects are opened.
1205
        """
1206
        all_fallbacks = []
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1207
        for a_vfs in self._immediate_fallback_vfs:
5050.70.2 by Martin Pool
Search all fallbacks for get_known_graph_ancestry
1208
            all_fallbacks.append(a_vfs)
1209
            all_fallbacks.extend(a_vfs._transitive_fallbacks())
1210
        return all_fallbacks
1211
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1212
1213
class ThunkedVersionedFiles(VersionedFiles):
1214
    """Storage for many versioned files thunked onto a 'VersionedFile' class.
1215
1216
    This object allows a single keyspace for accessing the history graph and
1217
    contents of named bytestrings.
1218
1219
    Currently no implementation allows the graph of different key prefixes to
1220
    intersect, but the API does allow such implementations in the future.
1221
    """
1222
1223
    def __init__(self, transport, file_factory, mapper, is_locked):
1224
        """Create a ThunkedVersionedFiles."""
1225
        self._transport = transport
1226
        self._file_factory = file_factory
1227
        self._mapper = mapper
1228
        self._is_locked = is_locked
1229
1230
    def add_lines(self, key, parents, lines, parent_texts=None,
1231
        left_matching_blocks=None, nostore_sha=None, random_id=False,
1232
        check_content=True):
1233
        """See VersionedFiles.add_lines()."""
1234
        path = self._mapper.map(key)
1235
        version_id = key[-1]
1236
        parents = [parent[-1] for parent in parents]
1237
        vf = self._get_vf(path)
1238
        try:
1239
            try:
1240
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1241
                    parent_texts=parent_texts,
1242
                    left_matching_blocks=left_matching_blocks,
1243
                    nostore_sha=nostore_sha, random_id=random_id,
1244
                    check_content=check_content)
1245
            except NotImplementedError:
1246
                return vf.add_lines(version_id, parents, lines,
1247
                    parent_texts=parent_texts,
1248
                    left_matching_blocks=left_matching_blocks,
1249
                    nostore_sha=nostore_sha, random_id=random_id,
1250
                    check_content=check_content)
1251
        except errors.NoSuchFile:
1252
            # parent directory may be missing, try again.
1253
            self._transport.mkdir(osutils.dirname(path))
1254
            try:
1255
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1256
                    parent_texts=parent_texts,
1257
                    left_matching_blocks=left_matching_blocks,
1258
                    nostore_sha=nostore_sha, random_id=random_id,
1259
                    check_content=check_content)
1260
            except NotImplementedError:
1261
                return vf.add_lines(version_id, parents, lines,
1262
                    parent_texts=parent_texts,
1263
                    left_matching_blocks=left_matching_blocks,
1264
                    nostore_sha=nostore_sha, random_id=random_id,
1265
                    check_content=check_content)
1266
1267
    def annotate(self, key):
1268
        """Return a list of (version-key, line) tuples for the text of key.
1269
1270
        :raise RevisionNotPresent: If the key is not present.
1271
        """
1272
        prefix = key[:-1]
1273
        path = self._mapper.map(prefix)
1274
        vf = self._get_vf(path)
1275
        origins = vf.annotate(key[-1])
1276
        result = []
1277
        for origin, line in origins:
1278
            result.append((prefix + (origin,), line))
1279
        return result
1280
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1281
    def check(self, progress_bar=None, keys=None):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1282
        """See VersionedFiles.check()."""
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1283
        # XXX: This is over-enthusiastic but as we only thunk for Weaves today
1284
        # this is tolerable. Ideally we'd pass keys down to check() and 
1285
        # have the older VersiondFile interface updated too.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1286
        for prefix, vf in self._iter_all_components():
1287
            vf.check()
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1288
        if keys is not None:
1289
            return self.get_record_stream(keys, 'unordered', True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1290
1291
    def get_parent_map(self, keys):
1292
        """Get a map of the parents of keys.
1293
1294
        :param keys: The keys to look up parents for.
1295
        :return: A mapping from keys to parents. Absent keys are absent from
1296
            the mapping.
1297
        """
1298
        prefixes = self._partition_keys(keys)
1299
        result = {}
1300
        for prefix, suffixes in prefixes.items():
1301
            path = self._mapper.map(prefix)
1302
            vf = self._get_vf(path)
1303
            parent_map = vf.get_parent_map(suffixes)
1304
            for key, parents in parent_map.items():
1305
                result[prefix + (key,)] = tuple(
1306
                    prefix + (parent,) for parent in parents)
1307
        return result
1308
1309
    def _get_vf(self, path):
1310
        if not self._is_locked():
1311
            raise errors.ObjectNotLocked(self)
1312
        return self._file_factory(path, self._transport, create=True,
1313
            get_scope=lambda:None)
1314
1315
    def _partition_keys(self, keys):
1316
        """Turn keys into a dict of prefix:suffix_list."""
1317
        result = {}
1318
        for key in keys:
1319
            prefix_keys = result.setdefault(key[:-1], [])
1320
            prefix_keys.append(key[-1])
1321
        return result
1322
6631.2.1 by Martin
Run 2to3 zip fixer and refactor
1323
    def _iter_all_prefixes(self):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1324
        # Identify all key prefixes.
1325
        # XXX: A bit hacky, needs polish.
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
1326
        if isinstance(self._mapper, ConstantMapper):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1327
            paths = [self._mapper.map(())]
1328
            prefixes = [()]
1329
        else:
1330
            relpaths = set()
1331
            for quoted_relpath in self._transport.iter_files_recursive():
1332
                path, ext = os.path.splitext(quoted_relpath)
1333
                relpaths.add(path)
1334
            paths = list(relpaths)
1335
            prefixes = [self._mapper.unmap(path) for path in paths]
1336
        return zip(paths, prefixes)
1337
1338
    def get_record_stream(self, keys, ordering, include_delta_closure):
1339
        """See VersionedFiles.get_record_stream()."""
1340
        # Ordering will be taken care of by each partitioned store; group keys
1341
        # by partition.
1342
        keys = sorted(keys)
1343
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1344
            suffixes = [(suffix,) for suffix in suffixes]
1345
            for record in vf.get_record_stream(suffixes, ordering,
1346
                include_delta_closure):
1347
                if record.parents is not None:
1348
                    record.parents = tuple(
1349
                        prefix + parent for parent in record.parents)
1350
                record.key = prefix + record.key
1351
                yield record
1352
1353
    def _iter_keys_vf(self, keys):
1354
        prefixes = self._partition_keys(keys)
1355
        sha1s = {}
1356
        for prefix, suffixes in prefixes.items():
1357
            path = self._mapper.map(prefix)
1358
            vf = self._get_vf(path)
1359
            yield prefix, suffixes, vf
1360
1361
    def get_sha1s(self, keys):
1362
        """See VersionedFiles.get_sha1s()."""
1363
        sha1s = {}
1364
        for prefix,suffixes, vf in self._iter_keys_vf(keys):
1365
            vf_sha1s = vf.get_sha1s(suffixes)
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1366
            for suffix, sha1 in vf_sha1s.iteritems():
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1367
                sha1s[prefix + (suffix,)] = sha1
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1368
        return sha1s
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1369
5195.3.26 by Parth Malwankar
reverted changes done to insert_record_stream API
1370
    def insert_record_stream(self, stream):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1371
        """Insert a record stream into this container.
1372
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1373
        :param stream: A stream of records to insert.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1374
        :return: None
1375
        :seealso VersionedFile.get_record_stream:
1376
        """
1377
        for record in stream:
1378
            prefix = record.key[:-1]
1379
            key = record.key[-1:]
1380
            if record.parents is not None:
1381
                parents = [parent[-1:] for parent in record.parents]
1382
            else:
1383
                parents = None
1384
            thunk_record = AdapterFactory(key, parents, record)
1385
            path = self._mapper.map(prefix)
1386
            # Note that this parses the file many times; we can do better but
1387
            # as this only impacts weaves in terms of performance, it is
1388
            # tolerable.
1389
            vf = self._get_vf(path)
1390
            vf.insert_record_stream([thunk_record])
1391
1392
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1393
        """Iterate over the lines in the versioned files from keys.
1394
1395
        This may return lines from other keys. Each item the returned
1396
        iterator yields is a tuple of a line and a text version that that line
1397
        is present in (not introduced in).
1398
1399
        Ordering of results is in whatever order is most suitable for the
1400
        underlying storage format.
1401
1402
        If a progress bar is supplied, it may be used to indicate progress.
1403
        The caller is responsible for cleaning up progress bars (because this
1404
        is an iterator).
1405
1406
        NOTES:
1407
         * Lines are normalised by the underlying store: they will all have \n
1408
           terminators.
1409
         * Lines are returned in arbitrary order.
1410
1411
        :return: An iterator over (line, key).
1412
        """
1413
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1414
            for line, version in vf.iter_lines_added_or_present_in_versions(suffixes):
1415
                yield line, prefix + (version,)
1416
1417
    def _iter_all_components(self):
6631.2.1 by Martin
Run 2to3 zip fixer and refactor
1418
        for path, prefix in self._iter_all_prefixes():
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1419
            yield prefix, self._get_vf(path)
1420
1421
    def keys(self):
1422
        """See VersionedFiles.keys()."""
1423
        result = set()
1424
        for prefix, vf in self._iter_all_components():
1425
            for suffix in vf.versions():
1426
                result.add(prefix + (suffix,))
1427
        return result
1428
1429
5816.8.1 by Andrew Bennetts
Be a little more clever about constructing a parents provider for stacked repositories, so that get_parent_map with local-stacked-on-remote doesn't use HPSS VFS calls.
1430
class VersionedFilesWithFallbacks(VersionedFiles):
1431
1432
    def without_fallbacks(self):
1433
        """Return a clone of this object without any fallbacks configured."""
1434
        raise NotImplementedError(self.without_fallbacks)
1435
1436
    def add_fallback_versioned_files(self, a_versioned_files):
1437
        """Add a source of texts for texts not present in this knit.
1438
1439
        :param a_versioned_files: A VersionedFiles object.
1440
        """
1441
        raise NotImplementedError(self.add_fallback_versioned_files)
1442
5863.1.1 by Andrew Bennetts
Move duplicate definitions of {Knit,GroupCompress}VersionedFiles.get_known_graph_ancestry into VersionedFilesWithFallbacks.
1443
    def get_known_graph_ancestry(self, keys):
1444
        """Get a KnownGraph instance with the ancestry of keys."""
1445
        parent_map, missing_keys = self._index.find_ancestry(keys)
1446
        for fallback in self._transitive_fallbacks():
1447
            if not missing_keys:
1448
                break
1449
            (f_parent_map, f_missing_keys) = fallback._index.find_ancestry(
1450
                                                missing_keys)
1451
            parent_map.update(f_parent_map)
1452
            missing_keys = f_missing_keys
1453
        kg = _mod_graph.KnownGraph(parent_map)
1454
        return kg
1455
5816.8.1 by Andrew Bennetts
Be a little more clever about constructing a parents provider for stacked repositories, so that get_parent_map with local-stacked-on-remote doesn't use HPSS VFS calls.
1456
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1457
class _PlanMergeVersionedFile(VersionedFiles):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1458
    """A VersionedFile for uncommitted and committed texts.
1459
1460
    It is intended to allow merges to be planned with working tree texts.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1461
    It implements only the small part of the VersionedFiles interface used by
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1462
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
1463
    _PlanMergeVersionedFile itself.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1464
1465
    :ivar: fallback_versionedfiles a list of VersionedFiles objects that can be
1466
        queried for missing texts.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1467
    """
1468
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1469
    def __init__(self, file_id):
1470
        """Create a _PlanMergeVersionedFile.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1471
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1472
        :param file_id: Used with _PlanMerge code which is not yet fully
1473
            tuple-keyspace aware.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1474
        """
1475
        self._file_id = file_id
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1476
        # fallback locations
1477
        self.fallback_versionedfiles = []
1478
        # Parents for locally held keys.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1479
        self._parents = {}
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1480
        # line data for locally held keys.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1481
        self._lines = {}
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1482
        # key lookup providers
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
1483
        self._providers = [_mod_graph.DictParentsProvider(self._parents)]
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1484
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1485
    def plan_merge(self, ver_a, ver_b, base=None):
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
1486
        """See VersionedFile.plan_merge"""
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1487
        from .merge import _PlanMerge
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1488
        if base is None:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1489
            return _PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge()
1490
        old_plan = list(_PlanMerge(ver_a, base, self, (self._file_id,)).plan_merge())
1491
        new_plan = list(_PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge())
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1492
        return _PlanMerge._subtract_plans(old_plan, new_plan)
1493
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1494
    def plan_lca_merge(self, ver_a, ver_b, base=None):
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
1495
        from .merge import _PlanLCAMerge
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
1496
        graph = _mod_graph.Graph(self)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1497
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, (self._file_id,), graph).plan_merge()
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1498
        if base is None:
1499
            return new_plan
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1500
        old_plan = _PlanLCAMerge(ver_a, base, self, (self._file_id,), graph).plan_merge()
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1501
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
1502
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1503
    def add_lines(self, key, parents, lines):
1504
        """See VersionedFiles.add_lines
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1505
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1506
        Lines are added locally, not to fallback versionedfiles.  Also, ghosts
1507
        are permitted.  Only reserved ids are permitted.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1508
        """
6619.3.18 by Jelmer Vernooij
Run 2to3 idioms fixer.
1509
        if not isinstance(key, tuple):
3350.6.8 by Martin Pool
Change stray pdb calls to exceptions
1510
            raise TypeError(key)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1511
        if not revision.is_reserved_id(key[-1]):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1512
            raise ValueError('Only reserved ids may be used')
1513
        if parents is None:
1514
            raise ValueError('Parents may not be None')
1515
        if lines is None:
1516
            raise ValueError('Lines may not be None')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1517
        self._parents[key] = tuple(parents)
1518
        self._lines[key] = lines
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1519
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1520
    def get_record_stream(self, keys, ordering, include_delta_closure):
1521
        pending = set(keys)
1522
        for key in keys:
1523
            if key in self._lines:
1524
                lines = self._lines[key]
1525
                parents = self._parents[key]
1526
                pending.remove(key)
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1527
                yield ChunkedContentFactory(key, parents, None, lines)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1528
        for versionedfile in self.fallback_versionedfiles:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1529
            for record in versionedfile.get_record_stream(
1530
                pending, 'unordered', True):
1531
                if record.storage_kind == 'absent':
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1532
                    continue
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1533
                else:
1534
                    pending.remove(record.key)
1535
                    yield record
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
1536
            if not pending:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1537
                return
1538
        # report absent entries
1539
        for key in pending:
1540
            yield AbsentContentFactory(key)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1541
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1542
    def get_parent_map(self, keys):
1543
        """See VersionedFiles.get_parent_map"""
1544
        # We create a new provider because a fallback may have been added.
1545
        # If we make fallbacks private we can update a stack list and avoid
1546
        # object creation thrashing.
3350.6.6 by Robert Collins
Fix test_plan_file_merge
1547
        keys = set(keys)
1548
        result = {}
1549
        if revision.NULL_REVISION in keys:
1550
            keys.remove(revision.NULL_REVISION)
1551
            result[revision.NULL_REVISION] = ()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1552
        self._providers = self._providers[:1] + self.fallback_versionedfiles
3350.6.6 by Robert Collins
Fix test_plan_file_merge
1553
        result.update(
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
1554
            _mod_graph.StackedParentsProvider(
1555
                self._providers).get_parent_map(keys))
3350.6.5 by Robert Collins
Update to bzr.dev.
1556
        for key, parents in result.iteritems():
1557
            if parents == ():
1558
                result[key] = (revision.NULL_REVISION,)
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
1559
        return result
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1560
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1561
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1562
class PlanWeaveMerge(TextMerge):
1551.6.13 by Aaron Bentley
Cleanup
1563
    """Weave merge that takes a plan as its input.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1564
1551.6.14 by Aaron Bentley
Tweaks from merge review
1565
    This exists so that VersionedFile.plan_merge is implementable.
1566
    Most callers will want to use WeaveMerge instead.
1551.6.13 by Aaron Bentley
Cleanup
1567
    """
1568
1551.6.14 by Aaron Bentley
Tweaks from merge review
1569
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
1570
                 b_marker=TextMerge.B_MARKER):
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1571
        TextMerge.__init__(self, a_marker, b_marker)
4634.101.7 by John Arbash Meinel
Start working on the ability to drop a .BASE file for --weave and --lca merge.
1572
        self.plan = list(plan)
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1573
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
1574
    def _merge_struct(self):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1575
        lines_a = []
1576
        lines_b = []
1577
        ch_a = ch_b = False
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1578
1579
        def outstanding_struct():
1580
            if not lines_a and not lines_b:
1581
                return
1582
            elif ch_a and not ch_b:
1583
                # one-sided change:
1584
                yield(lines_a,)
1585
            elif ch_b and not ch_a:
1586
                yield (lines_b,)
1587
            elif lines_a == lines_b:
1588
                yield(lines_a,)
1589
            else:
1590
                yield (lines_a, lines_b)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1591
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
1592
        # We previously considered either 'unchanged' or 'killed-both' lines
1593
        # to be possible places to resynchronize.  However, assuming agreement
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1594
        # on killed-both lines may be too aggressive. -- mbp 20060324
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
1595
        for state, line in self.plan:
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
1596
            if state == 'unchanged':
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1597
                # resync and flush queued conflicts changes if any
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1598
                for struct in outstanding_struct():
1599
                    yield struct
1551.6.11 by Aaron Bentley
Switched TextMerge_lines to work on a list
1600
                lines_a = []
1601
                lines_b = []
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1602
                ch_a = ch_b = False
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1603
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1604
            if state == 'unchanged':
1605
                if line:
1551.6.5 by Aaron Bentley
Got weave merge producing structural output
1606
                    yield ([line],)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1607
            elif state == 'killed-a':
1608
                ch_a = True
1609
                lines_b.append(line)
1610
            elif state == 'killed-b':
1611
                ch_b = True
1612
                lines_a.append(line)
1613
            elif state == 'new-a':
1614
                ch_a = True
1615
                lines_a.append(line)
1616
            elif state == 'new-b':
1617
                ch_b = True
1618
                lines_b.append(line)
3144.3.2 by Aaron Bentley
Get conflict handling working
1619
            elif state == 'conflicted-a':
1620
                ch_b = ch_a = True
1621
                lines_a.append(line)
1622
            elif state == 'conflicted-b':
1623
                ch_b = ch_a = True
1624
                lines_b.append(line)
4312.1.1 by John Arbash Meinel
Add a per-implementation test that deleting lines conflicts with modifying lines.
1625
            elif state == 'killed-both':
1626
                # This counts as a change, even though there is no associated
1627
                # line
1628
                ch_b = ch_a = True
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1629
            else:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1630
                if state not in ('irrelevant', 'ghost-a', 'ghost-b',
4312.1.1 by John Arbash Meinel
Add a per-implementation test that deleting lines conflicts with modifying lines.
1631
                        'killed-base'):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1632
                    raise AssertionError(state)
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1633
        for struct in outstanding_struct():
1634
            yield struct
1563.2.12 by Robert Collins
Checkpointing: created InterObject to factor out common inter object worker code, added InterVersionedFile and tests to allow making join work between any versionedfile.
1635
4634.101.7 by John Arbash Meinel
Start working on the ability to drop a .BASE file for --weave and --lca merge.
1636
    def base_from_plan(self):
1637
        """Construct a BASE file from the plan text."""
1638
        base_lines = []
1639
        for state, line in self.plan:
4634.101.9 by John Arbash Meinel
Reverse the .BASE values for --lca and conflicted lines.
1640
            if state in ('killed-a', 'killed-b', 'killed-both', 'unchanged'):
4634.101.7 by John Arbash Meinel
Start working on the ability to drop a .BASE file for --weave and --lca merge.
1641
                # If unchanged, then this line is straight from base. If a or b
1642
                # or both killed the line, then it *used* to be in base.
1643
                base_lines.append(line)
1644
            else:
1645
                if state not in ('killed-base', 'irrelevant',
1646
                                 'ghost-a', 'ghost-b',
4634.101.9 by John Arbash Meinel
Reverse the .BASE values for --lca and conflicted lines.
1647
                                 'new-a', 'new-b',
1648
                                 'conflicted-a', 'conflicted-b'):
4634.101.7 by John Arbash Meinel
Start working on the ability to drop a .BASE file for --weave and --lca merge.
1649
                    # killed-base, irrelevant means it doesn't apply
1650
                    # ghost-a/ghost-b are harder to say for sure, but they
1651
                    # aren't in the 'inc_c' which means they aren't in the
4634.101.13 by John Arbash Meinel
Clean up a code comment.
1652
                    # shared base of a & b. So we don't include them.  And
1653
                    # obviously if the line is newly inserted, it isn't in base
1654
1655
                    # If 'conflicted-a' or b, then it is new vs one base, but
1656
                    # old versus another base. However, if we make it present
1657
                    # in the base, it will be deleted from the target, and it
4634.101.9 by John Arbash Meinel
Reverse the .BASE values for --lca and conflicted lines.
1658
                    # seems better to get a line doubled in the merge result,
1659
                    # rather than have it deleted entirely.
4634.101.13 by John Arbash Meinel
Clean up a code comment.
1660
                    # Example, each node is the 'text' at that point:
1661
                    #           MN
1662
                    #          /   \
1663
                    #        MaN   MbN
1664
                    #         |  X  |
1665
                    #        MabN MbaN
1666
                    #          \   /
1667
                    #           ???
1668
                    # There was a criss-cross conflict merge. Both sides
1669
                    # include the other, but put themselves first.
1670
                    # Weave marks this as a 'clean' merge, picking OTHER over
1671
                    # THIS. (Though the details depend on order inserted into
1672
                    # weave, etc.)
1673
                    # LCA generates a plan:
1674
                    # [('unchanged', M),
1675
                    #  ('conflicted-b', b),
1676
                    #  ('unchanged', a),
1677
                    #  ('conflicted-a', b),
1678
                    #  ('unchanged', N)]
1679
                    # If you mark 'conflicted-*' as part of BASE, then a 3-way
1680
                    # merge tool will cleanly generate "MaN" (as BASE vs THIS
1681
                    # removes one 'b', and BASE vs OTHER removes the other)
1682
                    # If you include neither, 3-way creates a clean "MbabN" as
1683
                    # THIS adds one 'b', and OTHER does too.
1684
                    # It seems that having the line 2 times is better than
1685
                    # having it omitted. (Easier to manually delete than notice
1686
                    # it needs to be added.)
4634.101.7 by John Arbash Meinel
Start working on the ability to drop a .BASE file for --weave and --lca merge.
1687
                    raise AssertionError('Unknown state: %s' % (state,))
1688
        return base_lines
1689
1664.2.14 by Aaron Bentley
spacing fix
1690
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1691
class WeaveMerge(PlanWeaveMerge):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
1692
    """Weave merge that takes a VersionedFile and two versions as its input."""
1551.6.13 by Aaron Bentley
Cleanup
1693
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1694
    def __init__(self, versionedfile, ver_a, ver_b,
1551.6.14 by Aaron Bentley
Tweaks from merge review
1695
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
1696
        plan = versionedfile.plan_merge(ver_a, ver_b)
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1697
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
1698
1699
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1700
class VirtualVersionedFiles(VersionedFiles):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1701
    """Dummy implementation for VersionedFiles that uses other functions for
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1702
    obtaining fulltexts and parent maps.
1703
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1704
    This is always on the bottom of the stack and uses string keys
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1705
    (rather than tuples) internally.
1706
    """
1707
1708
    def __init__(self, get_parent_map, get_lines):
1709
        """Create a VirtualVersionedFiles.
1710
1711
        :param get_parent_map: Same signature as Repository.get_parent_map.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1712
        :param get_lines: Should return lines for specified key or None if
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1713
                          not available.
1714
        """
1715
        super(VirtualVersionedFiles, self).__init__()
1716
        self._get_parent_map = get_parent_map
1717
        self._get_lines = get_lines
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1718
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1719
    def check(self, progressbar=None):
1720
        """See VersionedFiles.check.
1721
1722
        :note: Always returns True for VirtualVersionedFiles.
1723
        """
1724
        return True
1725
1726
    def add_mpdiffs(self, records):
1727
        """See VersionedFiles.mpdiffs.
1728
1729
        :note: Not implemented for VirtualVersionedFiles.
1730
        """
1731
        raise NotImplementedError(self.add_mpdiffs)
1732
1733
    def get_parent_map(self, keys):
1734
        """See VersionedFiles.get_parent_map."""
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1735
        return dict([((k,), tuple([(p,) for p in v]))
1736
            for k,v in self._get_parent_map([k for (k,) in keys]).iteritems()])
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1737
1738
    def get_sha1s(self, keys):
1739
        """See VersionedFiles.get_sha1s."""
1740
        ret = {}
1741
        for (k,) in keys:
1742
            lines = self._get_lines(k)
1743
            if lines is not None:
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1744
                if not isinstance(lines, list):
1745
                    raise AssertionError
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1746
                ret[(k,)] = osutils.sha_strings(lines)
1747
        return ret
1748
1749
    def get_record_stream(self, keys, ordering, include_delta_closure):
1750
        """See VersionedFiles.get_record_stream."""
1751
        for (k,) in list(keys):
1752
            lines = self._get_lines(k)
1753
            if lines is not None:
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1754
                if not isinstance(lines, list):
1755
                    raise AssertionError
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1756
                yield ChunkedContentFactory((k,), None,
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1757
                        sha1=osutils.sha_strings(lines),
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1758
                        chunks=lines)
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1759
            else:
1760
                yield AbsentContentFactory((k,))
1761
3949.4.1 by Jelmer Vernooij
Implement VirtualVersionedFiles.iter_lines_added_or_present_in_keys.
1762
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1763
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
1764
        for i, (key,) in enumerate(keys):
1765
            if pb is not None:
4110.2.10 by Martin Pool
Tweak iter_lines progress messages
1766
                pb.update("Finding changed lines", i, len(keys))
3949.4.1 by Jelmer Vernooij
Implement VirtualVersionedFiles.iter_lines_added_or_present_in_keys.
1767
            for l in self._get_lines(key):
1768
                yield (l, key)
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
1769
1770
5375.1.4 by Andrew Bennetts
Put NoDupeAddLinesDecorator in versionedfiles.py, and make it slightly more reusable.
1771
class NoDupeAddLinesDecorator(object):
1772
    """Decorator for a VersionedFiles that skips doing an add_lines if the key
1773
    is already present.
1774
    """
1775
1776
    def __init__(self, store):
1777
        self._store = store
1778
1779
    def add_lines(self, key, parents, lines, parent_texts=None,
1780
            left_matching_blocks=None, nostore_sha=None, random_id=False,
1781
            check_content=True):
1782
        """See VersionedFiles.add_lines.
1783
        
1784
        This implementation may return None as the third element of the return
1785
        value when the original store wouldn't.
1786
        """
1787
        if nostore_sha:
1788
            raise NotImplementedError(
1789
                "NoDupeAddLinesDecorator.add_lines does not implement the "
1790
                "nostore_sha behaviour.")
1791
        if key[-1] is None:
1792
            sha1 = osutils.sha_strings(lines)
1793
            key = ("sha1:" + sha1,)
1794
        else:
1795
            sha1 = None
1796
        if key in self._store.get_parent_map([key]):
1797
            # This key has already been inserted, so don't do it again.
1798
            if sha1 is None:
1799
                sha1 = osutils.sha_strings(lines)
1800
            return sha1, sum(map(len, lines)), None
1801
        return self._store.add_lines(key, parents, lines,
1802
                parent_texts=parent_texts,
1803
                left_matching_blocks=left_matching_blocks,
1804
                nostore_sha=nostore_sha, random_id=random_id,
1805
                check_content=check_content)
1806
1807
    def __getattr__(self, name):
1808
        return getattr(self._store, name)
1809
1810
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
1811
def network_bytes_to_kind_and_offset(network_bytes):
1812
    """Strip of a record kind from the front of network_bytes.
1813
1814
    :param network_bytes: The bytes of a record.
1815
    :return: A tuple (storage_kind, offset_of_remaining_bytes)
1816
    """
1817
    line_end = network_bytes.find('\n')
1818
    storage_kind = network_bytes[:line_end]
1819
    return storage_kind, line_end + 1
1820
1821
1822
class NetworkRecordStream(object):
1823
    """A record_stream which reconstitures a serialised stream."""
1824
1825
    def __init__(self, bytes_iterator):
1826
        """Create a NetworkRecordStream.
1827
1828
        :param bytes_iterator: An iterator of bytes. Each item in this
1829
            iterator should have been obtained from a record_streams'
1830
            record.get_bytes_as(record.storage_kind) call.
1831
        """
1832
        self._bytes_iterator = bytes_iterator
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
1833
        self._kind_factory = {
1834
            'fulltext': fulltext_network_to_record,
1835
            'groupcompress-block': groupcompress.network_block_to_records,
1836
            'knit-ft-gz': knit.knit_network_to_record,
1837
            'knit-delta-gz': knit.knit_network_to_record,
1838
            'knit-annotated-ft-gz': knit.knit_network_to_record,
1839
            'knit-annotated-delta-gz': knit.knit_network_to_record,
1840
            'knit-delta-closure': knit.knit_delta_closure_to_records,
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
1841
            }
1842
1843
    def read(self):
1844
        """Read the stream.
1845
1846
        :return: An iterator as per VersionedFiles.get_record_stream().
1847
        """
1848
        for bytes in self._bytes_iterator:
1849
            storage_kind, line_end = network_bytes_to_kind_and_offset(bytes)
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1850
            for record in self._kind_factory[storage_kind](
1851
                storage_kind, bytes, line_end):
1852
                yield record
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1853
1854
1855
def fulltext_network_to_record(kind, bytes, line_end):
1856
    """Convert a network fulltext record to record."""
1857
    meta_len, = struct.unpack('!L', bytes[line_end:line_end+4])
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1858
    record_meta = bytes[line_end+4:line_end+4+meta_len]
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1859
    key, parents = bencode.bdecode_as_tuple(record_meta)
1860
    if parents == 'nil':
1861
        parents = None
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1862
    fulltext = bytes[line_end+4+meta_len:]
1863
    return [FulltextContentFactory(key, parents, None, fulltext)]
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1864
1865
1866
def _length_prefix(bytes):
1867
    return struct.pack('!L', len(bytes))
1868
1869
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1870
def record_to_fulltext_bytes(record):
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1871
    if record.parents is None:
1872
        parents = 'nil'
1873
    else:
1874
        parents = record.parents
1875
    record_meta = bencode.bencode((record.key, parents))
1876
    record_content = record.get_bytes_as('fulltext')
1877
    return "fulltext\n%s%s%s" % (
1878
        _length_prefix(record_meta), record_meta, record_content)
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1879
1880
1881
def sort_groupcompress(parent_map):
1882
    """Sort and group the keys in parent_map into groupcompress order.
1883
1884
    groupcompress is defined (currently) as reverse-topological order, grouped
1885
    by the key prefix.
1886
1887
    :return: A sorted-list of keys
1888
    """
1889
    # gc-optimal ordering is approximately reverse topological,
1890
    # properly grouped by file-id.
1891
    per_prefix_map = {}
1892
    for item in parent_map.iteritems():
1893
        key = item[0]
1894
        if isinstance(key, str) or len(key) == 1:
1895
            prefix = ''
1896
        else:
1897
            prefix = key[0]
1898
        try:
1899
            per_prefix_map[prefix].append(item)
1900
        except KeyError:
1901
            per_prefix_map[prefix] = [item]
1902
1903
    present_keys = []
1904
    for prefix in sorted(per_prefix_map):
1905
        present_keys.extend(reversed(tsort.topo_sort(per_prefix_map[prefix])))
1906
    return present_keys
5757.8.1 by Jelmer Vernooij
Avoid bzrlib.knit imports when using groupcompress repositories.
1907
1908
1909
class _KeyRefs(object):
1910
1911
    def __init__(self, track_new_keys=False):
1912
        # dict mapping 'key' to 'set of keys referring to that key'
1913
        self.refs = {}
1914
        if track_new_keys:
1915
            # set remembering all new keys
1916
            self.new_keys = set()
1917
        else:
1918
            self.new_keys = None
1919
1920
    def clear(self):
1921
        if self.refs:
1922
            self.refs.clear()
1923
        if self.new_keys:
1924
            self.new_keys.clear()
1925
1926
    def add_references(self, key, refs):
1927
        # Record the new references
1928
        for referenced in refs:
1929
            try:
1930
                needed_by = self.refs[referenced]
1931
            except KeyError:
1932
                needed_by = self.refs[referenced] = set()
1933
            needed_by.add(key)
1934
        # Discard references satisfied by the new key
1935
        self.add_key(key)
1936
1937
    def get_new_keys(self):
1938
        return self.new_keys
1939
    
1940
    def get_unsatisfied_refs(self):
1941
        return self.refs.iterkeys()
1942
1943
    def _satisfy_refs_for_key(self, key):
1944
        try:
1945
            del self.refs[key]
1946
        except KeyError:
1947
            # No keys depended on this key.  That's ok.
1948
            pass
1949
1950
    def add_key(self, key):
1951
        # satisfy refs for key, and remember that we've seen this key.
1952
        self._satisfy_refs_for_key(key)
1953
        if self.new_keys is not None:
1954
            self.new_keys.add(key)
1955
1956
    def satisfy_refs_for_keys(self, keys):
1957
        for key in keys:
1958
            self._satisfy_refs_for_key(key)
1959
1960
    def get_referrers(self):
1961
        result = set()
1962
        for referrers in self.refs.itervalues():
1963
            result.update(referrers)
1964
        return result
1965
1966
5815.5.8 by Jelmer Vernooij
Use traditional (fileid, revision) entries in file graph.
1967