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