~bzr-pqm/bzr/bzr.dev

3830.3.20 by John Arbash Meinel
Minor PEP8 and copyright updates.
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
2
#
3
# Authors:
4
#   Johan Rydberg <jrydberg@gnu.org>
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
10
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
15
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
18
# 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.
19
20
"""Versioned text file storage api."""
21
3350.8.2 by Robert Collins
stacked get_parent_map.
22
from copy import copy
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
23
from cStringIO import StringIO
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.
24
import os
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
25
import struct
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
26
from zlib import adler32
27
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
28
from bzrlib.lazy_import import lazy_import
29
lazy_import(globals(), """
3224.5.20 by Andrew Bennetts
Remove or lazyify a couple more imports.
30
import urllib
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
31
32
from bzrlib import (
33
    errors,
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,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
41
    ui,
42
    )
4379.3.3 by Gary van der Merwe
Rename and add doc string for StackedParentsProvider.
43
from bzrlib.graph import DictParentsProvider, Graph, StackedParentsProvider
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
44
from bzrlib.transport.memory import MemoryTransport
45
""")
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.
46
from bzrlib.inter import InterObject
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
47
from bzrlib.registry import Registry
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.
48
from bzrlib.symbol_versioning import *
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
49
from bzrlib.textmerge import TextMerge
2694.5.4 by Jelmer Vernooij
Move bzrlib.util.bencode to bzrlib._bencode_py.
50
from bzrlib import bencode
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.
51
52
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
53
adapter_registry = Registry()
54
adapter_registry.register_lazy(('knit-delta-gz', 'fulltext'), 'bzrlib.knit',
55
    'DeltaPlainToFullText')
56
adapter_registry.register_lazy(('knit-ft-gz', 'fulltext'), 'bzrlib.knit',
57
    'FTPlainToFullText')
58
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'knit-delta-gz'),
59
    'bzrlib.knit', 'DeltaAnnotatedToUnannotated')
60
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'fulltext'),
61
    'bzrlib.knit', 'DeltaAnnotatedToFullText')
62
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'knit-ft-gz'),
63
    'bzrlib.knit', 'FTAnnotatedToUnannotated')
64
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'fulltext'),
65
    'bzrlib.knit', 'FTAnnotatedToFullText')
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
66
# adapter_registry.register_lazy(('knit-annotated-ft-gz', 'chunked'),
67
#     'bzrlib.knit', 'FTAnnotatedToChunked')
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
68
69
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
70
class ContentFactory(object):
71
    """Abstract interface for insertion and retrieval from a VersionedFile.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
72
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
73
    :ivar sha1: None, or the sha1 of the content fulltext.
74
    :ivar storage_kind: The native storage kind of this factory. One of
75
        'mpdiff', 'knit-annotated-ft', 'knit-annotated-delta', 'knit-ft',
76
        'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
77
        'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'.
78
    :ivar key: The key of this content. Each key is a tuple with a single
79
        string in it.
80
    :ivar parents: A tuple of parent keys for self.key. If the object has
81
        no parent information, None (as opposed to () for an empty list of
82
        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.
83
    """
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
84
85
    def __init__(self):
86
        """Create a ContentFactory."""
87
        self.sha1 = None
88
        self.storage_kind = None
89
        self.key = None
90
        self.parents = None
91
92
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
93
class ChunkedContentFactory(ContentFactory):
94
    """Static data content factory.
95
96
    This takes a 'chunked' list of strings. The only requirement on 'chunked' is
97
    that ''.join(lines) becomes a valid fulltext. A tuple of a single string
98
    satisfies this, as does a list of lines.
99
100
    :ivar sha1: None, or the sha1 of the content fulltext.
101
    :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'
102
        'chunked'
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
103
    :ivar key: The key of this content. Each key is a tuple with a single
104
        string in it.
105
    :ivar parents: A tuple of parent keys for self.key. If the object has
106
        no parent information, None (as opposed to () for an empty list of
107
        parents).
108
     """
109
110
    def __init__(self, key, parents, sha1, chunks):
111
        """Create a ContentFactory."""
112
        self.sha1 = sha1
3890.2.2 by John Arbash Meinel
Change the signature to report the storage kind as 'chunked'
113
        self.storage_kind = 'chunked'
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
114
        self.key = key
115
        self.parents = parents
116
        self._chunks = chunks
117
118
    def get_bytes_as(self, storage_kind):
119
        if storage_kind == 'chunked':
120
            return self._chunks
121
        elif storage_kind == 'fulltext':
122
            return ''.join(self._chunks)
123
        raise errors.UnavailableRepresentation(self.key, storage_kind,
124
            self.storage_kind)
125
126
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.
127
class FulltextContentFactory(ContentFactory):
128
    """Static data content factory.
129
130
    This takes a fulltext when created and just returns that during
131
    get_bytes_as('fulltext').
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
132
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.
133
    :ivar sha1: None, or the sha1 of the content fulltext.
134
    :ivar storage_kind: The native storage kind of this factory. Always
135
        'fulltext'.
136
    :ivar key: The key of this content. Each key is a tuple with a single
137
        string in it.
138
    :ivar parents: A tuple of parent keys for self.key. If the object has
139
        no parent information, None (as opposed to () for an empty list of
140
        parents).
141
     """
142
143
    def __init__(self, key, parents, sha1, text):
144
        """Create a ContentFactory."""
145
        self.sha1 = sha1
146
        self.storage_kind = 'fulltext'
147
        self.key = key
148
        self.parents = parents
149
        self._text = text
150
151
    def get_bytes_as(self, storage_kind):
152
        if storage_kind == self.storage_kind:
153
            return self._text
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
154
        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.
155
            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.
156
        raise errors.UnavailableRepresentation(self.key, storage_kind,
157
            self.storage_kind)
158
159
160
class AbsentContentFactory(ContentFactory):
3350.3.12 by Robert Collins
Generate streams with absent records.
161
    """A placeholder content factory for unavailable texts.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
162
3350.3.12 by Robert Collins
Generate streams with absent records.
163
    :ivar sha1: None.
164
    :ivar storage_kind: 'absent'.
165
    :ivar key: The key of this content. Each key is a tuple with a single
166
        string in it.
167
    :ivar parents: None.
168
    """
169
170
    def __init__(self, key):
171
        """Create a ContentFactory."""
172
        self.sha1 = None
173
        self.storage_kind = 'absent'
174
        self.key = key
175
        self.parents = None
176
177
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.
178
class AdapterFactory(ContentFactory):
179
    """A content factory to adapt between key prefix's."""
180
181
    def __init__(self, key, parents, adapted):
182
        """Create an adapter factory instance."""
183
        self.key = key
184
        self.parents = parents
185
        self._adapted = adapted
186
187
    def __getattr__(self, attr):
188
        """Return a member from the adapted object."""
189
        if attr in ('key', 'parents'):
190
            return self.__dict__[attr]
191
        else:
192
            return getattr(self._adapted, attr)
193
194
3350.3.14 by Robert Collins
Deprecate VersionedFile.join.
195
def filter_absent(record_stream):
196
    """Adapt a record stream to remove absent records."""
197
    for record in record_stream:
198
        if record.storage_kind != 'absent':
199
            yield record
200
201
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
202
class VersionedFile(object):
203
    """Versioned text file storage.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
204
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
205
    A versioned file manages versions of line-based text files,
206
    keeping track of the originating version for each line.
207
208
    To clients the "lines" of the file are represented as a list of
209
    strings. These strings will typically have terminal newline
210
    characters, but this is not required.  In particular files commonly
211
    do not have a newline at the end of the file.
212
213
    Texts are identified by a version-id string.
214
    """
215
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
216
    @staticmethod
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
217
    def check_not_reserved_id(version_id):
218
        revision.check_not_reserved_id(version_id)
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
219
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
220
    def copy_to(self, name, transport):
221
        """Copy this versioned file to name on transport."""
222
        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
223
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
224
    def get_record_stream(self, versions, ordering, include_delta_closure):
225
        """Get a stream of records for versions.
226
227
        :param versions: The versions to include. Each version is a tuple
228
            (version,).
229
        :param ordering: Either 'unordered' or 'topological'. A topologically
230
            sorted stream has compression parents strictly before their
231
            children.
232
        :param include_delta_closure: If True then the closure across any
3350.3.22 by Robert Collins
Review feedback.
233
            compression parents will be included (in the data content of the
234
            stream, not in the emitted records). This guarantees that
235
            'fulltext' can be used successfully on every record.
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
236
        :return: An iterator of ContentFactory objects, each of which is only
237
            valid until the iterator is advanced.
238
        """
239
        raise NotImplementedError(self.get_record_stream)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
240
241
    def has_version(self, version_id):
242
        """Returns whether version is present."""
243
        raise NotImplementedError(self.has_version)
244
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
245
    def insert_record_stream(self, stream):
246
        """Insert a record stream into this versioned file.
247
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
248
        :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.
249
        :return: None
250
        :seealso VersionedFile.get_record_stream:
251
        """
252
        raise NotImplementedError
253
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
254
    def add_lines(self, version_id, parents, lines, parent_texts=None,
2805.6.7 by Robert Collins
Review feedback.
255
        left_matching_blocks=None, nostore_sha=None, random_id=False,
256
        check_content=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
257
        """Add a single text on top of the versioned file.
258
259
        Must raise RevisionAlreadyPresent if the new version is
260
        already present in file history.
261
262
        Must raise RevisionNotPresent if any of the given parents are
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
263
        not present in file history.
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
264
265
        :param lines: A list of lines. Each line must be a bytestring. And all
266
            of them except the last must be terminated with \n and contain no
267
            other \n's. The last line may either contain no \n's or a single
268
            terminated \n. If the lines list does meet this constraint the add
269
            routine may error or may succeed - but you will be unable to read
270
            the data back accurately. (Checking the lines have been split
2805.6.7 by Robert Collins
Review feedback.
271
            correctly is expensive and extremely unlikely to catch bugs so it
272
            is not done at runtime unless check_content is True.)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
273
        :param parent_texts: An optional dictionary containing the opaque
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
274
            representations of some or all of the parents of version_id to
275
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
276
            returned by add_lines or data corruption can be caused.
2520.4.148 by Aaron Bentley
Updates from review
277
        :param left_matching_blocks: a hint about which areas are common
278
            between the text and its left-hand-parent.  The format is
279
            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.
280
        :param nostore_sha: Raise ExistingContent and do not add the lines to
281
            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.
282
        :param random_id: If True a random id has been selected rather than
283
            an id determined by some deterministic process such as a converter
284
            from a foreign VCS. When True the backend may choose not to check
285
            for uniqueness of the resulting key within the versioned file, so
286
            this should only be done when the result is expected to be unique
287
            anyway.
2805.6.7 by Robert Collins
Review feedback.
288
        :param check_content: If True, the lines supplied are verified to be
289
            bytestrings that are correctly formed lines.
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
290
        :return: The text sha1, the number of bytes in the text, and an opaque
291
                 representation of the inserted version which can be provided
292
                 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.
293
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
294
        self._check_write_ok()
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
295
        return self._add_lines(version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
296
            left_matching_blocks, nostore_sha, random_id, check_content)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
297
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
298
    def _add_lines(self, version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
299
        left_matching_blocks, nostore_sha, random_id, check_content):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
300
        """Helper to do the class specific add_lines."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
301
        raise NotImplementedError(self.add_lines)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
302
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
303
    def add_lines_with_ghosts(self, version_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
304
        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.
305
        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.
306
        """Add lines to the versioned file, allowing ghosts to be present.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
307
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
308
        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.
309
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
310
        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.
311
        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.
312
            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.
313
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
314
    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.
315
        nostore_sha, random_id, check_content, left_matching_blocks):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
316
        """Helper to do class specific add_lines_with_ghosts."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
317
        raise NotImplementedError(self.add_lines_with_ghosts)
318
1563.2.19 by Robert Collins
stub out a check for knits.
319
    def check(self, progress_bar=None):
320
        """Check the versioned file for integrity."""
321
        raise NotImplementedError(self.check)
322
1666.1.6 by Robert Collins
Make knit the default format.
323
    def _check_lines_not_unicode(self, lines):
324
        """Check that lines being added to a versioned file are not unicode."""
325
        for line in lines:
326
            if line.__class__ is not str:
327
                raise errors.BzrBadParameterUnicode("lines")
328
329
    def _check_lines_are_lines(self, lines):
330
        """Check that the lines really are full lines without inline EOL."""
331
        for line in lines:
332
            if '\n' in line[:-1]:
333
                raise errors.BzrBadParameterContainsNewline("lines")
334
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
335
    def get_format_signature(self):
336
        """Get a text description of the data encoding in this file.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
337
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
338
        :since: 0.90
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
339
        """
340
        raise NotImplementedError(self.get_format_signature)
341
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
342
    def make_mpdiffs(self, version_ids):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
343
        """Create multiparent diffs for specified versions."""
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
344
        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.
345
        knit_versions.update(version_ids)
346
        parent_map = self.get_parent_map(version_ids)
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
347
        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.
348
            try:
349
                knit_versions.update(parent_map[version_id])
350
            except KeyError:
3453.3.1 by Daniel Fischer
Raise the right exception in make_mpdiffs (bug #235687)
351
                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.
352
        # We need to filter out ghosts, because we can't diff against them.
353
        knit_versions = set(self.get_parent_map(knit_versions).keys())
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
354
        lines = dict(zip(knit_versions,
355
            self._get_lf_split_line_list(knit_versions)))
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
356
        diffs = []
357
        for version_id in version_ids:
358
            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.
359
            try:
360
                parents = [lines[p] for p in parent_map[version_id] if p in
361
                    knit_versions]
362
            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
363
                # I don't know how this could ever trigger.
364
                # parent_map[version_id] was already triggered in the previous
365
                # for loop, and lines[p] has the 'if p in knit_versions' check,
366
                # so we again won't have a KeyError.
3453.3.1 by Daniel Fischer
Raise the right exception in make_mpdiffs (bug #235687)
367
                raise errors.RevisionNotPresent(version_id, self)
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
368
            if len(parents) > 0:
369
                left_parent_blocks = self._extract_blocks(version_id,
370
                                                          parents[0], target)
371
            else:
372
                left_parent_blocks = None
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
373
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
374
                         left_parent_blocks))
375
        return diffs
376
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
377
    def _extract_blocks(self, version_id, source, target):
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
378
        return None
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
379
2520.4.61 by Aaron Bentley
Do bulk insertion of records
380
    def add_mpdiffs(self, records):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
381
        """Add mpdiffs to this VersionedFile.
2520.4.126 by Aaron Bentley
Add more docs
382
383
        Records should be iterables of version, parents, expected_sha1,
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
384
        mpdiff. mpdiff should be a MultiParent instance.
2520.4.126 by Aaron Bentley
Add more docs
385
        """
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
386
        # Does this need to call self._check_write_ok()? (IanC 20070919)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
387
        vf_parents = {}
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
388
        mpvf = multiparent.MultiMemoryVersionedFile()
389
        versions = []
390
        for version, parent_ids, expected_sha1, mpdiff in records:
391
            versions.append(version)
392
            mpvf.add_diff(mpdiff, version, parent_ids)
393
        needed_parents = set()
2520.4.142 by Aaron Bentley
Clean up installation of inventory records
394
        for version, parent_ids, expected_sha1, mpdiff in records:
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
395
            needed_parents.update(p for p in parent_ids
396
                                  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.
397
        present_parents = set(self.get_parent_map(needed_parents).keys())
398
        for parent_id, lines in zip(present_parents,
399
                                 self._get_lf_split_line_list(present_parents)):
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
400
            mpvf.add_version(lines, parent_id, [])
401
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
402
            zip(records, mpvf.get_line_list(versions)):
403
            if len(parent_ids) == 1:
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
404
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
2520.4.141 by Aaron Bentley
More batch operations adding mpdiffs
405
                    mpvf.get_diff(parent_ids[0]).num_lines()))
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
406
            else:
407
                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.
408
            try:
409
                _, _, version_text = self.add_lines_with_ghosts(version,
410
                    parent_ids, lines, vf_parents,
411
                    left_matching_blocks=left_matching_blocks)
412
            except NotImplementedError:
413
                # The vf can't handle ghosts, so add lines normally, which will
414
                # (reasonably) fail if there are ghosts in the data.
415
                _, _, version_text = self.add_lines(version,
416
                    parent_ids, lines, vf_parents,
417
                    left_matching_blocks=left_matching_blocks)
2520.4.61 by Aaron Bentley
Do bulk insertion of records
418
            vf_parents[version] = version_text
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
419
        sha1s = self.get_sha1s(versions)
420
        for version, parent_ids, expected_sha1, mpdiff in records:
421
            if expected_sha1 != sha1s[version]:
2520.4.71 by Aaron Bentley
Update test to accept VersionedFileInvalidChecksum instead of TestamentMismatch
422
                raise errors.VersionedFileInvalidChecksum(version)
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
423
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
424
    def get_text(self, version_id):
425
        """Return version contents as a text string.
426
427
        Raises RevisionNotPresent if version is not present in
428
        file history.
429
        """
430
        return ''.join(self.get_lines(version_id))
431
    get_string = get_text
432
1756.2.1 by Aaron Bentley
Implement get_texts
433
    def get_texts(self, version_ids):
434
        """Return the texts of listed versions as a list of strings.
435
436
        Raises RevisionNotPresent if version is not present in
437
        file history.
438
        """
439
        return [''.join(self.get_lines(v)) for v in version_ids]
440
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
441
    def get_lines(self, version_id):
442
        """Return version contents as a sequence of lines.
443
444
        Raises RevisionNotPresent if version is not present in
445
        file history.
446
        """
447
        raise NotImplementedError(self.get_lines)
448
2520.4.90 by Aaron Bentley
Handle \r terminated lines in Weaves properly
449
    def _get_lf_split_line_list(self, version_ids):
450
        return [StringIO(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
451
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
452
    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.
453
        """Return a list of all ancestors of given version(s). This
454
        will not include the null revision.
455
2490.2.32 by Aaron Bentley
Merge of not-sorting-ancestry branch
456
        This list will not be topologically sorted if topo_sorted=False is
457
        passed.
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
458
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
459
        Must raise RevisionNotPresent if any of the given versions are
460
        not present in file history."""
461
        if isinstance(version_ids, basestring):
462
            version_ids = [version_ids]
463
        raise NotImplementedError(self.get_ancestry)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
464
1594.2.8 by Robert Collins
add ghost aware apis to knits.
465
    def get_ancestry_with_ghosts(self, version_ids):
466
        """Return a list of all ancestors of given version(s). This
467
        will not include the null revision.
468
469
        Must raise RevisionNotPresent if any of the given versions are
470
        not present in file history.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
471
1594.2.8 by Robert Collins
add ghost aware apis to knits.
472
        Ghosts that are known about will be included in ancestry list,
473
        but are not explicitly marked.
474
        """
475
        raise NotImplementedError(self.get_ancestry_with_ghosts)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
476
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
477
    def get_parent_map(self, version_ids):
478
        """Get a map of the parents of version_ids.
479
480
        :param version_ids: The version ids to look up parents for.
481
        :return: A mapping from version id to parents.
482
        """
483
        raise NotImplementedError(self.get_parent_map)
484
1594.2.8 by Robert Collins
add ghost aware apis to knits.
485
    def get_parents_with_ghosts(self, version_id):
486
        """Return version names for parents of version_id.
487
488
        Will raise RevisionNotPresent if version_id is not present
489
        in the history.
490
491
        Ghosts that are known about will be included in the parent list,
492
        but are not explicitly marked.
493
        """
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
494
        try:
495
            return list(self.get_parent_map([version_id])[version_id])
496
        except KeyError:
497
            raise errors.RevisionNotPresent(version_id, self)
1594.2.8 by Robert Collins
add ghost aware apis to knits.
498
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
499
    def annotate(self, version_id):
3316.2.13 by Robert Collins
* ``VersionedFile.annotate_iter`` is deprecated. While in principal this
500
        """Return a list of (version-id, line) tuples for version_id.
501
502
        :raise RevisionNotPresent: If the given version is
503
        not present in file history.
504
        """
505
        raise NotImplementedError(self.annotate)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
506
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
507
    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)
508
                                                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.
509
        """Iterate over the lines in the versioned file from version_ids.
510
2975.3.2 by Robert Collins
Review feedback - document the API change and improve readability in pack's _do_copy_nodes.
511
        This may return lines from other versions. Each item the returned
512
        iterator yields is a tuple of a line and a text version that that line
513
        is present in (not introduced in).
514
515
        Ordering of results is in whatever order is most suitable for the
516
        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.
517
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
518
        If a progress bar is supplied, it may be used to indicate progress.
519
        The caller is responsible for cleaning up progress bars (because this
520
        is an iterator).
521
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
522
        NOTES: Lines are normalised: they will all have \n terminators.
523
               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.
524
525
        :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.
526
        """
527
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
528
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
529
    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.
530
        """Return pseudo-annotation indicating how the two versions merge.
531
532
        This is computed between versions a and b and their common
533
        base.
534
535
        Weave lines present in none of them are skipped entirely.
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
536
537
        Legend:
538
        killed-base Dead in base revision
539
        killed-both Killed in each revision
540
        killed-a    Killed in a
541
        killed-b    Killed in b
542
        unchanged   Alive in both a and b (possibly created in both)
543
        new-a       Created in a
544
        new-b       Created in b
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
545
        ghost-a     Killed in a, unborn in b
1664.2.5 by Aaron Bentley
Update plan-merge legend
546
        ghost-b     Killed in b, unborn in a
1664.2.2 by Aaron Bentley
Added legend for plan-merge output
547
        irrelevant  Not in either revision
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
548
        """
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
549
        raise NotImplementedError(VersionedFile.plan_merge)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
550
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
551
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
1551.6.14 by Aaron Bentley
Tweaks from merge review
552
                    b_marker=TextMerge.B_MARKER):
1551.6.12 by Aaron Bentley
Indicate conflicts from merge_lines, insead of guessing
553
        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
554
1664.2.7 by Aaron Bentley
Merge bzr.dev
555
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.
556
class RecordingVersionedFilesDecorator(object):
557
    """A minimal versioned files that records calls made on it.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
558
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
559
    Only enough methods have been added to support tests using it to date.
560
561
    :ivar calls: A list of the calls made; can be reset at any time by
562
        assigning [] to it.
563
    """
564
565
    def __init__(self, backing_vf):
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
566
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
567
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
568
        :param backing_vf: The versioned file to answer all methods.
569
        """
570
        self._backing_vf = backing_vf
571
        self.calls = []
572
3350.8.2 by Robert Collins
stacked get_parent_map.
573
    def add_lines(self, key, parents, lines, parent_texts=None,
574
        left_matching_blocks=None, nostore_sha=None, random_id=False,
575
        check_content=True):
576
        self.calls.append(("add_lines", key, parents, lines, parent_texts,
577
            left_matching_blocks, nostore_sha, random_id, check_content))
578
        return self._backing_vf.add_lines(key, parents, lines, parent_texts,
579
            left_matching_blocks, nostore_sha, random_id, check_content)
580
3517.4.19 by Martin Pool
Update test for knit.check() to expect it to recurse into fallback vfs
581
    def check(self):
582
        self._backing_vf.check()
583
3350.8.2 by Robert Collins
stacked get_parent_map.
584
    def get_parent_map(self, keys):
585
        self.calls.append(("get_parent_map", copy(keys)))
586
        return self._backing_vf.get_parent_map(keys)
587
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.
588
    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!).
589
        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.
590
            include_delta_closure))
591
        return self._backing_vf.get_record_stream(keys, sort_order,
592
            include_delta_closure)
593
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
594
    def get_sha1s(self, keys):
595
        self.calls.append(("get_sha1s", copy(keys)))
596
        return self._backing_vf.get_sha1s(keys)
597
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
598
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
599
        self.calls.append(("iter_lines_added_or_present_in_keys", copy(keys)))
3350.8.14 by Robert Collins
Review feedback.
600
        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.
601
3350.8.4 by Robert Collins
Vf.keys() stacking support.
602
    def keys(self):
603
        self.calls.append(("keys",))
604
        return self._backing_vf.keys()
605
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.
606
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
607
class OrderingVersionedFilesDecorator(RecordingVersionedFilesDecorator):
608
    """A VF that records calls, and returns keys in specific order.
609
610
    :ivar calls: A list of the calls made; can be reset at any time by
611
        assigning [] to it.
612
    """
613
614
    def __init__(self, backing_vf, key_priority):
615
        """Create a RecordingVersionedFilesDecorator decorating backing_vf.
616
617
        :param backing_vf: The versioned file to answer all methods.
618
        :param key_priority: A dictionary defining what order keys should be
619
            returned from an 'unordered' get_record_stream request.
620
            Keys with lower priority are returned first, keys not present in
621
            the map get an implicit priority of 0, and are returned in
622
            lexicographical order.
623
        """
624
        RecordingVersionedFilesDecorator.__init__(self, backing_vf)
625
        self._key_priority = key_priority
626
627
    def get_record_stream(self, keys, sort_order, include_delta_closure):
628
        self.calls.append(("get_record_stream", list(keys), sort_order,
629
            include_delta_closure))
630
        if sort_order == 'unordered':
631
            def sort_key(key):
632
                return (self._key_priority.get(key, 0), key)
633
            # Use a defined order by asking for the keys one-by-one from the
634
            # backing_vf
635
            for key in sorted(keys, key=sort_key):
636
                for record in self._backing_vf.get_record_stream([key],
637
                                'unordered', include_delta_closure):
638
                    yield record
639
        else:
640
            for record in self._backing_vf.get_record_stream(keys, sort_order,
641
                            include_delta_closure):
642
                yield record
643
644
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.
645
class KeyMapper(object):
3350.6.10 by Martin Pool
VersionedFiles review cleanups
646
    """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.
647
648
    def map(self, key):
649
        """Map key to an underlying storage identifier.
650
651
        :param key: A key tuple e.g. ('file-id', 'revision-id').
652
        :return: An underlying storage identifier, specific to the partitioning
653
            mechanism.
654
        """
655
        raise NotImplementedError(self.map)
656
657
    def unmap(self, partition_id):
658
        """Map a partitioned storage id back to a key prefix.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
659
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.
660
        :param partition_id: The underlying partition id.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
661
        :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.
662
            id.
663
        """
664
        raise NotImplementedError(self.unmap)
665
666
667
class ConstantMapper(KeyMapper):
668
    """A key mapper that maps to a constant result."""
669
670
    def __init__(self, result):
671
        """Create a ConstantMapper which will return result for all maps."""
672
        self._result = result
673
674
    def map(self, key):
675
        """See KeyMapper.map()."""
676
        return self._result
677
678
679
class URLEscapeMapper(KeyMapper):
680
    """Base class for use with transport backed storage.
681
682
    This provides a map and unmap wrapper that respectively url escape and
683
    unescape their outputs and inputs.
684
    """
685
686
    def map(self, key):
687
        """See KeyMapper.map()."""
688
        return urllib.quote(self._map(key))
689
690
    def unmap(self, partition_id):
691
        """See KeyMapper.unmap()."""
692
        return self._unmap(urllib.unquote(partition_id))
693
694
695
class PrefixMapper(URLEscapeMapper):
696
    """A key mapper that extracts the first component of a key.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
697
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.
698
    This mapper is for use with a transport based backend.
699
    """
700
701
    def _map(self, key):
702
        """See KeyMapper.map()."""
703
        return key[0]
704
705
    def _unmap(self, partition_id):
706
        """See KeyMapper.unmap()."""
707
        return (partition_id,)
708
709
710
class HashPrefixMapper(URLEscapeMapper):
711
    """A key mapper that combines the first component of a key with a hash.
712
713
    This mapper is for use with a transport based backend.
714
    """
715
716
    def _map(self, key):
717
        """See KeyMapper.map()."""
718
        prefix = self._escape(key[0])
719
        return "%02x/%s" % (adler32(prefix) & 0xff, prefix)
720
721
    def _escape(self, prefix):
722
        """No escaping needed here."""
723
        return prefix
724
725
    def _unmap(self, partition_id):
726
        """See KeyMapper.unmap()."""
727
        return (self._unescape(osutils.basename(partition_id)),)
728
729
    def _unescape(self, basename):
730
        """No unescaping needed for HashPrefixMapper."""
731
        return basename
732
733
734
class HashEscapedPrefixMapper(HashPrefixMapper):
735
    """Combines the escaped first component of a key with a hash.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
736
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.
737
    This mapper is for use with a transport based backend.
738
    """
739
740
    _safe = "abcdefghijklmnopqrstuvwxyz0123456789-_@,."
741
742
    def _escape(self, prefix):
743
        """Turn a key element into a filesystem safe string.
744
745
        This is similar to a plain urllib.quote, except
746
        it uses specific safe characters, so that it doesn't
747
        have to translate a lot of valid file ids.
748
        """
749
        # @ does not get escaped. This is because it is a valid
750
        # filesystem character we use all the time, and it looks
751
        # a lot better than seeing %40 all the time.
752
        r = [((c in self._safe) and c or ('%%%02x' % ord(c)))
753
             for c in prefix]
754
        return ''.join(r)
755
756
    def _unescape(self, basename):
757
        """Escaped names are easily unescaped by urlutils."""
758
        return urllib.unquote(basename)
759
760
761
def make_versioned_files_factory(versioned_file_factory, mapper):
762
    """Create a ThunkedVersionedFiles factory.
763
764
    This will create a callable which when called creates a
765
    ThunkedVersionedFiles on a transport, using mapper to access individual
766
    versioned files, and versioned_file_factory to create each individual file.
767
    """
768
    def factory(transport):
769
        return ThunkedVersionedFiles(transport, versioned_file_factory, mapper,
770
            lambda:True)
771
    return factory
772
773
774
class VersionedFiles(object):
775
    """Storage for many versioned files.
776
777
    This object allows a single keyspace for accessing the history graph and
778
    contents of named bytestrings.
779
780
    Currently no implementation allows the graph of different key prefixes to
781
    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.
782
783
    The keyspace is expressed via simple tuples. Any instance of VersionedFiles
784
    may have a different length key-size, but that size will be constant for
785
    all texts added to or retrieved from it. For instance, bzrlib uses
786
    instances with a key-size of 2 for storing user files in a repository, with
787
    the first element the fileid, and the second the version of that file.
788
789
    The use of tuples allows a single code base to support several different
790
    uses with only the mapping logic changing from instance to instance.
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.
791
    """
792
793
    def add_lines(self, key, parents, lines, parent_texts=None,
794
        left_matching_blocks=None, nostore_sha=None, random_id=False,
795
        check_content=True):
796
        """Add a text to the store.
797
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
798
        :param key: The key tuple of the text to add. If the last element is
799
            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.
800
        :param parents: The parents key tuples of the text to add.
801
        :param lines: A list of lines. Each line must be a bytestring. And all
802
            of them except the last must be terminated with \n and contain no
803
            other \n's. The last line may either contain no \n's or a single
804
            terminating \n. If the lines list does meet this constraint the add
805
            routine may error or may succeed - but you will be unable to read
806
            the data back accurately. (Checking the lines have been split
807
            correctly is expensive and extremely unlikely to catch bugs so it
808
            is not done at runtime unless check_content is True.)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
809
        :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.
810
            representations of some or all of the parents of version_id to
811
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
812
            returned by add_lines or data corruption can be caused.
813
        :param left_matching_blocks: a hint about which areas are common
814
            between the text and its left-hand-parent.  The format is
815
            the SequenceMatcher.get_matching_blocks format.
816
        :param nostore_sha: Raise ExistingContent and do not add the lines to
817
            the versioned file if the digest of the lines matches this.
818
        :param random_id: If True a random id has been selected rather than
819
            an id determined by some deterministic process such as a converter
820
            from a foreign VCS. When True the backend may choose not to check
821
            for uniqueness of the resulting key within the versioned file, so
822
            this should only be done when the result is expected to be unique
823
            anyway.
824
        :param check_content: If True, the lines supplied are verified to be
825
            bytestrings that are correctly formed lines.
826
        :return: The text sha1, the number of bytes in the text, and an opaque
827
                 representation of the inserted version which can be provided
828
                 back to future add_lines calls in the parent_texts dictionary.
829
        """
830
        raise NotImplementedError(self.add_lines)
831
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
832
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
833
        """Add a text to the store.
834
835
        This is a private function for use by CommitBuilder.
836
837
        :param key: The key tuple of the text to add. If the last element is
838
            None, a CHK string will be generated during the addition.
839
        :param parents: The parents key tuples of the text to add.
840
        :param text: A string containing the text to be committed.
841
        :param nostore_sha: Raise ExistingContent and do not add the lines to
842
            the versioned file if the digest of the lines matches this.
843
        :param random_id: If True a random id has been selected rather than
844
            an id determined by some deterministic process such as a converter
845
            from a foreign VCS. When True the backend may choose not to check
846
            for uniqueness of the resulting key within the versioned file, so
847
            this should only be done when the result is expected to be unique
848
            anyway.
849
        :param check_content: If True, the lines supplied are verified to be
850
            bytestrings that are correctly formed lines.
851
        :return: The text sha1, the number of bytes in the text, and an opaque
852
                 representation of the inserted version which can be provided
853
                 back to future _add_text calls in the parent_texts dictionary.
854
        """
855
        # The default implementation just thunks over to .add_lines(),
856
        # inefficient, but it works.
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
857
        return self.add_lines(key, parents, osutils.split_lines(text),
858
                              nostore_sha=nostore_sha,
859
                              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'.
860
                              check_content=True)
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
861
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.
862
    def add_mpdiffs(self, records):
863
        """Add mpdiffs to this VersionedFile.
864
865
        Records should be iterables of version, parents, expected_sha1,
866
        mpdiff. mpdiff should be a MultiParent instance.
867
        """
868
        vf_parents = {}
869
        mpvf = multiparent.MultiMemoryVersionedFile()
870
        versions = []
871
        for version, parent_ids, expected_sha1, mpdiff in records:
872
            versions.append(version)
873
            mpvf.add_diff(mpdiff, version, parent_ids)
874
        needed_parents = set()
875
        for version, parent_ids, expected_sha1, mpdiff in records:
876
            needed_parents.update(p for p in parent_ids
877
                                  if not mpvf.has_version(p))
878
        # It seems likely that adding all the present parents as fulltexts can
879
        # easily exhaust memory.
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
880
        chunks_to_lines = osutils.chunks_to_lines
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
881
        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.
882
            True):
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
883
            if record.storage_kind == 'absent':
884
                continue
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
885
            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.
886
                record.key, [])
887
        for (key, parent_keys, expected_sha1, mpdiff), lines in\
888
            zip(records, mpvf.get_line_list(versions)):
889
            if len(parent_keys) == 1:
890
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
891
                    mpvf.get_diff(parent_keys[0]).num_lines()))
892
            else:
893
                left_matching_blocks = None
894
            version_sha1, _, version_text = self.add_lines(key,
895
                parent_keys, lines, vf_parents,
896
                left_matching_blocks=left_matching_blocks)
897
            if version_sha1 != expected_sha1:
898
                raise errors.VersionedFileInvalidChecksum(version)
899
            vf_parents[key] = version_text
900
901
    def annotate(self, key):
902
        """Return a list of (version-key, line) tuples for the text of key.
903
904
        :raise RevisionNotPresent: If the key is not present.
905
        """
906
        raise NotImplementedError(self.annotate)
907
908
    def check(self, progress_bar=None):
909
        """Check this object for integrity."""
910
        raise NotImplementedError(self.check)
911
912
    @staticmethod
913
    def check_not_reserved_id(version_id):
914
        revision.check_not_reserved_id(version_id)
915
916
    def _check_lines_not_unicode(self, lines):
917
        """Check that lines being added to a versioned file are not unicode."""
918
        for line in lines:
919
            if line.__class__ is not str:
920
                raise errors.BzrBadParameterUnicode("lines")
921
922
    def _check_lines_are_lines(self, lines):
923
        """Check that the lines really are full lines without inline EOL."""
924
        for line in lines:
925
            if '\n' in line[:-1]:
926
                raise errors.BzrBadParameterContainsNewline("lines")
927
928
    def get_parent_map(self, keys):
929
        """Get a map of the parents of keys.
930
931
        :param keys: The keys to look up parents for.
932
        :return: A mapping from keys to parents. Absent keys are absent from
933
            the mapping.
934
        """
935
        raise NotImplementedError(self.get_parent_map)
936
937
    def get_record_stream(self, keys, ordering, include_delta_closure):
938
        """Get a stream of records for keys.
939
940
        :param keys: The keys to include.
941
        :param ordering: Either 'unordered' or 'topological'. A topologically
942
            sorted stream has compression parents strictly before their
943
            children.
944
        :param include_delta_closure: If True then the closure across any
945
            compression parents will be included (in the opaque data).
946
        :return: An iterator of ContentFactory objects, each of which is only
947
            valid until the iterator is advanced.
948
        """
949
        raise NotImplementedError(self.get_record_stream)
950
951
    def get_sha1s(self, keys):
952
        """Get the sha1's of the texts for the given keys.
953
954
        :param keys: The names of the keys to lookup
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
955
        :return: a dict from key to sha1 digest. Keys of texts which are not
3350.8.14 by Robert Collins
Review feedback.
956
            present in the store are not present in the returned
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
957
            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.
958
        """
959
        raise NotImplementedError(self.get_sha1s)
960
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
961
    has_key = index._has_key_from_parent_map
962
4009.3.3 by Andrew Bennetts
Add docstrings.
963
    def get_missing_compression_parent_keys(self):
964
        """Return an iterable of keys of missing compression parents.
965
966
        Check this after calling insert_record_stream to find out if there are
967
        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.
968
        depend on them are not able to be inserted safely. The precise
969
        behaviour depends on the concrete VersionedFiles class in use.
970
971
        Classes that do not support this will raise NotImplementedError.
4009.3.3 by Andrew Bennetts
Add docstrings.
972
        """
973
        raise NotImplementedError(self.get_missing_compression_parent_keys)
974
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.
975
    def insert_record_stream(self, stream):
976
        """Insert a record stream into this container.
977
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
978
        :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.
979
        :return: None
980
        :seealso VersionedFile.get_record_stream:
981
        """
982
        raise NotImplementedError
983
984
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
985
        """Iterate over the lines in the versioned files from keys.
986
987
        This may return lines from other keys. Each item the returned
988
        iterator yields is a tuple of a line and a text version that that line
989
        is present in (not introduced in).
990
991
        Ordering of results is in whatever order is most suitable for the
992
        underlying storage format.
993
994
        If a progress bar is supplied, it may be used to indicate progress.
995
        The caller is responsible for cleaning up progress bars (because this
996
        is an iterator).
997
998
        NOTES:
999
         * Lines are normalised by the underlying store: they will all have \n
1000
           terminators.
1001
         * Lines are returned in arbitrary order.
1002
1003
        :return: An iterator over (line, key).
1004
        """
1005
        raise NotImplementedError(self.iter_lines_added_or_present_in_keys)
1006
1007
    def keys(self):
1008
        """Return a iterable of the keys for all the contained texts."""
1009
        raise NotImplementedError(self.keys)
1010
1011
    def make_mpdiffs(self, keys):
1012
        """Create multiparent diffs for specified keys."""
1013
        keys_order = tuple(keys)
1014
        keys = frozenset(keys)
1015
        knit_keys = set(keys)
1016
        parent_map = self.get_parent_map(keys)
1017
        for parent_keys in parent_map.itervalues():
1018
            if parent_keys:
1019
                knit_keys.update(parent_keys)
1020
        missing_keys = keys - set(parent_map)
1021
        if missing_keys:
3530.3.2 by Robert Collins
Handling frozen set inputs in mpdiff generation when a key is missing
1022
            raise errors.RevisionNotPresent(list(missing_keys)[0], 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.
1023
        # We need to filter out ghosts, because we can't diff against them.
1024
        maybe_ghosts = knit_keys - keys
1025
        ghosts = maybe_ghosts - set(self.get_parent_map(maybe_ghosts))
1026
        knit_keys.difference_update(ghosts)
1027
        lines = {}
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
1028
        chunks_to_lines = osutils.chunks_to_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.
1029
        for record in self.get_record_stream(knit_keys, 'topological', True):
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
1030
            lines[record.key] = 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
            # line_block_dict = {}
1032
            # for parent, blocks in record.extract_line_blocks():
1033
            #   line_blocks[parent] = blocks
1034
            # line_blocks[record.key] = line_block_dict
1035
        diffs = []
1036
        for key in keys_order:
1037
            target = lines[key]
1038
            parents = parent_map[key] or []
1039
            # Note that filtering knit_keys can lead to a parent difference
1040
            # between the creation and the application of the mpdiff.
1041
            parent_lines = [lines[p] for p in parents if p in knit_keys]
1042
            if len(parent_lines) > 0:
1043
                left_parent_blocks = self._extract_blocks(key, parent_lines[0],
1044
                    target)
1045
            else:
1046
                left_parent_blocks = None
1047
            diffs.append(multiparent.MultiParent.from_lines(target,
1048
                parent_lines, left_parent_blocks))
1049
        return diffs
1050
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
1051
    missing_keys = index._missing_keys_from_parent_map
1052
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.
1053
    def _extract_blocks(self, version_id, source, target):
1054
        return None
1055
1056
1057
class ThunkedVersionedFiles(VersionedFiles):
1058
    """Storage for many versioned files thunked onto a 'VersionedFile' class.
1059
1060
    This object allows a single keyspace for accessing the history graph and
1061
    contents of named bytestrings.
1062
1063
    Currently no implementation allows the graph of different key prefixes to
1064
    intersect, but the API does allow such implementations in the future.
1065
    """
1066
1067
    def __init__(self, transport, file_factory, mapper, is_locked):
1068
        """Create a ThunkedVersionedFiles."""
1069
        self._transport = transport
1070
        self._file_factory = file_factory
1071
        self._mapper = mapper
1072
        self._is_locked = is_locked
1073
1074
    def add_lines(self, key, parents, lines, parent_texts=None,
1075
        left_matching_blocks=None, nostore_sha=None, random_id=False,
1076
        check_content=True):
1077
        """See VersionedFiles.add_lines()."""
1078
        path = self._mapper.map(key)
1079
        version_id = key[-1]
1080
        parents = [parent[-1] for parent in parents]
1081
        vf = self._get_vf(path)
1082
        try:
1083
            try:
1084
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1085
                    parent_texts=parent_texts,
1086
                    left_matching_blocks=left_matching_blocks,
1087
                    nostore_sha=nostore_sha, random_id=random_id,
1088
                    check_content=check_content)
1089
            except NotImplementedError:
1090
                return vf.add_lines(version_id, parents, lines,
1091
                    parent_texts=parent_texts,
1092
                    left_matching_blocks=left_matching_blocks,
1093
                    nostore_sha=nostore_sha, random_id=random_id,
1094
                    check_content=check_content)
1095
        except errors.NoSuchFile:
1096
            # parent directory may be missing, try again.
1097
            self._transport.mkdir(osutils.dirname(path))
1098
            try:
1099
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1100
                    parent_texts=parent_texts,
1101
                    left_matching_blocks=left_matching_blocks,
1102
                    nostore_sha=nostore_sha, random_id=random_id,
1103
                    check_content=check_content)
1104
            except NotImplementedError:
1105
                return vf.add_lines(version_id, parents, lines,
1106
                    parent_texts=parent_texts,
1107
                    left_matching_blocks=left_matching_blocks,
1108
                    nostore_sha=nostore_sha, random_id=random_id,
1109
                    check_content=check_content)
1110
1111
    def annotate(self, key):
1112
        """Return a list of (version-key, line) tuples for the text of key.
1113
1114
        :raise RevisionNotPresent: If the key is not present.
1115
        """
1116
        prefix = key[:-1]
1117
        path = self._mapper.map(prefix)
1118
        vf = self._get_vf(path)
1119
        origins = vf.annotate(key[-1])
1120
        result = []
1121
        for origin, line in origins:
1122
            result.append((prefix + (origin,), line))
1123
        return result
1124
1125
    def check(self, progress_bar=None):
1126
        """See VersionedFiles.check()."""
1127
        for prefix, vf in self._iter_all_components():
1128
            vf.check()
1129
1130
    def get_parent_map(self, keys):
1131
        """Get a map of the parents of keys.
1132
1133
        :param keys: The keys to look up parents for.
1134
        :return: A mapping from keys to parents. Absent keys are absent from
1135
            the mapping.
1136
        """
1137
        prefixes = self._partition_keys(keys)
1138
        result = {}
1139
        for prefix, suffixes in prefixes.items():
1140
            path = self._mapper.map(prefix)
1141
            vf = self._get_vf(path)
1142
            parent_map = vf.get_parent_map(suffixes)
1143
            for key, parents in parent_map.items():
1144
                result[prefix + (key,)] = tuple(
1145
                    prefix + (parent,) for parent in parents)
1146
        return result
1147
1148
    def _get_vf(self, path):
1149
        if not self._is_locked():
1150
            raise errors.ObjectNotLocked(self)
1151
        return self._file_factory(path, self._transport, create=True,
1152
            get_scope=lambda:None)
1153
1154
    def _partition_keys(self, keys):
1155
        """Turn keys into a dict of prefix:suffix_list."""
1156
        result = {}
1157
        for key in keys:
1158
            prefix_keys = result.setdefault(key[:-1], [])
1159
            prefix_keys.append(key[-1])
1160
        return result
1161
1162
    def _get_all_prefixes(self):
1163
        # Identify all key prefixes.
1164
        # XXX: A bit hacky, needs polish.
1165
        if type(self._mapper) == ConstantMapper:
1166
            paths = [self._mapper.map(())]
1167
            prefixes = [()]
1168
        else:
1169
            relpaths = set()
1170
            for quoted_relpath in self._transport.iter_files_recursive():
1171
                path, ext = os.path.splitext(quoted_relpath)
1172
                relpaths.add(path)
1173
            paths = list(relpaths)
1174
            prefixes = [self._mapper.unmap(path) for path in paths]
1175
        return zip(paths, prefixes)
1176
1177
    def get_record_stream(self, keys, ordering, include_delta_closure):
1178
        """See VersionedFiles.get_record_stream()."""
1179
        # Ordering will be taken care of by each partitioned store; group keys
1180
        # by partition.
1181
        keys = sorted(keys)
1182
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1183
            suffixes = [(suffix,) for suffix in suffixes]
1184
            for record in vf.get_record_stream(suffixes, ordering,
1185
                include_delta_closure):
1186
                if record.parents is not None:
1187
                    record.parents = tuple(
1188
                        prefix + parent for parent in record.parents)
1189
                record.key = prefix + record.key
1190
                yield record
1191
1192
    def _iter_keys_vf(self, keys):
1193
        prefixes = self._partition_keys(keys)
1194
        sha1s = {}
1195
        for prefix, suffixes in prefixes.items():
1196
            path = self._mapper.map(prefix)
1197
            vf = self._get_vf(path)
1198
            yield prefix, suffixes, vf
1199
1200
    def get_sha1s(self, keys):
1201
        """See VersionedFiles.get_sha1s()."""
1202
        sha1s = {}
1203
        for prefix,suffixes, vf in self._iter_keys_vf(keys):
1204
            vf_sha1s = vf.get_sha1s(suffixes)
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1205
            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.
1206
                sha1s[prefix + (suffix,)] = sha1
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1207
        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.
1208
1209
    def insert_record_stream(self, stream):
1210
        """Insert a record stream into this container.
1211
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1212
        :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.
1213
        :return: None
1214
        :seealso VersionedFile.get_record_stream:
1215
        """
1216
        for record in stream:
1217
            prefix = record.key[:-1]
1218
            key = record.key[-1:]
1219
            if record.parents is not None:
1220
                parents = [parent[-1:] for parent in record.parents]
1221
            else:
1222
                parents = None
1223
            thunk_record = AdapterFactory(key, parents, record)
1224
            path = self._mapper.map(prefix)
1225
            # Note that this parses the file many times; we can do better but
1226
            # as this only impacts weaves in terms of performance, it is
1227
            # tolerable.
1228
            vf = self._get_vf(path)
1229
            vf.insert_record_stream([thunk_record])
1230
1231
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1232
        """Iterate over the lines in the versioned files from keys.
1233
1234
        This may return lines from other keys. Each item the returned
1235
        iterator yields is a tuple of a line and a text version that that line
1236
        is present in (not introduced in).
1237
1238
        Ordering of results is in whatever order is most suitable for the
1239
        underlying storage format.
1240
1241
        If a progress bar is supplied, it may be used to indicate progress.
1242
        The caller is responsible for cleaning up progress bars (because this
1243
        is an iterator).
1244
1245
        NOTES:
1246
         * Lines are normalised by the underlying store: they will all have \n
1247
           terminators.
1248
         * Lines are returned in arbitrary order.
1249
1250
        :return: An iterator over (line, key).
1251
        """
1252
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1253
            for line, version in vf.iter_lines_added_or_present_in_versions(suffixes):
1254
                yield line, prefix + (version,)
1255
1256
    def _iter_all_components(self):
1257
        for path, prefix in self._get_all_prefixes():
1258
            yield prefix, self._get_vf(path)
1259
1260
    def keys(self):
1261
        """See VersionedFiles.keys()."""
1262
        result = set()
1263
        for prefix, vf in self._iter_all_components():
1264
            for suffix in vf.versions():
1265
                result.add(prefix + (suffix,))
1266
        return result
1267
1268
1269
class _PlanMergeVersionedFile(VersionedFiles):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1270
    """A VersionedFile for uncommitted and committed texts.
1271
1272
    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.
1273
    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
1274
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
1275
    _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.
1276
1277
    :ivar: fallback_versionedfiles a list of VersionedFiles objects that can be
1278
        queried for missing texts.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1279
    """
1280
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.
1281
    def __init__(self, file_id):
1282
        """Create a _PlanMergeVersionedFile.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1283
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.
1284
        :param file_id: Used with _PlanMerge code which is not yet fully
1285
            tuple-keyspace aware.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1286
        """
1287
        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.
1288
        # fallback locations
1289
        self.fallback_versionedfiles = []
1290
        # Parents for locally held keys.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1291
        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.
1292
        # line data for locally held keys.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1293
        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.
1294
        # key lookup providers
1295
        self._providers = [DictParentsProvider(self._parents)]
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1296
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1297
    def plan_merge(self, ver_a, ver_b, base=None):
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
1298
        """See VersionedFile.plan_merge"""
3144.3.7 by Aaron Bentley
Update from review
1299
        from bzrlib.merge import _PlanMerge
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1300
        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.
1301
            return _PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge()
1302
        old_plan = list(_PlanMerge(ver_a, base, self, (self._file_id,)).plan_merge())
1303
        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
1304
        return _PlanMerge._subtract_plans(old_plan, new_plan)
1305
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1306
    def plan_lca_merge(self, ver_a, ver_b, base=None):
3144.3.7 by Aaron Bentley
Update from review
1307
        from bzrlib.merge import _PlanLCAMerge
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.
1308
        graph = Graph(self)
1309
        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
1310
        if base is None:
1311
            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.
1312
        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
1313
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
1314
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.
1315
    def add_lines(self, key, parents, lines):
1316
        """See VersionedFiles.add_lines
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1317
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.
1318
        Lines are added locally, not to fallback versionedfiles.  Also, ghosts
1319
        are permitted.  Only reserved ids are permitted.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1320
        """
3350.6.8 by Martin Pool
Change stray pdb calls to exceptions
1321
        if type(key) is not tuple:
1322
            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.
1323
        if not revision.is_reserved_id(key[-1]):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1324
            raise ValueError('Only reserved ids may be used')
1325
        if parents is None:
1326
            raise ValueError('Parents may not be None')
1327
        if lines is None:
1328
            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.
1329
        self._parents[key] = tuple(parents)
1330
        self._lines[key] = lines
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1331
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.
1332
    def get_record_stream(self, keys, ordering, include_delta_closure):
1333
        pending = set(keys)
1334
        for key in keys:
1335
            if key in self._lines:
1336
                lines = self._lines[key]
1337
                parents = self._parents[key]
1338
                pending.remove(key)
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1339
                yield ChunkedContentFactory(key, parents, None, lines)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1340
        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.
1341
            for record in versionedfile.get_record_stream(
1342
                pending, 'unordered', True):
1343
                if record.storage_kind == 'absent':
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1344
                    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.
1345
                else:
1346
                    pending.remove(record.key)
1347
                    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.
1348
            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.
1349
                return
1350
        # report absent entries
1351
        for key in pending:
1352
            yield AbsentContentFactory(key)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1353
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.
1354
    def get_parent_map(self, keys):
1355
        """See VersionedFiles.get_parent_map"""
1356
        # We create a new provider because a fallback may have been added.
1357
        # If we make fallbacks private we can update a stack list and avoid
1358
        # object creation thrashing.
3350.6.6 by Robert Collins
Fix test_plan_file_merge
1359
        keys = set(keys)
1360
        result = {}
1361
        if revision.NULL_REVISION in keys:
1362
            keys.remove(revision.NULL_REVISION)
1363
            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.
1364
        self._providers = self._providers[:1] + self.fallback_versionedfiles
3350.6.6 by Robert Collins
Fix test_plan_file_merge
1365
        result.update(
4379.3.3 by Gary van der Merwe
Rename and add doc string for StackedParentsProvider.
1366
            StackedParentsProvider(self._providers).get_parent_map(keys))
3350.6.5 by Robert Collins
Update to bzr.dev.
1367
        for key, parents in result.iteritems():
1368
            if parents == ():
1369
                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.
1370
        return result
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1371
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1372
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1373
class PlanWeaveMerge(TextMerge):
1551.6.13 by Aaron Bentley
Cleanup
1374
    """Weave merge that takes a plan as its input.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1375
1551.6.14 by Aaron Bentley
Tweaks from merge review
1376
    This exists so that VersionedFile.plan_merge is implementable.
1377
    Most callers will want to use WeaveMerge instead.
1551.6.13 by Aaron Bentley
Cleanup
1378
    """
1379
1551.6.14 by Aaron Bentley
Tweaks from merge review
1380
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
1381
                 b_marker=TextMerge.B_MARKER):
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1382
        TextMerge.__init__(self, a_marker, b_marker)
1383
        self.plan = plan
1384
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
1385
    def _merge_struct(self):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1386
        lines_a = []
1387
        lines_b = []
1388
        ch_a = ch_b = False
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1389
1390
        def outstanding_struct():
1391
            if not lines_a and not lines_b:
1392
                return
1393
            elif ch_a and not ch_b:
1394
                # one-sided change:
1395
                yield(lines_a,)
1396
            elif ch_b and not ch_a:
1397
                yield (lines_b,)
1398
            elif lines_a == lines_b:
1399
                yield(lines_a,)
1400
            else:
1401
                yield (lines_a, lines_b)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1402
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
1403
        # We previously considered either 'unchanged' or 'killed-both' lines
1404
        # to be possible places to resynchronize.  However, assuming agreement
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1405
        # on killed-both lines may be too aggressive. -- mbp 20060324
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
1406
        for state, line in self.plan:
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
1407
            if state == 'unchanged':
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1408
                # resync and flush queued conflicts changes if any
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1409
                for struct in outstanding_struct():
1410
                    yield struct
1551.6.11 by Aaron Bentley
Switched TextMerge_lines to work on a list
1411
                lines_a = []
1412
                lines_b = []
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1413
                ch_a = ch_b = False
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1414
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1415
            if state == 'unchanged':
1416
                if line:
1551.6.5 by Aaron Bentley
Got weave merge producing structural output
1417
                    yield ([line],)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1418
            elif state == 'killed-a':
1419
                ch_a = True
1420
                lines_b.append(line)
1421
            elif state == 'killed-b':
1422
                ch_b = True
1423
                lines_a.append(line)
1424
            elif state == 'new-a':
1425
                ch_a = True
1426
                lines_a.append(line)
1427
            elif state == 'new-b':
1428
                ch_b = True
1429
                lines_b.append(line)
3144.3.2 by Aaron Bentley
Get conflict handling working
1430
            elif state == 'conflicted-a':
1431
                ch_b = ch_a = True
1432
                lines_a.append(line)
1433
            elif state == 'conflicted-b':
1434
                ch_b = ch_a = True
1435
                lines_b.append(line)
4312.1.1 by John Arbash Meinel
Add a per-implementation test that deleting lines conflicts with modifying lines.
1436
            elif state == 'killed-both':
1437
                # This counts as a change, even though there is no associated
1438
                # line
1439
                ch_b = ch_a = True
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1440
            else:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1441
                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.
1442
                        'killed-base'):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1443
                    raise AssertionError(state)
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1444
        for struct in outstanding_struct():
1445
            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.
1446
1664.2.14 by Aaron Bentley
spacing fix
1447
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1448
class WeaveMerge(PlanWeaveMerge):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
1449
    """Weave merge that takes a VersionedFile and two versions as its input."""
1551.6.13 by Aaron Bentley
Cleanup
1450
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1451
    def __init__(self, versionedfile, ver_a, ver_b,
1551.6.14 by Aaron Bentley
Tweaks from merge review
1452
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
1453
        plan = versionedfile.plan_merge(ver_a, ver_b)
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1454
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
1455
1456
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1457
class VirtualVersionedFiles(VersionedFiles):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1458
    """Dummy implementation for VersionedFiles that uses other functions for
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1459
    obtaining fulltexts and parent maps.
1460
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1461
    This is always on the bottom of the stack and uses string keys
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1462
    (rather than tuples) internally.
1463
    """
1464
1465
    def __init__(self, get_parent_map, get_lines):
1466
        """Create a VirtualVersionedFiles.
1467
1468
        :param get_parent_map: Same signature as Repository.get_parent_map.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1469
        :param get_lines: Should return lines for specified key or None if
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1470
                          not available.
1471
        """
1472
        super(VirtualVersionedFiles, self).__init__()
1473
        self._get_parent_map = get_parent_map
1474
        self._get_lines = get_lines
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1475
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1476
    def check(self, progressbar=None):
1477
        """See VersionedFiles.check.
1478
1479
        :note: Always returns True for VirtualVersionedFiles.
1480
        """
1481
        return True
1482
1483
    def add_mpdiffs(self, records):
1484
        """See VersionedFiles.mpdiffs.
1485
1486
        :note: Not implemented for VirtualVersionedFiles.
1487
        """
1488
        raise NotImplementedError(self.add_mpdiffs)
1489
1490
    def get_parent_map(self, keys):
1491
        """See VersionedFiles.get_parent_map."""
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1492
        return dict([((k,), tuple([(p,) for p in v]))
1493
            for k,v in self._get_parent_map([k for (k,) in keys]).iteritems()])
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1494
1495
    def get_sha1s(self, keys):
1496
        """See VersionedFiles.get_sha1s."""
1497
        ret = {}
1498
        for (k,) in keys:
1499
            lines = self._get_lines(k)
1500
            if lines is not None:
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1501
                if not isinstance(lines, list):
1502
                    raise AssertionError
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1503
                ret[(k,)] = osutils.sha_strings(lines)
1504
        return ret
1505
1506
    def get_record_stream(self, keys, ordering, include_delta_closure):
1507
        """See VersionedFiles.get_record_stream."""
1508
        for (k,) in list(keys):
1509
            lines = self._get_lines(k)
1510
            if lines is not None:
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1511
                if not isinstance(lines, list):
1512
                    raise AssertionError
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1513
                yield ChunkedContentFactory((k,), None,
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1514
                        sha1=osutils.sha_strings(lines),
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1515
                        chunks=lines)
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1516
            else:
1517
                yield AbsentContentFactory((k,))
1518
3949.4.1 by Jelmer Vernooij
Implement VirtualVersionedFiles.iter_lines_added_or_present_in_keys.
1519
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1520
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
1521
        for i, (key,) in enumerate(keys):
1522
            if pb is not None:
4110.2.10 by Martin Pool
Tweak iter_lines progress messages
1523
                pb.update("Finding changed lines", i, len(keys))
3949.4.1 by Jelmer Vernooij
Implement VirtualVersionedFiles.iter_lines_added_or_present_in_keys.
1524
            for l in self._get_lines(key):
1525
                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.
1526
1527
1528
def network_bytes_to_kind_and_offset(network_bytes):
1529
    """Strip of a record kind from the front of network_bytes.
1530
1531
    :param network_bytes: The bytes of a record.
1532
    :return: A tuple (storage_kind, offset_of_remaining_bytes)
1533
    """
1534
    line_end = network_bytes.find('\n')
1535
    storage_kind = network_bytes[:line_end]
1536
    return storage_kind, line_end + 1
1537
1538
1539
class NetworkRecordStream(object):
1540
    """A record_stream which reconstitures a serialised stream."""
1541
1542
    def __init__(self, bytes_iterator):
1543
        """Create a NetworkRecordStream.
1544
1545
        :param bytes_iterator: An iterator of bytes. Each item in this
1546
            iterator should have been obtained from a record_streams'
1547
            record.get_bytes_as(record.storage_kind) call.
1548
        """
1549
        self._bytes_iterator = bytes_iterator
1550
        self._kind_factory = {'knit-ft-gz':knit.knit_network_to_record,
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
1551
            'knit-delta-gz':knit.knit_network_to_record,
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.
1552
            'knit-annotated-ft-gz':knit.knit_network_to_record,
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
1553
            'knit-annotated-delta-gz':knit.knit_network_to_record,
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.
1554
            'knit-delta-closure':knit.knit_delta_closure_to_records,
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1555
            'fulltext':fulltext_network_to_record,
3735.32.18 by John Arbash Meinel
We now support generating a network stream.
1556
            'groupcompress-block':groupcompress.network_block_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.
1557
            }
1558
1559
    def read(self):
1560
        """Read the stream.
1561
1562
        :return: An iterator as per VersionedFiles.get_record_stream().
1563
        """
1564
        for bytes in self._bytes_iterator:
1565
            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.
1566
            for record in self._kind_factory[storage_kind](
1567
                storage_kind, bytes, line_end):
1568
                yield record
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1569
1570
1571
def fulltext_network_to_record(kind, bytes, line_end):
1572
    """Convert a network fulltext record to record."""
1573
    meta_len, = struct.unpack('!L', bytes[line_end:line_end+4])
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1574
    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.
1575
    key, parents = bencode.bdecode_as_tuple(record_meta)
1576
    if parents == 'nil':
1577
        parents = None
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1578
    fulltext = bytes[line_end+4+meta_len:]
1579
    return [FulltextContentFactory(key, parents, None, fulltext)]
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1580
1581
1582
def _length_prefix(bytes):
1583
    return struct.pack('!L', len(bytes))
1584
1585
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1586
def record_to_fulltext_bytes(record):
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1587
    if record.parents is None:
1588
        parents = 'nil'
1589
    else:
1590
        parents = record.parents
1591
    record_meta = bencode.bencode((record.key, parents))
1592
    record_content = record.get_bytes_as('fulltext')
1593
    return "fulltext\n%s%s%s" % (
1594
        _length_prefix(record_meta), record_meta, record_content)
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1595
1596
1597
def sort_groupcompress(parent_map):
1598
    """Sort and group the keys in parent_map into groupcompress order.
1599
1600
    groupcompress is defined (currently) as reverse-topological order, grouped
1601
    by the key prefix.
1602
1603
    :return: A sorted-list of keys
1604
    """
1605
    # gc-optimal ordering is approximately reverse topological,
1606
    # properly grouped by file-id.
1607
    per_prefix_map = {}
1608
    for item in parent_map.iteritems():
1609
        key = item[0]
1610
        if isinstance(key, str) or len(key) == 1:
1611
            prefix = ''
1612
        else:
1613
            prefix = key[0]
1614
        try:
1615
            per_prefix_map[prefix].append(item)
1616
        except KeyError:
1617
            per_prefix_map[prefix] = [item]
1618
1619
    present_keys = []
1620
    for prefix in sorted(per_prefix_map):
1621
        present_keys.extend(reversed(tsort.topo_sort(per_prefix_map[prefix])))
1622
    return present_keys