/brz/remove-bazaar

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