/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5652.2.2 by Martin Pool
Rename _fallback_vfs to _immediate_fallbacks
1
# Copyright (C) 2006-2011 Canonical Ltd
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
16
17
"""Versioned text file storage api."""
18
3350.8.2 by Robert Collins
stacked get_parent_map.
19
from copy import copy
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
20
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.
21
import os
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
22
import struct
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
23
from zlib import adler32
24
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
25
from bzrlib.lazy_import import lazy_import
26
lazy_import(globals(), """
27
from bzrlib import (
4454.3.65 by John Arbash Meinel
Tests that VF implementations support .get_annotator()
28
    annotate,
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
29
    bencode,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
30
    errors,
4593.5.36 by John Arbash Meinel
a few more implementations of the interface.
31
    graph as _mod_graph,
3735.32.18 by John Arbash Meinel
We now support generating a network stream.
32
    groupcompress,
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
33
    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.
34
    knit,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
35
    osutils,
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
36
    multiparent,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
37
    tsort,
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
38
    revision,
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
39
    urlutils,
1996.3.7 by John Arbash Meinel
lazy import versionedfile, late-load bzrlib.merge
40
    )
41
""")
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
42
from bzrlib.registry import Registry
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
43
from bzrlib.textmerge import TextMerge
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
44
45
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
46
adapter_registry = Registry()
47
adapter_registry.register_lazy(('knit-delta-gz', 'fulltext'), 'bzrlib.knit',
48
    'DeltaPlainToFullText')
49
adapter_registry.register_lazy(('knit-ft-gz', 'fulltext'), 'bzrlib.knit',
50
    'FTPlainToFullText')
51
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'knit-delta-gz'),
52
    'bzrlib.knit', 'DeltaAnnotatedToUnannotated')
53
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'fulltext'),
54
    'bzrlib.knit', 'DeltaAnnotatedToFullText')
55
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'knit-ft-gz'),
56
    'bzrlib.knit', 'FTAnnotatedToUnannotated')
57
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'fulltext'),
58
    'bzrlib.knit', 'FTAnnotatedToFullText')
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
59
# adapter_registry.register_lazy(('knit-annotated-ft-gz', 'chunked'),
60
#     'bzrlib.knit', 'FTAnnotatedToChunked')
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
61
62
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
63
class ContentFactory(object):
64
    """Abstract interface for insertion and retrieval from a VersionedFile.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
65
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
66
    :ivar sha1: None, or the sha1 of the content fulltext.
67
    :ivar storage_kind: The native storage kind of this factory. One of
68
        'mpdiff', 'knit-annotated-ft', 'knit-annotated-delta', 'knit-ft',
69
        'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
70
        'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'.
71
    :ivar key: The key of this content. Each key is a tuple with a single
72
        string in it.
73
    :ivar parents: A tuple of parent keys for self.key. If the object has
74
        no parent information, None (as opposed to () for an empty list of
75
        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.
76
    """
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
77
78
    def __init__(self):
79
        """Create a ContentFactory."""
80
        self.sha1 = None
81
        self.storage_kind = None
82
        self.key = None
83
        self.parents = None
84
85
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
86
class ChunkedContentFactory(ContentFactory):
87
    """Static data content factory.
88
89
    This takes a 'chunked' list of strings. The only requirement on 'chunked' is
90
    that ''.join(lines) becomes a valid fulltext. A tuple of a single string
91
    satisfies this, as does a list of lines.
92
93
    :ivar sha1: None, or the sha1 of the content fulltext.
94
    :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'
95
        'chunked'
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
96
    :ivar key: The key of this content. Each key is a tuple with a single
97
        string in it.
98
    :ivar parents: A tuple of parent keys for self.key. If the object has
99
        no parent information, None (as opposed to () for an empty list of
100
        parents).
101
     """
102
103
    def __init__(self, key, parents, sha1, chunks):
104
        """Create a ContentFactory."""
105
        self.sha1 = sha1
3890.2.2 by John Arbash Meinel
Change the signature to report the storage kind as 'chunked'
106
        self.storage_kind = 'chunked'
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
107
        self.key = key
108
        self.parents = parents
109
        self._chunks = chunks
110
111
    def get_bytes_as(self, storage_kind):
112
        if storage_kind == 'chunked':
113
            return self._chunks
114
        elif storage_kind == 'fulltext':
115
            return ''.join(self._chunks)
116
        raise errors.UnavailableRepresentation(self.key, storage_kind,
117
            self.storage_kind)
118
119
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
120
class FulltextContentFactory(ContentFactory):
121
    """Static data content factory.
122
123
    This takes a fulltext when created and just returns that during
124
    get_bytes_as('fulltext').
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
125
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
126
    :ivar sha1: None, or the sha1 of the content fulltext.
127
    :ivar storage_kind: The native storage kind of this factory. Always
128
        'fulltext'.
129
    :ivar key: The key of this content. Each key is a tuple with a single
130
        string in it.
131
    :ivar parents: A tuple of parent keys for self.key. If the object has
132
        no parent information, None (as opposed to () for an empty list of
133
        parents).
134
     """
135
136
    def __init__(self, key, parents, sha1, text):
137
        """Create a ContentFactory."""
138
        self.sha1 = sha1
139
        self.storage_kind = 'fulltext'
140
        self.key = key
141
        self.parents = parents
142
        self._text = text
143
144
    def get_bytes_as(self, storage_kind):
145
        if storage_kind == self.storage_kind:
146
            return self._text
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
147
        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.
148
            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.
149
        raise errors.UnavailableRepresentation(self.key, storage_kind,
150
            self.storage_kind)
151
152
153
class AbsentContentFactory(ContentFactory):
3350.3.12 by Robert Collins
Generate streams with absent records.
154
    """A placeholder content factory for unavailable texts.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
155
3350.3.12 by Robert Collins
Generate streams with absent records.
156
    :ivar sha1: None.
157
    :ivar storage_kind: 'absent'.
158
    :ivar key: The key of this content. Each key is a tuple with a single
159
        string in it.
160
    :ivar parents: None.
161
    """
162
163
    def __init__(self, key):
164
        """Create a ContentFactory."""
165
        self.sha1 = None
166
        self.storage_kind = 'absent'
167
        self.key = key
168
        self.parents = None
169
4537.2.1 by John Arbash Meinel
Add AbsentContentFactory.get_bytes_as()
170
    def get_bytes_as(self, storage_kind):
171
        raise ValueError('A request was made for key: %s, but that'
172
                         ' content is not available, and the calling'
173
                         ' code does not handle if it is missing.'
174
                         % (self.key,))
175
3350.3.12 by Robert Collins
Generate streams with absent records.
176
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
177
class AdapterFactory(ContentFactory):
178
    """A content factory to adapt between key prefix's."""
179
180
    def __init__(self, key, parents, adapted):
181
        """Create an adapter factory instance."""
182
        self.key = key
183
        self.parents = parents
184
        self._adapted = adapted
185
186
    def __getattr__(self, attr):
187
        """Return a member from the adapted object."""
188
        if attr in ('key', 'parents'):
189
            return self.__dict__[attr]
190
        else:
191
            return getattr(self._adapted, attr)
192
193
3350.3.14 by Robert Collins
Deprecate VersionedFile.join.
194
def filter_absent(record_stream):
195
    """Adapt a record stream to remove absent records."""
196
    for record in record_stream:
197
        if record.storage_kind != 'absent':
198
            yield record
199
200
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
201
class _MPDiffGenerator(object):
202
    """Pull out the functionality for generating mp_diffs."""
203
204
    def __init__(self, vf, keys):
205
        self.vf = vf
206
        # This is the order the keys were requested in
207
        self.ordered_keys = tuple(keys)
208
        # keys + their parents, what we need to compute the diffs
209
        self.needed_keys = ()
210
        # Map from key: mp_diff
211
        self.diffs = {}
212
        # Map from key: parents_needed (may have ghosts)
213
        self.parent_map = {}
214
        # Parents that aren't present
215
        self.ghost_parents = ()
216
        # Map from parent_key => number of children for this text
217
        self.refcounts = {}
218
        # Content chunks that are cached while we still need them
219
        self.chunks = {}
220
221
    def _find_needed_keys(self):
222
        """Find the set of keys we need to request.
223
224
        This includes all the original keys passed in, and the non-ghost
225
        parents of those keys.
226
227
        :return: (needed_keys, refcounts)
228
            needed_keys is the set of all texts we need to extract
229
            refcounts is a dict of {key: num_children} letting us know when we
230
                no longer need to cache a given parent text
231
        """
232
        # All the keys and their parents
233
        needed_keys = set(self.ordered_keys)
234
        parent_map = self.vf.get_parent_map(needed_keys)
235
        self.parent_map = parent_map
236
        # TODO: Should we be using a different construct here? I think this
237
        #       uses difference_update internally, and we expect the result to
238
        #       be tiny
239
        missing_keys = needed_keys.difference(parent_map)
240
        if missing_keys:
241
            raise errors.RevisionNotPresent(list(missing_keys)[0], self.vf)
242
        # Parents that might be missing. They are allowed to be ghosts, but we
243
        # should check for them
244
        refcounts = {}
245
        setdefault = refcounts.setdefault
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
246
        just_parents = set()
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
247
        for child_key, parent_keys in parent_map.iteritems():
248
            if not parent_keys:
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
249
                # parent_keys may be None if a given VersionedFile claims to
250
                # not support graph operations.
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
251
                continue
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
252
            just_parents.update(parent_keys)
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
253
            needed_keys.update(parent_keys)
254
            for p in parent_keys:
255
                refcounts[p] = setdefault(p, 0) + 1
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
256
        just_parents.difference_update(parent_map)
257
        # Remove any parents that are actually ghosts from the needed set
258
        self.present_parents = set(self.vf.get_parent_map(just_parents))
259
        self.ghost_parents = just_parents.difference(self.present_parents)
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
260
        needed_keys.difference_update(self.ghost_parents)
261
        self.needed_keys = needed_keys
262
        self.refcounts = refcounts
263
        return needed_keys, refcounts
264
265
    def _compute_diff(self, key, parent_lines, lines):
266
        """Compute a single mp_diff, and store it in self._diffs"""
267
        if len(parent_lines) > 0:
268
            # XXX: _extract_blocks is not usefully defined anywhere...
269
            #      It was meant to extract the left-parent diff without
270
            #      having to recompute it for Knit content (pack-0.92,
271
            #      etc). That seems to have regressed somewhere
272
            left_parent_blocks = self.vf._extract_blocks(key,
273
                parent_lines[0], lines)
274
        else:
275
            left_parent_blocks = None
276
        diff = multiparent.MultiParent.from_lines(lines,
277
                    parent_lines, left_parent_blocks)
278
        self.diffs[key] = diff
279
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
280
    def _process_one_record(self, key, this_chunks):
281
        parent_keys = None
282
        if key in self.parent_map:
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
283
            # This record should be ready to diff, since we requested
284
            # content in 'topological' order
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
285
            parent_keys = self.parent_map.pop(key)
5374.2.3 by John Arbash Meinel
Replace the generic VersionedFiles.make_mpdiffs interface.
286
            # If a VersionedFile claims 'no-graph' support, then it may return
287
            # None for any parent request, so we replace it with an empty tuple
288
            if parent_keys is None:
289
                parent_keys = ()
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
290
            parent_lines = []
291
            for p in parent_keys:
292
                # Alternatively we could check p not in self.needed_keys, but
293
                # ghost_parents should be tiny versus huge
294
                if p in self.ghost_parents:
295
                    continue
296
                refcount = self.refcounts[p]
297
                if refcount == 1: # Last child reference
298
                    self.refcounts.pop(p)
299
                    parent_chunks = self.chunks.pop(p)
300
                else:
301
                    self.refcounts[p] = refcount - 1
302
                    parent_chunks = self.chunks[p]
5374.2.4 by John Arbash Meinel
Cache the lines as extracted if they are used right now.
303
                p_lines = osutils.chunks_to_lines(parent_chunks)
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
304
                # TODO: Should we cache the line form? We did the
305
                #       computation to get it, but storing it this way will
306
                #       be less memory efficient...
5374.2.4 by John Arbash Meinel
Cache the lines as extracted if they are used right now.
307
                parent_lines.append(p_lines)
308
                del p_lines
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
309
            lines = osutils.chunks_to_lines(this_chunks)
5374.2.4 by John Arbash Meinel
Cache the lines as extracted if they are used right now.
310
            # Since we needed the lines, we'll go ahead and cache them this way
311
            this_chunks = lines
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
312
            self._compute_diff(key, parent_lines, lines)
5374.2.4 by John Arbash Meinel
Cache the lines as extracted if they are used right now.
313
            del lines
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
314
        # Is this content required for any more children?
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
315
        if key in self.refcounts:
316
            self.chunks[key] = this_chunks
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
317
318
    def _extract_diffs(self):
319
        needed_keys, refcounts = self._find_needed_keys()
320
        for record in self.vf.get_record_stream(needed_keys,
321
                                                'topological', True):
322
            if record.storage_kind == 'absent':
323
                raise errors.RevisionNotPresent(record.key, self.vf)
5374.2.5 by John Arbash Meinel
Rework things a bit so the logic can be shared.
324
            self._process_one_record(record.key,
325
                                     record.get_bytes_as('chunked'))
5374.2.2 by John Arbash Meinel
Create a multi-parent diff generator class.
326
        
327
    def compute_diffs(self):
328
        self._extract_diffs()
329
        dpop = self.diffs.pop
330
        return [dpop(k) for k in self.ordered_keys]
331
332
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
333
class VersionedFile(object):
334
    """Versioned text file storage.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
335
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
336
    A versioned file manages versions of line-based text files,
337
    keeping track of the originating version for each line.
338
339
    To clients the "lines" of the file are represented as a list of
340
    strings. These strings will typically have terminal newline
341
    characters, but this is not required.  In particular files commonly
342
    do not have a newline at the end of the file.
343
344
    Texts are identified by a version-id string.
345
    """
346
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
347
    @staticmethod
2229.2.3 by Aaron Bentley
change reserved_id to is_reserved_id, add check_not_reserved for DRY
348
    def check_not_reserved_id(version_id):
349
        revision.check_not_reserved_id(version_id)
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
350
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
351
    def copy_to(self, name, transport):
352
        """Copy this versioned file to name on transport."""
353
        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
354
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
355
    def get_record_stream(self, versions, ordering, include_delta_closure):
356
        """Get a stream of records for versions.
357
358
        :param versions: The versions to include. Each version is a tuple
359
            (version,).
360
        :param ordering: Either 'unordered' or 'topological'. A topologically
361
            sorted stream has compression parents strictly before their
362
            children.
363
        :param include_delta_closure: If True then the closure across any
3350.3.22 by Robert Collins
Review feedback.
364
            compression parents will be included (in the data content of the
365
            stream, not in the emitted records). This guarantees that
366
            'fulltext' can be used successfully on every record.
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
367
        :return: An iterator of ContentFactory objects, each of which is only
368
            valid until the iterator is advanced.
369
        """
370
        raise NotImplementedError(self.get_record_stream)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
371
372
    def has_version(self, version_id):
373
        """Returns whether version is present."""
374
        raise NotImplementedError(self.has_version)
375
5195.3.26 by Parth Malwankar
reverted changes done to insert_record_stream API
376
    def insert_record_stream(self, stream):
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
377
        """Insert a record stream into this versioned file.
378
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
379
        :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.
380
        :return: None
381
        :seealso VersionedFile.get_record_stream:
382
        """
383
        raise NotImplementedError
384
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
385
    def add_lines(self, version_id, parents, lines, parent_texts=None,
2805.6.7 by Robert Collins
Review feedback.
386
        left_matching_blocks=None, nostore_sha=None, random_id=False,
387
        check_content=True):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
388
        """Add a single text on top of the versioned file.
389
390
        Must raise RevisionAlreadyPresent if the new version is
391
        already present in file history.
392
393
        Must raise RevisionNotPresent if any of the given parents are
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
394
        not present in file history.
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
395
396
        :param lines: A list of lines. Each line must be a bytestring. And all
397
            of them except the last must be terminated with \n and contain no
398
            other \n's. The last line may either contain no \n's or a single
399
            terminated \n. If the lines list does meet this constraint the add
400
            routine may error or may succeed - but you will be unable to read
401
            the data back accurately. (Checking the lines have been split
2805.6.7 by Robert Collins
Review feedback.
402
            correctly is expensive and extremely unlikely to catch bugs so it
403
            is not done at runtime unless check_content is True.)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
404
        :param parent_texts: An optional dictionary containing the opaque
2805.6.3 by Robert Collins
* The ``VersionedFile`` interface no longer protects against misuse when
405
            representations of some or all of the parents of version_id to
406
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
407
            returned by add_lines or data corruption can be caused.
2520.4.148 by Aaron Bentley
Updates from review
408
        :param left_matching_blocks: a hint about which areas are common
409
            between the text and its left-hand-parent.  The format is
410
            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.
411
        :param nostore_sha: Raise ExistingContent and do not add the lines to
412
            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.
413
        :param random_id: If True a random id has been selected rather than
414
            an id determined by some deterministic process such as a converter
415
            from a foreign VCS. When True the backend may choose not to check
416
            for uniqueness of the resulting key within the versioned file, so
417
            this should only be done when the result is expected to be unique
418
            anyway.
2805.6.7 by Robert Collins
Review feedback.
419
        :param check_content: If True, the lines supplied are verified to be
420
            bytestrings that are correctly formed lines.
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
421
        :return: The text sha1, the number of bytes in the text, and an opaque
422
                 representation of the inserted version which can be provided
423
                 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.
424
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
425
        self._check_write_ok()
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
426
        return self._add_lines(version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
427
            left_matching_blocks, nostore_sha, random_id, check_content)
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
428
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
429
    def _add_lines(self, version_id, parents, lines, parent_texts,
2805.6.7 by Robert Collins
Review feedback.
430
        left_matching_blocks, nostore_sha, random_id, check_content):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
431
        """Helper to do the class specific add_lines."""
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
432
        raise NotImplementedError(self.add_lines)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
433
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
434
    def add_lines_with_ghosts(self, version_id, parents, lines,
2805.6.7 by Robert Collins
Review feedback.
435
        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.
436
        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.
437
        """Add lines to the versioned file, allowing ghosts to be present.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
438
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
439
        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.
440
        """
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
441
        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.
442
        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.
443
            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.
444
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
445
    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.
446
        nostore_sha, random_id, check_content, left_matching_blocks):
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
447
        """Helper to do class specific add_lines_with_ghosts."""
1594.2.8 by Robert Collins
add ghost aware apis to knits.
448
        raise NotImplementedError(self.add_lines_with_ghosts)
449
1563.2.19 by Robert Collins
stub out a check for knits.
450
    def check(self, progress_bar=None):
451
        """Check the versioned file for integrity."""
452
        raise NotImplementedError(self.check)
453
1666.1.6 by Robert Collins
Make knit the default format.
454
    def _check_lines_not_unicode(self, lines):
455
        """Check that lines being added to a versioned file are not unicode."""
456
        for line in lines:
457
            if line.__class__ is not str:
458
                raise errors.BzrBadParameterUnicode("lines")
459
460
    def _check_lines_are_lines(self, lines):
461
        """Check that the lines really are full lines without inline EOL."""
462
        for line in lines:
463
            if '\n' in line[:-1]:
464
                raise errors.BzrBadParameterContainsNewline("lines")
465
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
466
    def get_format_signature(self):
467
        """Get a text description of the data encoding in this file.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
468
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
469
        :since: 0.90
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
470
        """
471
        raise NotImplementedError(self.get_format_signature)
472
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
473
    def make_mpdiffs(self, version_ids):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
474
        """Create multiparent diffs for specified versions."""
5374.2.3 by John Arbash Meinel
Replace the generic VersionedFiles.make_mpdiffs interface.
475
        # XXX: Can't use _MPDiffGenerator just yet. This is because version_ids
476
        #      is a list of strings, not keys. And while self.get_record_stream
477
        #      is supported, it takes *keys*, while self.get_parent_map() takes
478
        #      strings... *sigh*
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()."""
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
823
        return urlutils.quote(self._map(key))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
824
825
    def unmap(self, partition_id):
826
        """See KeyMapper.unmap()."""
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
827
        return self._unmap(urlutils.unquote(partition_id))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
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
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
880
        This is similar to a plain urlutils.quote, except
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
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."""
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
893
        return urlutils.unquote(basename)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
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.
5652.2.2 by Martin Pool
Rename _fallback_vfs to _immediate_fallbacks
926
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
927
    :ivar _immediate_fallback_vfs: For subclasses that support stacking,
5652.2.2 by Martin Pool
Rename _fallback_vfs to _immediate_fallbacks
928
        this is a list of other VersionedFiles immediately underneath this
929
        one.  They may in turn each have further fallbacks.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
930
    """
931
932
    def add_lines(self, key, parents, lines, parent_texts=None,
933
        left_matching_blocks=None, nostore_sha=None, random_id=False,
934
        check_content=True):
935
        """Add a text to the store.
936
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
937
        :param key: The key tuple of the text to add. If the last element is
938
            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.
939
        :param parents: The parents key tuples of the text to add.
940
        :param lines: A list of lines. Each line must be a bytestring. And all
941
            of them except the last must be terminated with \n and contain no
942
            other \n's. The last line may either contain no \n's or a single
943
            terminating \n. If the lines list does meet this constraint the add
944
            routine may error or may succeed - but you will be unable to read
945
            the data back accurately. (Checking the lines have been split
946
            correctly is expensive and extremely unlikely to catch bugs so it
947
            is not done at runtime unless check_content is True.)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
948
        :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.
949
            representations of some or all of the parents of version_id to
950
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
951
            returned by add_lines or data corruption can be caused.
952
        :param left_matching_blocks: a hint about which areas are common
953
            between the text and its left-hand-parent.  The format is
954
            the SequenceMatcher.get_matching_blocks format.
955
        :param nostore_sha: Raise ExistingContent and do not add the lines to
956
            the versioned file if the digest of the lines matches this.
957
        :param random_id: If True a random id has been selected rather than
958
            an id determined by some deterministic process such as a converter
959
            from a foreign VCS. When True the backend may choose not to check
960
            for uniqueness of the resulting key within the versioned file, so
961
            this should only be done when the result is expected to be unique
962
            anyway.
963
        :param check_content: If True, the lines supplied are verified to be
964
            bytestrings that are correctly formed lines.
965
        :return: The text sha1, the number of bytes in the text, and an opaque
966
                 representation of the inserted version which can be provided
967
                 back to future add_lines calls in the parent_texts dictionary.
968
        """
969
        raise NotImplementedError(self.add_lines)
970
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
971
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
972
        """Add a text to the store.
973
5815.4.2 by Jelmer Vernooij
split out versionedfile-specific stuff from commitbuilder.
974
        This is a private function for use by VersionedFileCommitBuilder.
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
975
976
        :param key: The key tuple of the text to add. If the last element is
977
            None, a CHK string will be generated during the addition.
978
        :param parents: The parents key tuples of the text to add.
979
        :param text: A string containing the text to be committed.
980
        :param nostore_sha: Raise ExistingContent and do not add the lines to
981
            the versioned file if the digest of the lines matches this.
982
        :param random_id: If True a random id has been selected rather than
983
            an id determined by some deterministic process such as a converter
984
            from a foreign VCS. When True the backend may choose not to check
985
            for uniqueness of the resulting key within the versioned file, so
986
            this should only be done when the result is expected to be unique
987
            anyway.
988
        :param check_content: If True, the lines supplied are verified to be
989
            bytestrings that are correctly formed lines.
990
        :return: The text sha1, the number of bytes in the text, and an opaque
991
                 representation of the inserted version which can be provided
992
                 back to future _add_text calls in the parent_texts dictionary.
993
        """
994
        # The default implementation just thunks over to .add_lines(),
995
        # inefficient, but it works.
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
996
        return self.add_lines(key, parents, osutils.split_lines(text),
997
                              nostore_sha=nostore_sha,
998
                              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'.
999
                              check_content=True)
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
1000
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1001
    def add_mpdiffs(self, records):
1002
        """Add mpdiffs to this VersionedFile.
1003
1004
        Records should be iterables of version, parents, expected_sha1,
1005
        mpdiff. mpdiff should be a MultiParent instance.
1006
        """
1007
        vf_parents = {}
1008
        mpvf = multiparent.MultiMemoryVersionedFile()
1009
        versions = []
1010
        for version, parent_ids, expected_sha1, mpdiff in records:
1011
            versions.append(version)
1012
            mpvf.add_diff(mpdiff, version, parent_ids)
1013
        needed_parents = set()
1014
        for version, parent_ids, expected_sha1, mpdiff in records:
1015
            needed_parents.update(p for p in parent_ids
1016
                                  if not mpvf.has_version(p))
1017
        # It seems likely that adding all the present parents as fulltexts can
1018
        # easily exhaust memory.
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
1019
        chunks_to_lines = osutils.chunks_to_lines
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
1020
        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.
1021
            True):
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
1022
            if record.storage_kind == 'absent':
1023
                continue
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
1024
            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.
1025
                record.key, [])
1026
        for (key, parent_keys, expected_sha1, mpdiff), lines in\
1027
            zip(records, mpvf.get_line_list(versions)):
1028
            if len(parent_keys) == 1:
1029
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
1030
                    mpvf.get_diff(parent_keys[0]).num_lines()))
1031
            else:
1032
                left_matching_blocks = None
1033
            version_sha1, _, version_text = self.add_lines(key,
1034
                parent_keys, lines, vf_parents,
1035
                left_matching_blocks=left_matching_blocks)
1036
            if version_sha1 != expected_sha1:
1037
                raise errors.VersionedFileInvalidChecksum(version)
1038
            vf_parents[key] = version_text
1039
1040
    def annotate(self, key):
1041
        """Return a list of (version-key, line) tuples for the text of key.
1042
1043
        :raise RevisionNotPresent: If the key is not present.
1044
        """
1045
        raise NotImplementedError(self.annotate)
1046
1047
    def check(self, progress_bar=None):
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1048
        """Check this object for integrity.
1049
        
1050
        :param progress_bar: A progress bar to output as the check progresses.
1051
        :param keys: Specific keys within the VersionedFiles to check. When
1052
            this parameter is not None, check() becomes a generator as per
1053
            get_record_stream. The difference to get_record_stream is that
1054
            more or deeper checks will be performed.
1055
        :return: None, or if keys was supplied a generator as per
1056
            get_record_stream.
1057
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1058
        raise NotImplementedError(self.check)
1059
1060
    @staticmethod
1061
    def check_not_reserved_id(version_id):
1062
        revision.check_not_reserved_id(version_id)
1063
4744.2.5 by John Arbash Meinel
Change to a generic 'VersionedFiles.clear_cache()' api.
1064
    def clear_cache(self):
1065
        """Clear whatever caches this VersionedFile holds.
1066
1067
        This is generally called after an operation has been performed, when we
1068
        don't expect to be using this versioned file again soon.
1069
        """
1070
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1071
    def _check_lines_not_unicode(self, lines):
1072
        """Check that lines being added to a versioned file are not unicode."""
1073
        for line in lines:
1074
            if line.__class__ is not str:
1075
                raise errors.BzrBadParameterUnicode("lines")
1076
1077
    def _check_lines_are_lines(self, lines):
1078
        """Check that the lines really are full lines without inline EOL."""
1079
        for line in lines:
1080
            if '\n' in line[:-1]:
1081
                raise errors.BzrBadParameterContainsNewline("lines")
1082
4593.5.36 by John Arbash Meinel
a few more implementations of the interface.
1083
    def get_known_graph_ancestry(self, keys):
1084
        """Get a KnownGraph instance with the ancestry of keys."""
1085
        # most basic implementation is a loop around get_parent_map
1086
        pending = set(keys)
1087
        parent_map = {}
1088
        while pending:
1089
            this_parent_map = self.get_parent_map(pending)
1090
            parent_map.update(this_parent_map)
1091
            pending = set()
1092
            map(pending.update, this_parent_map.itervalues())
1093
            pending = pending.difference(parent_map)
1094
        kg = _mod_graph.KnownGraph(parent_map)
1095
        return kg
1096
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1097
    def get_parent_map(self, keys):
1098
        """Get a map of the parents of keys.
1099
1100
        :param keys: The keys to look up parents for.
1101
        :return: A mapping from keys to parents. Absent keys are absent from
1102
            the mapping.
1103
        """
1104
        raise NotImplementedError(self.get_parent_map)
1105
1106
    def get_record_stream(self, keys, ordering, include_delta_closure):
1107
        """Get a stream of records for keys.
1108
1109
        :param keys: The keys to include.
1110
        :param ordering: Either 'unordered' or 'topological'. A topologically
1111
            sorted stream has compression parents strictly before their
1112
            children.
1113
        :param include_delta_closure: If True then the closure across any
1114
            compression parents will be included (in the opaque data).
1115
        :return: An iterator of ContentFactory objects, each of which is only
1116
            valid until the iterator is advanced.
1117
        """
1118
        raise NotImplementedError(self.get_record_stream)
1119
1120
    def get_sha1s(self, keys):
1121
        """Get the sha1's of the texts for the given keys.
1122
1123
        :param keys: The names of the keys to lookup
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1124
        :return: a dict from key to sha1 digest. Keys of texts which are not
3350.8.14 by Robert Collins
Review feedback.
1125
            present in the store are not present in the returned
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1126
            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.
1127
        """
1128
        raise NotImplementedError(self.get_sha1s)
1129
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
1130
    has_key = index._has_key_from_parent_map
1131
4009.3.3 by Andrew Bennetts
Add docstrings.
1132
    def get_missing_compression_parent_keys(self):
1133
        """Return an iterable of keys of missing compression parents.
1134
1135
        Check this after calling insert_record_stream to find out if there are
1136
        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.
1137
        depend on them are not able to be inserted safely. The precise
1138
        behaviour depends on the concrete VersionedFiles class in use.
1139
1140
        Classes that do not support this will raise NotImplementedError.
4009.3.3 by Andrew Bennetts
Add docstrings.
1141
        """
1142
        raise NotImplementedError(self.get_missing_compression_parent_keys)
1143
5195.3.26 by Parth Malwankar
reverted changes done to insert_record_stream API
1144
    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.
1145
        """Insert a record stream into this container.
1146
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1147
        :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.
1148
        :return: None
1149
        :seealso VersionedFile.get_record_stream:
1150
        """
1151
        raise NotImplementedError
1152
1153
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1154
        """Iterate over the lines in the versioned files from keys.
1155
1156
        This may return lines from other keys. Each item the returned
1157
        iterator yields is a tuple of a line and a text version that that line
1158
        is present in (not introduced in).
1159
1160
        Ordering of results is in whatever order is most suitable for the
1161
        underlying storage format.
1162
1163
        If a progress bar is supplied, it may be used to indicate progress.
1164
        The caller is responsible for cleaning up progress bars (because this
1165
        is an iterator).
1166
1167
        NOTES:
1168
         * Lines are normalised by the underlying store: they will all have \n
1169
           terminators.
1170
         * Lines are returned in arbitrary order.
1171
1172
        :return: An iterator over (line, key).
1173
        """
1174
        raise NotImplementedError(self.iter_lines_added_or_present_in_keys)
1175
1176
    def keys(self):
1177
        """Return a iterable of the keys for all the contained texts."""
1178
        raise NotImplementedError(self.keys)
1179
1180
    def make_mpdiffs(self, keys):
1181
        """Create multiparent diffs for specified keys."""
5374.2.3 by John Arbash Meinel
Replace the generic VersionedFiles.make_mpdiffs interface.
1182
        generator = _MPDiffGenerator(self, keys)
1183
        return generator.compute_diffs()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1184
5363.1.1 by Jelmer Vernooij
Provide VersionedFiles.get_annotator.
1185
    def get_annotator(self):
1186
        return annotate.Annotator(self)
1187
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
1188
    missing_keys = index._missing_keys_from_parent_map
1189
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1190
    def _extract_blocks(self, version_id, source, target):
1191
        return None
1192
5050.70.2 by Martin Pool
Search all fallbacks for get_known_graph_ancestry
1193
    def _transitive_fallbacks(self):
1194
        """Return the whole stack of fallback versionedfiles.
1195
1196
        This VersionedFiles may have a list of fallbacks, but it doesn't
1197
        necessarily know about the whole stack going down, and it can't know
1198
        at open time because they may change after the objects are opened.
1199
        """
1200
        all_fallbacks = []
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1201
        for a_vfs in self._immediate_fallback_vfs:
5050.70.2 by Martin Pool
Search all fallbacks for get_known_graph_ancestry
1202
            all_fallbacks.append(a_vfs)
1203
            all_fallbacks.extend(a_vfs._transitive_fallbacks())
1204
        return all_fallbacks
1205
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1206
1207
class ThunkedVersionedFiles(VersionedFiles):
1208
    """Storage for many versioned files thunked onto a 'VersionedFile' class.
1209
1210
    This object allows a single keyspace for accessing the history graph and
1211
    contents of named bytestrings.
1212
1213
    Currently no implementation allows the graph of different key prefixes to
1214
    intersect, but the API does allow such implementations in the future.
1215
    """
1216
1217
    def __init__(self, transport, file_factory, mapper, is_locked):
1218
        """Create a ThunkedVersionedFiles."""
1219
        self._transport = transport
1220
        self._file_factory = file_factory
1221
        self._mapper = mapper
1222
        self._is_locked = is_locked
1223
1224
    def add_lines(self, key, parents, lines, parent_texts=None,
1225
        left_matching_blocks=None, nostore_sha=None, random_id=False,
1226
        check_content=True):
1227
        """See VersionedFiles.add_lines()."""
1228
        path = self._mapper.map(key)
1229
        version_id = key[-1]
1230
        parents = [parent[-1] for parent in parents]
1231
        vf = self._get_vf(path)
1232
        try:
1233
            try:
1234
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1235
                    parent_texts=parent_texts,
1236
                    left_matching_blocks=left_matching_blocks,
1237
                    nostore_sha=nostore_sha, random_id=random_id,
1238
                    check_content=check_content)
1239
            except NotImplementedError:
1240
                return vf.add_lines(version_id, parents, lines,
1241
                    parent_texts=parent_texts,
1242
                    left_matching_blocks=left_matching_blocks,
1243
                    nostore_sha=nostore_sha, random_id=random_id,
1244
                    check_content=check_content)
1245
        except errors.NoSuchFile:
1246
            # parent directory may be missing, try again.
1247
            self._transport.mkdir(osutils.dirname(path))
1248
            try:
1249
                return vf.add_lines_with_ghosts(version_id, parents, lines,
1250
                    parent_texts=parent_texts,
1251
                    left_matching_blocks=left_matching_blocks,
1252
                    nostore_sha=nostore_sha, random_id=random_id,
1253
                    check_content=check_content)
1254
            except NotImplementedError:
1255
                return vf.add_lines(version_id, parents, lines,
1256
                    parent_texts=parent_texts,
1257
                    left_matching_blocks=left_matching_blocks,
1258
                    nostore_sha=nostore_sha, random_id=random_id,
1259
                    check_content=check_content)
1260
1261
    def annotate(self, key):
1262
        """Return a list of (version-key, line) tuples for the text of key.
1263
1264
        :raise RevisionNotPresent: If the key is not present.
1265
        """
1266
        prefix = key[:-1]
1267
        path = self._mapper.map(prefix)
1268
        vf = self._get_vf(path)
1269
        origins = vf.annotate(key[-1])
1270
        result = []
1271
        for origin, line in origins:
1272
            result.append((prefix + (origin,), line))
1273
        return result
1274
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1275
    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.
1276
        """See VersionedFiles.check()."""
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1277
        # XXX: This is over-enthusiastic but as we only thunk for Weaves today
1278
        # this is tolerable. Ideally we'd pass keys down to check() and 
1279
        # 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.
1280
        for prefix, vf in self._iter_all_components():
1281
            vf.check()
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1282
        if keys is not None:
1283
            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.
1284
1285
    def get_parent_map(self, keys):
1286
        """Get a map of the parents of keys.
1287
1288
        :param keys: The keys to look up parents for.
1289
        :return: A mapping from keys to parents. Absent keys are absent from
1290
            the mapping.
1291
        """
1292
        prefixes = self._partition_keys(keys)
1293
        result = {}
1294
        for prefix, suffixes in prefixes.items():
1295
            path = self._mapper.map(prefix)
1296
            vf = self._get_vf(path)
1297
            parent_map = vf.get_parent_map(suffixes)
1298
            for key, parents in parent_map.items():
1299
                result[prefix + (key,)] = tuple(
1300
                    prefix + (parent,) for parent in parents)
1301
        return result
1302
1303
    def _get_vf(self, path):
1304
        if not self._is_locked():
1305
            raise errors.ObjectNotLocked(self)
1306
        return self._file_factory(path, self._transport, create=True,
1307
            get_scope=lambda:None)
1308
1309
    def _partition_keys(self, keys):
1310
        """Turn keys into a dict of prefix:suffix_list."""
1311
        result = {}
1312
        for key in keys:
1313
            prefix_keys = result.setdefault(key[:-1], [])
1314
            prefix_keys.append(key[-1])
1315
        return result
1316
1317
    def _get_all_prefixes(self):
1318
        # Identify all key prefixes.
1319
        # XXX: A bit hacky, needs polish.
1320
        if type(self._mapper) == ConstantMapper:
1321
            paths = [self._mapper.map(())]
1322
            prefixes = [()]
1323
        else:
1324
            relpaths = set()
1325
            for quoted_relpath in self._transport.iter_files_recursive():
1326
                path, ext = os.path.splitext(quoted_relpath)
1327
                relpaths.add(path)
1328
            paths = list(relpaths)
1329
            prefixes = [self._mapper.unmap(path) for path in paths]
1330
        return zip(paths, prefixes)
1331
1332
    def get_record_stream(self, keys, ordering, include_delta_closure):
1333
        """See VersionedFiles.get_record_stream()."""
1334
        # Ordering will be taken care of by each partitioned store; group keys
1335
        # by partition.
1336
        keys = sorted(keys)
1337
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1338
            suffixes = [(suffix,) for suffix in suffixes]
1339
            for record in vf.get_record_stream(suffixes, ordering,
1340
                include_delta_closure):
1341
                if record.parents is not None:
1342
                    record.parents = tuple(
1343
                        prefix + parent for parent in record.parents)
1344
                record.key = prefix + record.key
1345
                yield record
1346
1347
    def _iter_keys_vf(self, keys):
1348
        prefixes = self._partition_keys(keys)
1349
        sha1s = {}
1350
        for prefix, suffixes in prefixes.items():
1351
            path = self._mapper.map(prefix)
1352
            vf = self._get_vf(path)
1353
            yield prefix, suffixes, vf
1354
1355
    def get_sha1s(self, keys):
1356
        """See VersionedFiles.get_sha1s()."""
1357
        sha1s = {}
1358
        for prefix,suffixes, vf in self._iter_keys_vf(keys):
1359
            vf_sha1s = vf.get_sha1s(suffixes)
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1360
            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.
1361
                sha1s[prefix + (suffix,)] = sha1
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1362
        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.
1363
5195.3.26 by Parth Malwankar
reverted changes done to insert_record_stream API
1364
    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.
1365
        """Insert a record stream into this container.
1366
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1367
        :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.
1368
        :return: None
1369
        :seealso VersionedFile.get_record_stream:
1370
        """
1371
        for record in stream:
1372
            prefix = record.key[:-1]
1373
            key = record.key[-1:]
1374
            if record.parents is not None:
1375
                parents = [parent[-1:] for parent in record.parents]
1376
            else:
1377
                parents = None
1378
            thunk_record = AdapterFactory(key, parents, record)
1379
            path = self._mapper.map(prefix)
1380
            # Note that this parses the file many times; we can do better but
1381
            # as this only impacts weaves in terms of performance, it is
1382
            # tolerable.
1383
            vf = self._get_vf(path)
1384
            vf.insert_record_stream([thunk_record])
1385
1386
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1387
        """Iterate over the lines in the versioned files from keys.
1388
1389
        This may return lines from other keys. Each item the returned
1390
        iterator yields is a tuple of a line and a text version that that line
1391
        is present in (not introduced in).
1392
1393
        Ordering of results is in whatever order is most suitable for the
1394
        underlying storage format.
1395
1396
        If a progress bar is supplied, it may be used to indicate progress.
1397
        The caller is responsible for cleaning up progress bars (because this
1398
        is an iterator).
1399
1400
        NOTES:
1401
         * Lines are normalised by the underlying store: they will all have \n
1402
           terminators.
1403
         * Lines are returned in arbitrary order.
1404
1405
        :return: An iterator over (line, key).
1406
        """
1407
        for prefix, suffixes, vf in self._iter_keys_vf(keys):
1408
            for line, version in vf.iter_lines_added_or_present_in_versions(suffixes):
1409
                yield line, prefix + (version,)
1410
1411
    def _iter_all_components(self):
1412
        for path, prefix in self._get_all_prefixes():
1413
            yield prefix, self._get_vf(path)
1414
1415
    def keys(self):
1416
        """See VersionedFiles.keys()."""
1417
        result = set()
1418
        for prefix, vf in self._iter_all_components():
1419
            for suffix in vf.versions():
1420
                result.add(prefix + (suffix,))
1421
        return result
1422
1423
5816.8.1 by Andrew Bennetts
Be a little more clever about constructing a parents provider for stacked repositories, so that get_parent_map with local-stacked-on-remote doesn't use HPSS VFS calls.
1424
class VersionedFilesWithFallbacks(VersionedFiles):
1425
1426
    def without_fallbacks(self):
1427
        """Return a clone of this object without any fallbacks configured."""
1428
        raise NotImplementedError(self.without_fallbacks)
1429
1430
    def add_fallback_versioned_files(self, a_versioned_files):
1431
        """Add a source of texts for texts not present in this knit.
1432
1433
        :param a_versioned_files: A VersionedFiles object.
1434
        """
1435
        raise NotImplementedError(self.add_fallback_versioned_files)
1436
5863.1.1 by Andrew Bennetts
Move duplicate definitions of {Knit,GroupCompress}VersionedFiles.get_known_graph_ancestry into VersionedFilesWithFallbacks.
1437
    def get_known_graph_ancestry(self, keys):
1438
        """Get a KnownGraph instance with the ancestry of keys."""
1439
        parent_map, missing_keys = self._index.find_ancestry(keys)
1440
        for fallback in self._transitive_fallbacks():
1441
            if not missing_keys:
1442
                break
1443
            (f_parent_map, f_missing_keys) = fallback._index.find_ancestry(
1444
                                                missing_keys)
1445
            parent_map.update(f_parent_map)
1446
            missing_keys = f_missing_keys
1447
        kg = _mod_graph.KnownGraph(parent_map)
1448
        return kg
1449
5816.8.1 by Andrew Bennetts
Be a little more clever about constructing a parents provider for stacked repositories, so that get_parent_map with local-stacked-on-remote doesn't use HPSS VFS calls.
1450
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1451
class _PlanMergeVersionedFile(VersionedFiles):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1452
    """A VersionedFile for uncommitted and committed texts.
1453
1454
    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.
1455
    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
1456
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
1457
    _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.
1458
1459
    :ivar: fallback_versionedfiles a list of VersionedFiles objects that can be
1460
        queried for missing texts.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1461
    """
1462
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1463
    def __init__(self, file_id):
1464
        """Create a _PlanMergeVersionedFile.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1465
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1466
        :param file_id: Used with _PlanMerge code which is not yet fully
1467
            tuple-keyspace aware.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1468
        """
1469
        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.
1470
        # fallback locations
1471
        self.fallback_versionedfiles = []
1472
        # Parents for locally held keys.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1473
        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.
1474
        # line data for locally held keys.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1475
        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.
1476
        # key lookup providers
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
1477
        self._providers = [_mod_graph.DictParentsProvider(self._parents)]
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1478
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1479
    def plan_merge(self, ver_a, ver_b, base=None):
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
1480
        """See VersionedFile.plan_merge"""
3144.3.7 by Aaron Bentley
Update from review
1481
        from bzrlib.merge import _PlanMerge
3062.2.3 by Aaron Bentley
Sync up with bzr.dev API changes
1482
        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.
1483
            return _PlanMerge(ver_a, ver_b, self, (self._file_id,)).plan_merge()
1484
        old_plan = list(_PlanMerge(ver_a, base, self, (self._file_id,)).plan_merge())
1485
        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
1486
        return _PlanMerge._subtract_plans(old_plan, new_plan)
1487
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1488
    def plan_lca_merge(self, ver_a, ver_b, base=None):
3144.3.7 by Aaron Bentley
Update from review
1489
        from bzrlib.merge import _PlanLCAMerge
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
1490
        graph = _mod_graph.Graph(self)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1491
        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
1492
        if base is None:
1493
            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.
1494
        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
1495
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
3062.1.13 by Aaron Bentley
Make _PlanMerge an implementation detail of _PlanMergeVersionedFile
1496
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1497
    def add_lines(self, key, parents, lines):
1498
        """See VersionedFiles.add_lines
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1499
3350.6.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
        Lines are added locally, not to fallback versionedfiles.  Also, ghosts
1501
        are permitted.  Only reserved ids are permitted.
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1502
        """
3350.6.8 by Martin Pool
Change stray pdb calls to exceptions
1503
        if type(key) is not tuple:
1504
            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.
1505
        if not revision.is_reserved_id(key[-1]):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1506
            raise ValueError('Only reserved ids may be used')
1507
        if parents is None:
1508
            raise ValueError('Parents may not be None')
1509
        if lines is None:
1510
            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.
1511
        self._parents[key] = tuple(parents)
1512
        self._lines[key] = lines
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1513
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1514
    def get_record_stream(self, keys, ordering, include_delta_closure):
1515
        pending = set(keys)
1516
        for key in keys:
1517
            if key in self._lines:
1518
                lines = self._lines[key]
1519
                parents = self._parents[key]
1520
                pending.remove(key)
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1521
                yield ChunkedContentFactory(key, parents, None, lines)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1522
        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.
1523
            for record in versionedfile.get_record_stream(
1524
                pending, 'unordered', True):
1525
                if record.storage_kind == 'absent':
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1526
                    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.
1527
                else:
1528
                    pending.remove(record.key)
1529
                    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.
1530
            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.
1531
                return
1532
        # report absent entries
1533
        for key in pending:
1534
            yield AbsentContentFactory(key)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1535
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1536
    def get_parent_map(self, keys):
1537
        """See VersionedFiles.get_parent_map"""
1538
        # We create a new provider because a fallback may have been added.
1539
        # If we make fallbacks private we can update a stack list and avoid
1540
        # object creation thrashing.
3350.6.6 by Robert Collins
Fix test_plan_file_merge
1541
        keys = set(keys)
1542
        result = {}
1543
        if revision.NULL_REVISION in keys:
1544
            keys.remove(revision.NULL_REVISION)
1545
            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.
1546
        self._providers = self._providers[:1] + self.fallback_versionedfiles
3350.6.6 by Robert Collins
Fix test_plan_file_merge
1547
        result.update(
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
1548
            _mod_graph.StackedParentsProvider(
1549
                self._providers).get_parent_map(keys))
3350.6.5 by Robert Collins
Update to bzr.dev.
1550
        for key, parents in result.iteritems():
1551
            if parents == ():
1552
                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.
1553
        return result
3144.3.1 by Aaron Bentley
Implement LCA merge, with problematic conflict markers
1554
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
1555
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1556
class PlanWeaveMerge(TextMerge):
1551.6.13 by Aaron Bentley
Cleanup
1557
    """Weave merge that takes a plan as its input.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1558
1551.6.14 by Aaron Bentley
Tweaks from merge review
1559
    This exists so that VersionedFile.plan_merge is implementable.
1560
    Most callers will want to use WeaveMerge instead.
1551.6.13 by Aaron Bentley
Cleanup
1561
    """
1562
1551.6.14 by Aaron Bentley
Tweaks from merge review
1563
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
1564
                 b_marker=TextMerge.B_MARKER):
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1565
        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.
1566
        self.plan = list(plan)
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1567
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
1568
    def _merge_struct(self):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1569
        lines_a = []
1570
        lines_b = []
1571
        ch_a = ch_b = False
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1572
1573
        def outstanding_struct():
1574
            if not lines_a and not lines_b:
1575
                return
1576
            elif ch_a and not ch_b:
1577
                # one-sided change:
1578
                yield(lines_a,)
1579
            elif ch_b and not ch_a:
1580
                yield (lines_b,)
1581
            elif lines_a == lines_b:
1582
                yield(lines_a,)
1583
            else:
1584
                yield (lines_a, lines_b)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1585
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
1586
        # We previously considered either 'unchanged' or 'killed-both' lines
1587
        # to be possible places to resynchronize.  However, assuming agreement
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1588
        # on killed-both lines may be too aggressive. -- mbp 20060324
1551.6.7 by Aaron Bentley
Implemented two-way merge, refactored weave merge
1589
        for state, line in self.plan:
1616.1.18 by Martin Pool
(weave-merge) don't treat killed-both lines as points of agreement;
1590
            if state == 'unchanged':
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1591
                # resync and flush queued conflicts changes if any
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1592
                for struct in outstanding_struct():
1593
                    yield struct
1551.6.11 by Aaron Bentley
Switched TextMerge_lines to work on a list
1594
                lines_a = []
1595
                lines_b = []
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1596
                ch_a = ch_b = False
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1597
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1598
            if state == 'unchanged':
1599
                if line:
1551.6.5 by Aaron Bentley
Got weave merge producing structural output
1600
                    yield ([line],)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1601
            elif state == 'killed-a':
1602
                ch_a = True
1603
                lines_b.append(line)
1604
            elif state == 'killed-b':
1605
                ch_b = True
1606
                lines_a.append(line)
1607
            elif state == 'new-a':
1608
                ch_a = True
1609
                lines_a.append(line)
1610
            elif state == 'new-b':
1611
                ch_b = True
1612
                lines_b.append(line)
3144.3.2 by Aaron Bentley
Get conflict handling working
1613
            elif state == 'conflicted-a':
1614
                ch_b = ch_a = True
1615
                lines_a.append(line)
1616
            elif state == 'conflicted-b':
1617
                ch_b = ch_a = True
1618
                lines_b.append(line)
4312.1.1 by John Arbash Meinel
Add a per-implementation test that deleting lines conflicts with modifying lines.
1619
            elif state == 'killed-both':
1620
                # This counts as a change, even though there is no associated
1621
                # line
1622
                ch_b = ch_a = True
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
1623
            else:
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1624
                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.
1625
                        'killed-base'):
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
1626
                    raise AssertionError(state)
1664.2.8 by Aaron Bentley
Fix WeaveMerge when plan doesn't end with unchanged lines
1627
        for struct in outstanding_struct():
1628
            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.
1629
4634.101.7 by John Arbash Meinel
Start working on the ability to drop a .BASE file for --weave and --lca merge.
1630
    def base_from_plan(self):
1631
        """Construct a BASE file from the plan text."""
1632
        base_lines = []
1633
        for state, line in self.plan:
4634.101.9 by John Arbash Meinel
Reverse the .BASE values for --lca and conflicted lines.
1634
            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.
1635
                # If unchanged, then this line is straight from base. If a or b
1636
                # or both killed the line, then it *used* to be in base.
1637
                base_lines.append(line)
1638
            else:
1639
                if state not in ('killed-base', 'irrelevant',
1640
                                 'ghost-a', 'ghost-b',
4634.101.9 by John Arbash Meinel
Reverse the .BASE values for --lca and conflicted lines.
1641
                                 'new-a', 'new-b',
1642
                                 '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.
1643
                    # killed-base, irrelevant means it doesn't apply
1644
                    # ghost-a/ghost-b are harder to say for sure, but they
1645
                    # 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.
1646
                    # shared base of a & b. So we don't include them.  And
1647
                    # obviously if the line is newly inserted, it isn't in base
1648
1649
                    # If 'conflicted-a' or b, then it is new vs one base, but
1650
                    # old versus another base. However, if we make it present
1651
                    # 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.
1652
                    # seems better to get a line doubled in the merge result,
1653
                    # rather than have it deleted entirely.
4634.101.13 by John Arbash Meinel
Clean up a code comment.
1654
                    # Example, each node is the 'text' at that point:
1655
                    #           MN
1656
                    #          /   \
1657
                    #        MaN   MbN
1658
                    #         |  X  |
1659
                    #        MabN MbaN
1660
                    #          \   /
1661
                    #           ???
1662
                    # There was a criss-cross conflict merge. Both sides
1663
                    # include the other, but put themselves first.
1664
                    # Weave marks this as a 'clean' merge, picking OTHER over
1665
                    # THIS. (Though the details depend on order inserted into
1666
                    # weave, etc.)
1667
                    # LCA generates a plan:
1668
                    # [('unchanged', M),
1669
                    #  ('conflicted-b', b),
1670
                    #  ('unchanged', a),
1671
                    #  ('conflicted-a', b),
1672
                    #  ('unchanged', N)]
1673
                    # If you mark 'conflicted-*' as part of BASE, then a 3-way
1674
                    # merge tool will cleanly generate "MaN" (as BASE vs THIS
1675
                    # removes one 'b', and BASE vs OTHER removes the other)
1676
                    # If you include neither, 3-way creates a clean "MbabN" as
1677
                    # THIS adds one 'b', and OTHER does too.
1678
                    # It seems that having the line 2 times is better than
1679
                    # having it omitted. (Easier to manually delete than notice
1680
                    # 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.
1681
                    raise AssertionError('Unknown state: %s' % (state,))
1682
        return base_lines
1683
1664.2.14 by Aaron Bentley
spacing fix
1684
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1685
class WeaveMerge(PlanWeaveMerge):
2831.7.1 by Ian Clatworthy
versionedfile.py code cleanups
1686
    """Weave merge that takes a VersionedFile and two versions as its input."""
1551.6.13 by Aaron Bentley
Cleanup
1687
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1688
    def __init__(self, versionedfile, ver_a, ver_b,
1551.6.14 by Aaron Bentley
Tweaks from merge review
1689
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
1551.6.15 by Aaron Bentley
Moved plan_merge into Weave
1690
        plan = versionedfile.plan_merge(ver_a, ver_b)
1551.6.10 by Aaron Bentley
Renamed WeaveMerge to PlanMerge, added plan method, created planless WeaveMerge
1691
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
1692
1693
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1694
class VirtualVersionedFiles(VersionedFiles):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1695
    """Dummy implementation for VersionedFiles that uses other functions for
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1696
    obtaining fulltexts and parent maps.
1697
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1698
    This is always on the bottom of the stack and uses string keys
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1699
    (rather than tuples) internally.
1700
    """
1701
1702
    def __init__(self, get_parent_map, get_lines):
1703
        """Create a VirtualVersionedFiles.
1704
1705
        :param get_parent_map: Same signature as Repository.get_parent_map.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1706
        :param get_lines: Should return lines for specified key or None if
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1707
                          not available.
1708
        """
1709
        super(VirtualVersionedFiles, self).__init__()
1710
        self._get_parent_map = get_parent_map
1711
        self._get_lines = get_lines
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1712
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1713
    def check(self, progressbar=None):
1714
        """See VersionedFiles.check.
1715
1716
        :note: Always returns True for VirtualVersionedFiles.
1717
        """
1718
        return True
1719
1720
    def add_mpdiffs(self, records):
1721
        """See VersionedFiles.mpdiffs.
1722
1723
        :note: Not implemented for VirtualVersionedFiles.
1724
        """
1725
        raise NotImplementedError(self.add_mpdiffs)
1726
1727
    def get_parent_map(self, keys):
1728
        """See VersionedFiles.get_parent_map."""
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1729
        return dict([((k,), tuple([(p,) for p in v]))
1730
            for k,v in self._get_parent_map([k for (k,) in keys]).iteritems()])
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1731
1732
    def get_sha1s(self, keys):
1733
        """See VersionedFiles.get_sha1s."""
1734
        ret = {}
1735
        for (k,) in keys:
1736
            lines = self._get_lines(k)
1737
            if lines is not None:
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1738
                if not isinstance(lines, list):
1739
                    raise AssertionError
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1740
                ret[(k,)] = osutils.sha_strings(lines)
1741
        return ret
1742
1743
    def get_record_stream(self, keys, ordering, include_delta_closure):
1744
        """See VersionedFiles.get_record_stream."""
1745
        for (k,) in list(keys):
1746
            lines = self._get_lines(k)
1747
            if lines is not None:
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
1748
                if not isinstance(lines, list):
1749
                    raise AssertionError
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1750
                yield ChunkedContentFactory((k,), None,
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1751
                        sha1=osutils.sha_strings(lines),
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1752
                        chunks=lines)
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
1753
            else:
1754
                yield AbsentContentFactory((k,))
1755
3949.4.1 by Jelmer Vernooij
Implement VirtualVersionedFiles.iter_lines_added_or_present_in_keys.
1756
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1757
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
1758
        for i, (key,) in enumerate(keys):
1759
            if pb is not None:
4110.2.10 by Martin Pool
Tweak iter_lines progress messages
1760
                pb.update("Finding changed lines", i, len(keys))
3949.4.1 by Jelmer Vernooij
Implement VirtualVersionedFiles.iter_lines_added_or_present_in_keys.
1761
            for l in self._get_lines(key):
1762
                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.
1763
1764
5375.1.4 by Andrew Bennetts
Put NoDupeAddLinesDecorator in versionedfiles.py, and make it slightly more reusable.
1765
class NoDupeAddLinesDecorator(object):
1766
    """Decorator for a VersionedFiles that skips doing an add_lines if the key
1767
    is already present.
1768
    """
1769
1770
    def __init__(self, store):
1771
        self._store = store
1772
1773
    def add_lines(self, key, parents, lines, parent_texts=None,
1774
            left_matching_blocks=None, nostore_sha=None, random_id=False,
1775
            check_content=True):
1776
        """See VersionedFiles.add_lines.
1777
        
1778
        This implementation may return None as the third element of the return
1779
        value when the original store wouldn't.
1780
        """
1781
        if nostore_sha:
1782
            raise NotImplementedError(
1783
                "NoDupeAddLinesDecorator.add_lines does not implement the "
1784
                "nostore_sha behaviour.")
1785
        if key[-1] is None:
1786
            sha1 = osutils.sha_strings(lines)
1787
            key = ("sha1:" + sha1,)
1788
        else:
1789
            sha1 = None
1790
        if key in self._store.get_parent_map([key]):
1791
            # This key has already been inserted, so don't do it again.
1792
            if sha1 is None:
1793
                sha1 = osutils.sha_strings(lines)
1794
            return sha1, sum(map(len, lines)), None
1795
        return self._store.add_lines(key, parents, lines,
1796
                parent_texts=parent_texts,
1797
                left_matching_blocks=left_matching_blocks,
1798
                nostore_sha=nostore_sha, random_id=random_id,
1799
                check_content=check_content)
1800
1801
    def __getattr__(self, name):
1802
        return getattr(self._store, name)
1803
1804
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.
1805
def network_bytes_to_kind_and_offset(network_bytes):
1806
    """Strip of a record kind from the front of network_bytes.
1807
1808
    :param network_bytes: The bytes of a record.
1809
    :return: A tuple (storage_kind, offset_of_remaining_bytes)
1810
    """
1811
    line_end = network_bytes.find('\n')
1812
    storage_kind = network_bytes[:line_end]
1813
    return storage_kind, line_end + 1
1814
1815
1816
class NetworkRecordStream(object):
1817
    """A record_stream which reconstitures a serialised stream."""
1818
1819
    def __init__(self, bytes_iterator):
1820
        """Create a NetworkRecordStream.
1821
1822
        :param bytes_iterator: An iterator of bytes. Each item in this
1823
            iterator should have been obtained from a record_streams'
1824
            record.get_bytes_as(record.storage_kind) call.
1825
        """
1826
        self._bytes_iterator = bytes_iterator
4476.3.4 by Andrew Bennetts
Network serialisation, and most tests passing with InterDifferingSerializer commented out.
1827
        self._kind_factory = {
1828
            'fulltext': fulltext_network_to_record,
1829
            'groupcompress-block': groupcompress.network_block_to_records,
1830
            'knit-ft-gz': knit.knit_network_to_record,
1831
            'knit-delta-gz': knit.knit_network_to_record,
1832
            'knit-annotated-ft-gz': knit.knit_network_to_record,
1833
            'knit-annotated-delta-gz': knit.knit_network_to_record,
1834
            '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.
1835
            }
1836
1837
    def read(self):
1838
        """Read the stream.
1839
1840
        :return: An iterator as per VersionedFiles.get_record_stream().
1841
        """
1842
        for bytes in self._bytes_iterator:
1843
            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.
1844
            for record in self._kind_factory[storage_kind](
1845
                storage_kind, bytes, line_end):
1846
                yield record
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1847
1848
1849
def fulltext_network_to_record(kind, bytes, line_end):
1850
    """Convert a network fulltext record to record."""
1851
    meta_len, = struct.unpack('!L', bytes[line_end:line_end+4])
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1852
    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.
1853
    key, parents = bencode.bdecode_as_tuple(record_meta)
1854
    if parents == 'nil':
1855
        parents = None
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1856
    fulltext = bytes[line_end+4+meta_len:]
1857
    return [FulltextContentFactory(key, parents, None, fulltext)]
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1858
1859
1860
def _length_prefix(bytes):
1861
    return struct.pack('!L', len(bytes))
1862
1863
4060.1.4 by Robert Collins
Streaming fetch from remote servers.
1864
def record_to_fulltext_bytes(record):
4022.1.6 by Robert Collins
Cherrypick and polish the RemoteSink for streaming push.
1865
    if record.parents is None:
1866
        parents = 'nil'
1867
    else:
1868
        parents = record.parents
1869
    record_meta = bencode.bencode((record.key, parents))
1870
    record_content = record.get_bytes_as('fulltext')
1871
    return "fulltext\n%s%s%s" % (
1872
        _length_prefix(record_meta), record_meta, record_content)
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1873
1874
1875
def sort_groupcompress(parent_map):
1876
    """Sort and group the keys in parent_map into groupcompress order.
1877
1878
    groupcompress is defined (currently) as reverse-topological order, grouped
1879
    by the key prefix.
1880
1881
    :return: A sorted-list of keys
1882
    """
1883
    # gc-optimal ordering is approximately reverse topological,
1884
    # properly grouped by file-id.
1885
    per_prefix_map = {}
1886
    for item in parent_map.iteritems():
1887
        key = item[0]
1888
        if isinstance(key, str) or len(key) == 1:
1889
            prefix = ''
1890
        else:
1891
            prefix = key[0]
1892
        try:
1893
            per_prefix_map[prefix].append(item)
1894
        except KeyError:
1895
            per_prefix_map[prefix] = [item]
1896
1897
    present_keys = []
1898
    for prefix in sorted(per_prefix_map):
1899
        present_keys.extend(reversed(tsort.topo_sort(per_prefix_map[prefix])))
1900
    return present_keys
5757.8.1 by Jelmer Vernooij
Avoid bzrlib.knit imports when using groupcompress repositories.
1901
1902
1903
class _KeyRefs(object):
1904
1905
    def __init__(self, track_new_keys=False):
1906
        # dict mapping 'key' to 'set of keys referring to that key'
1907
        self.refs = {}
1908
        if track_new_keys:
1909
            # set remembering all new keys
1910
            self.new_keys = set()
1911
        else:
1912
            self.new_keys = None
1913
1914
    def clear(self):
1915
        if self.refs:
1916
            self.refs.clear()
1917
        if self.new_keys:
1918
            self.new_keys.clear()
1919
1920
    def add_references(self, key, refs):
1921
        # Record the new references
1922
        for referenced in refs:
1923
            try:
1924
                needed_by = self.refs[referenced]
1925
            except KeyError:
1926
                needed_by = self.refs[referenced] = set()
1927
            needed_by.add(key)
1928
        # Discard references satisfied by the new key
1929
        self.add_key(key)
1930
1931
    def get_new_keys(self):
1932
        return self.new_keys
1933
    
1934
    def get_unsatisfied_refs(self):
1935
        return self.refs.iterkeys()
1936
1937
    def _satisfy_refs_for_key(self, key):
1938
        try:
1939
            del self.refs[key]
1940
        except KeyError:
1941
            # No keys depended on this key.  That's ok.
1942
            pass
1943
1944
    def add_key(self, key):
1945
        # satisfy refs for key, and remember that we've seen this key.
1946
        self._satisfy_refs_for_key(key)
1947
        if self.new_keys is not None:
1948
            self.new_keys.add(key)
1949
1950
    def satisfy_refs_for_keys(self, keys):
1951
        for key in keys:
1952
            self._satisfy_refs_for_key(key)
1953
1954
    def get_referrers(self):
1955
        result = set()
1956
        for referrers in self.refs.itervalues():
1957
            result.update(referrers)
1958
        return result
1959
1960
5815.5.8 by Jelmer Vernooij
Use traditional (fileid, revision) entries in file graph.
1961