/brz/remove-bazaar

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