/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/versionedfile.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-06-05 03:02:10 UTC
  • mfrom: (3472.1.1 ianc-integration)
  • Revision ID: pqm@pqm.ubuntu.com-20080605030210-xwokghqkg4sqo1xy
Isolate the test HTTPServer from chdir calls (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 by Canonical Ltd
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
2
#
3
3
# Authors:
4
4
#   Johan Rydberg <jrydberg@gnu.org>
7
7
# it under the terms of the GNU General Public License as published by
8
8
# the Free Software Foundation; either version 2 of the License, or
9
9
# (at your option) any later version.
10
 
 
 
10
#
11
11
# This program is distributed in the hope that it will be useful,
12
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
14
# GNU General Public License for more details.
15
 
 
 
15
#
16
16
# You should have received a copy of the GNU General Public License
17
17
# along with this program; if not, write to the Free Software
18
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
19
 
20
 
# Remaing to do is to figure out if get_graph should return a simple
21
 
# map, or a graph object of some kind.
22
 
 
23
 
 
24
20
"""Versioned text file storage api."""
25
21
 
26
 
 
27
 
from copy import deepcopy
28
 
from unittest import TestSuite
29
 
 
30
 
 
31
 
import bzrlib.errors as errors
 
22
from bzrlib.lazy_import import lazy_import
 
23
lazy_import(globals(), """
 
24
 
 
25
from bzrlib import (
 
26
    errors,
 
27
    osutils,
 
28
    multiparent,
 
29
    tsort,
 
30
    revision,
 
31
    ui,
 
32
    )
 
33
from bzrlib.graph import Graph
 
34
from bzrlib.transport.memory import MemoryTransport
 
35
""")
 
36
 
 
37
from cStringIO import StringIO
 
38
 
32
39
from bzrlib.inter import InterObject
 
40
from bzrlib.registry import Registry
33
41
from bzrlib.symbol_versioning import *
34
 
from bzrlib.transport.memory import MemoryTransport
35
 
from bzrlib.tsort import topo_sort
36
 
from bzrlib import ui
 
42
from bzrlib.textmerge import TextMerge
 
43
 
 
44
 
 
45
adapter_registry = Registry()
 
46
adapter_registry.register_lazy(('knit-delta-gz', 'fulltext'), 'bzrlib.knit',
 
47
    'DeltaPlainToFullText')
 
48
adapter_registry.register_lazy(('knit-ft-gz', 'fulltext'), 'bzrlib.knit',
 
49
    'FTPlainToFullText')
 
50
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'knit-delta-gz'),
 
51
    'bzrlib.knit', 'DeltaAnnotatedToUnannotated')
 
52
adapter_registry.register_lazy(('knit-annotated-delta-gz', 'fulltext'),
 
53
    'bzrlib.knit', 'DeltaAnnotatedToFullText')
 
54
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'knit-ft-gz'),
 
55
    'bzrlib.knit', 'FTAnnotatedToUnannotated')
 
56
adapter_registry.register_lazy(('knit-annotated-ft-gz', 'fulltext'),
 
57
    'bzrlib.knit', 'FTAnnotatedToFullText')
 
58
 
 
59
 
 
60
class ContentFactory(object):
 
61
    """Abstract interface for insertion and retrieval from a VersionedFile.
 
62
    
 
63
    :ivar sha1: None, or the sha1 of the content fulltext.
 
64
    :ivar storage_kind: The native storage kind of this factory. One of
 
65
        'mpdiff', 'knit-annotated-ft', 'knit-annotated-delta', 'knit-ft',
 
66
        'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
 
67
        'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'.
 
68
    :ivar key: The key of this content. Each key is a tuple with a single
 
69
        string in it.
 
70
    :ivar parents: A tuple of parent keys for self.key. If the object has
 
71
        no parent information, None (as opposed to () for an empty list of
 
72
        parents).
 
73
        """
 
74
 
 
75
    def __init__(self):
 
76
        """Create a ContentFactory."""
 
77
        self.sha1 = None
 
78
        self.storage_kind = None
 
79
        self.key = None
 
80
        self.parents = None
 
81
 
 
82
 
 
83
class AbsentContentFactory(object):
 
84
    """A placeholder content factory for unavailable texts.
 
85
    
 
86
    :ivar sha1: None.
 
87
    :ivar storage_kind: 'absent'.
 
88
    :ivar key: The key of this content. Each key is a tuple with a single
 
89
        string in it.
 
90
    :ivar parents: None.
 
91
    """
 
92
 
 
93
    def __init__(self, key):
 
94
        """Create a ContentFactory."""
 
95
        self.sha1 = None
 
96
        self.storage_kind = 'absent'
 
97
        self.key = key
 
98
        self.parents = None
 
99
 
 
100
 
 
101
def filter_absent(record_stream):
 
102
    """Adapt a record stream to remove absent records."""
 
103
    for record in record_stream:
 
104
        if record.storage_kind != 'absent':
 
105
            yield record
37
106
 
38
107
 
39
108
class VersionedFile(object):
50
119
    Texts are identified by a version-id string.
51
120
    """
52
121
 
53
 
    def __init__(self, access_mode):
54
 
        self.finished = False
55
 
        self._access_mode = access_mode
 
122
    @staticmethod
 
123
    def check_not_reserved_id(version_id):
 
124
        revision.check_not_reserved_id(version_id)
56
125
 
57
126
    def copy_to(self, name, transport):
58
127
        """Copy this versioned file to name on transport."""
59
128
        raise NotImplementedError(self.copy_to)
60
 
    
61
 
    @deprecated_method(zero_eight)
62
 
    def names(self):
63
 
        """Return a list of all the versions in this versioned file.
64
 
 
65
 
        Please use versionedfile.versions() now.
 
129
 
 
130
    def get_record_stream(self, versions, ordering, include_delta_closure):
 
131
        """Get a stream of records for versions.
 
132
 
 
133
        :param versions: The versions to include. Each version is a tuple
 
134
            (version,).
 
135
        :param ordering: Either 'unordered' or 'topological'. A topologically
 
136
            sorted stream has compression parents strictly before their
 
137
            children.
 
138
        :param include_delta_closure: If True then the closure across any
 
139
            compression parents will be included (in the data content of the
 
140
            stream, not in the emitted records). This guarantees that
 
141
            'fulltext' can be used successfully on every record.
 
142
        :return: An iterator of ContentFactory objects, each of which is only
 
143
            valid until the iterator is advanced.
66
144
        """
67
 
        return self.versions()
68
 
 
69
 
    def versions(self):
70
 
        """Return a unsorted list of versions."""
71
 
        raise NotImplementedError(self.versions)
72
 
 
73
 
    def has_ghost(self, version_id):
74
 
        """Returns whether version is present as a ghost."""
75
 
        raise NotImplementedError(self.has_ghost)
 
145
        raise NotImplementedError(self.get_record_stream)
76
146
 
77
147
    def has_version(self, version_id):
78
148
        """Returns whether version is present."""
79
149
        raise NotImplementedError(self.has_version)
80
150
 
81
 
    def add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
82
 
        """Add a text to the versioned file via a pregenerated delta.
83
 
 
84
 
        :param version_id: The version id being added.
85
 
        :param parents: The parents of the version_id.
86
 
        :param delta_parent: The parent this delta was created against.
87
 
        :param sha1: The sha1 of the full text.
88
 
        :param delta: The delta instructions. See get_delta for details.
89
 
        """
90
 
        self._check_write_ok()
91
 
        if self.has_version(version_id):
92
 
            raise errors.RevisionAlreadyPresent(version_id, self)
93
 
        return self._add_delta(version_id, parents, delta_parent, sha1, noeol, delta)
94
 
 
95
 
    def _add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
96
 
        """Class specific routine to add a delta.
97
 
 
98
 
        This generic version simply applies the delta to the delta_parent and
99
 
        then inserts it.
100
 
        """
101
 
        # strip annotation from delta
102
 
        new_delta = []
103
 
        for start, stop, delta_len, delta_lines in delta:
104
 
            new_delta.append((start, stop, delta_len, [text for origin, text in delta_lines]))
105
 
        if delta_parent is not None:
106
 
            parent_full = self.get_lines(delta_parent)
107
 
        else:
108
 
            parent_full = []
109
 
        new_full = self._apply_delta(parent_full, new_delta)
110
 
        # its impossible to have noeol on an empty file
111
 
        if noeol and new_full[-1][-1] == '\n':
112
 
            new_full[-1] = new_full[-1][:-1]
113
 
        self.add_lines(version_id, parents, new_full)
114
 
 
115
 
    def add_lines(self, version_id, parents, lines, parent_texts=None):
 
151
    def insert_record_stream(self, stream):
 
152
        """Insert a record stream into this versioned file.
 
153
 
 
154
        :param stream: A stream of records to insert. 
 
155
        :return: None
 
156
        :seealso VersionedFile.get_record_stream:
 
157
        """
 
158
        raise NotImplementedError
 
159
 
 
160
    def add_lines(self, version_id, parents, lines, parent_texts=None,
 
161
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
162
        check_content=True):
116
163
        """Add a single text on top of the versioned file.
117
164
 
118
165
        Must raise RevisionAlreadyPresent if the new version is
120
167
 
121
168
        Must raise RevisionNotPresent if any of the given parents are
122
169
        not present in file history.
 
170
 
 
171
        :param lines: A list of lines. Each line must be a bytestring. And all
 
172
            of them except the last must be terminated with \n and contain no
 
173
            other \n's. The last line may either contain no \n's or a single
 
174
            terminated \n. If the lines list does meet this constraint the add
 
175
            routine may error or may succeed - but you will be unable to read
 
176
            the data back accurately. (Checking the lines have been split
 
177
            correctly is expensive and extremely unlikely to catch bugs so it
 
178
            is not done at runtime unless check_content is True.)
123
179
        :param parent_texts: An optional dictionary containing the opaque 
124
 
             representations of some or all of the parents of 
125
 
             version_id to allow delta optimisations. 
126
 
             VERY IMPORTANT: the texts must be those returned
127
 
             by add_lines or data corruption can be caused.
128
 
        :return: An opaque representation of the inserted version which can be
129
 
                 provided back to future add_lines calls in the parent_texts
130
 
                 dictionary.
 
180
            representations of some or all of the parents of version_id to
 
181
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
 
182
            returned by add_lines or data corruption can be caused.
 
183
        :param left_matching_blocks: a hint about which areas are common
 
184
            between the text and its left-hand-parent.  The format is
 
185
            the SequenceMatcher.get_matching_blocks format.
 
186
        :param nostore_sha: Raise ExistingContent and do not add the lines to
 
187
            the versioned file if the digest of the lines matches this.
 
188
        :param random_id: If True a random id has been selected rather than
 
189
            an id determined by some deterministic process such as a converter
 
190
            from a foreign VCS. When True the backend may choose not to check
 
191
            for uniqueness of the resulting key within the versioned file, so
 
192
            this should only be done when the result is expected to be unique
 
193
            anyway.
 
194
        :param check_content: If True, the lines supplied are verified to be
 
195
            bytestrings that are correctly formed lines.
 
196
        :return: The text sha1, the number of bytes in the text, and an opaque
 
197
                 representation of the inserted version which can be provided
 
198
                 back to future add_lines calls in the parent_texts dictionary.
131
199
        """
132
200
        self._check_write_ok()
133
 
        return self._add_lines(version_id, parents, lines, parent_texts)
 
201
        return self._add_lines(version_id, parents, lines, parent_texts,
 
202
            left_matching_blocks, nostore_sha, random_id, check_content)
134
203
 
135
 
    def _add_lines(self, version_id, parents, lines, parent_texts):
 
204
    def _add_lines(self, version_id, parents, lines, parent_texts,
 
205
        left_matching_blocks, nostore_sha, random_id, check_content):
136
206
        """Helper to do the class specific add_lines."""
137
207
        raise NotImplementedError(self.add_lines)
138
208
 
139
209
    def add_lines_with_ghosts(self, version_id, parents, lines,
140
 
                              parent_texts=None):
 
210
        parent_texts=None, nostore_sha=None, random_id=False,
 
211
        check_content=True, left_matching_blocks=None):
141
212
        """Add lines to the versioned file, allowing ghosts to be present.
142
213
        
143
 
        This takes the same parameters as add_lines.
 
214
        This takes the same parameters as add_lines and returns the same.
144
215
        """
145
216
        self._check_write_ok()
146
217
        return self._add_lines_with_ghosts(version_id, parents, lines,
147
 
                                           parent_texts)
 
218
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
148
219
 
149
 
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
 
220
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
 
221
        nostore_sha, random_id, check_content, left_matching_blocks):
150
222
        """Helper to do class specific add_lines_with_ghosts."""
151
223
        raise NotImplementedError(self.add_lines_with_ghosts)
152
224
 
154
226
        """Check the versioned file for integrity."""
155
227
        raise NotImplementedError(self.check)
156
228
 
157
 
    def _check_write_ok(self):
158
 
        """Is the versioned file marked as 'finished' ? Raise if it is."""
159
 
        if self.finished:
160
 
            raise errors.OutSideTransaction()
161
 
        if self._access_mode != 'w':
162
 
            raise errors.ReadOnlyObjectDirtiedError(self)
163
 
 
164
 
    def clear_cache(self):
165
 
        """Remove any data cached in the versioned file object."""
166
 
 
167
 
    def clone_text(self, new_version_id, old_version_id, parents):
168
 
        """Add an identical text to old_version_id as new_version_id.
169
 
 
170
 
        Must raise RevisionNotPresent if the old version or any of the
171
 
        parents are not present in file history.
172
 
 
173
 
        Must raise RevisionAlreadyPresent if the new version is
174
 
        already present in file history."""
175
 
        self._check_write_ok()
176
 
        return self._clone_text(new_version_id, old_version_id, parents)
177
 
 
178
 
    def _clone_text(self, new_version_id, old_version_id, parents):
179
 
        """Helper function to do the _clone_text work."""
180
 
        raise NotImplementedError(self.clone_text)
181
 
 
182
 
    def create_empty(self, name, transport, mode=None):
183
 
        """Create a new versioned file of this exact type.
184
 
 
185
 
        :param name: the file name
186
 
        :param transport: the transport
187
 
        :param mode: optional file mode.
188
 
        """
189
 
        raise NotImplementedError(self.create_empty)
190
 
 
191
 
    def fix_parents(self, version, new_parents):
192
 
        """Fix the parents list for version.
193
 
        
194
 
        This is done by appending a new version to the index
195
 
        with identical data except for the parents list.
196
 
        the parents list must be a superset of the current
197
 
        list.
198
 
        """
199
 
        self._check_write_ok()
200
 
        return self._fix_parents(version, new_parents)
201
 
 
202
 
    def _fix_parents(self, version, new_parents):
203
 
        """Helper for fix_parents."""
204
 
        raise NotImplementedError(self.fix_parents)
205
 
 
206
 
    def get_delta(self, version):
207
 
        """Get a delta for constructing version from some other version.
208
 
        
209
 
        :return: (delta_parent, sha1, noeol, delta)
210
 
        Where delta_parent is a version id or None to indicate no parent.
211
 
        """
212
 
        raise NotImplementedError(self.get_delta)
213
 
 
214
 
    def get_deltas(self, versions):
215
 
        """Get multiple deltas at once for constructing versions.
216
 
        
217
 
        :return: dict(version_id:(delta_parent, sha1, noeol, delta))
218
 
        Where delta_parent is a version id or None to indicate no parent, and
219
 
        version_id is the version_id created by that delta.
220
 
        """
221
 
        result = {}
222
 
        for version in versions:
223
 
            result[version] = self.get_delta(version)
224
 
        return result
225
 
 
226
 
    def get_suffixes(self):
227
 
        """Return the file suffixes associated with this versioned file."""
228
 
        raise NotImplementedError(self.get_suffixes)
229
 
    
 
229
    def _check_lines_not_unicode(self, lines):
 
230
        """Check that lines being added to a versioned file are not unicode."""
 
231
        for line in lines:
 
232
            if line.__class__ is not str:
 
233
                raise errors.BzrBadParameterUnicode("lines")
 
234
 
 
235
    def _check_lines_are_lines(self, lines):
 
236
        """Check that the lines really are full lines without inline EOL."""
 
237
        for line in lines:
 
238
            if '\n' in line[:-1]:
 
239
                raise errors.BzrBadParameterContainsNewline("lines")
 
240
 
 
241
    def get_format_signature(self):
 
242
        """Get a text description of the data encoding in this file.
 
243
        
 
244
        :since: 0.90
 
245
        """
 
246
        raise NotImplementedError(self.get_format_signature)
 
247
 
 
248
    def make_mpdiffs(self, version_ids):
 
249
        """Create multiparent diffs for specified versions."""
 
250
        knit_versions = set()
 
251
        knit_versions.update(version_ids)
 
252
        parent_map = self.get_parent_map(version_ids)
 
253
        for version_id in version_ids:
 
254
            try:
 
255
                knit_versions.update(parent_map[version_id])
 
256
            except KeyError:
 
257
                raise RevisionNotPresent(version_id, self)
 
258
        # We need to filter out ghosts, because we can't diff against them.
 
259
        knit_versions = set(self.get_parent_map(knit_versions).keys())
 
260
        lines = dict(zip(knit_versions,
 
261
            self._get_lf_split_line_list(knit_versions)))
 
262
        diffs = []
 
263
        for version_id in version_ids:
 
264
            target = lines[version_id]
 
265
            try:
 
266
                parents = [lines[p] for p in parent_map[version_id] if p in
 
267
                    knit_versions]
 
268
            except KeyError:
 
269
                raise RevisionNotPresent(version_id, self)
 
270
            if len(parents) > 0:
 
271
                left_parent_blocks = self._extract_blocks(version_id,
 
272
                                                          parents[0], target)
 
273
            else:
 
274
                left_parent_blocks = None
 
275
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
 
276
                         left_parent_blocks))
 
277
        return diffs
 
278
 
 
279
    def _extract_blocks(self, version_id, source, target):
 
280
        return None
 
281
 
 
282
    def add_mpdiffs(self, records):
 
283
        """Add mpdiffs to this VersionedFile.
 
284
 
 
285
        Records should be iterables of version, parents, expected_sha1,
 
286
        mpdiff. mpdiff should be a MultiParent instance.
 
287
        """
 
288
        # Does this need to call self._check_write_ok()? (IanC 20070919)
 
289
        vf_parents = {}
 
290
        mpvf = multiparent.MultiMemoryVersionedFile()
 
291
        versions = []
 
292
        for version, parent_ids, expected_sha1, mpdiff in records:
 
293
            versions.append(version)
 
294
            mpvf.add_diff(mpdiff, version, parent_ids)
 
295
        needed_parents = set()
 
296
        for version, parent_ids, expected_sha1, mpdiff in records:
 
297
            needed_parents.update(p for p in parent_ids
 
298
                                  if not mpvf.has_version(p))
 
299
        present_parents = set(self.get_parent_map(needed_parents).keys())
 
300
        for parent_id, lines in zip(present_parents,
 
301
                                 self._get_lf_split_line_list(present_parents)):
 
302
            mpvf.add_version(lines, parent_id, [])
 
303
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
 
304
            zip(records, mpvf.get_line_list(versions)):
 
305
            if len(parent_ids) == 1:
 
306
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
 
307
                    mpvf.get_diff(parent_ids[0]).num_lines()))
 
308
            else:
 
309
                left_matching_blocks = None
 
310
            try:
 
311
                _, _, version_text = self.add_lines_with_ghosts(version,
 
312
                    parent_ids, lines, vf_parents,
 
313
                    left_matching_blocks=left_matching_blocks)
 
314
            except NotImplementedError:
 
315
                # The vf can't handle ghosts, so add lines normally, which will
 
316
                # (reasonably) fail if there are ghosts in the data.
 
317
                _, _, version_text = self.add_lines(version,
 
318
                    parent_ids, lines, vf_parents,
 
319
                    left_matching_blocks=left_matching_blocks)
 
320
            vf_parents[version] = version_text
 
321
        for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
 
322
             zip(records, self.get_sha1s(versions)):
 
323
            if expected_sha1 != sha1:
 
324
                raise errors.VersionedFileInvalidChecksum(version)
 
325
 
 
326
    def get_sha1s(self, version_ids):
 
327
        """Get the stored sha1 sums for the given revisions.
 
328
 
 
329
        :param version_ids: The names of the versions to lookup
 
330
        :return: a list of sha1s in order according to the version_ids
 
331
        """
 
332
        raise NotImplementedError(self.get_sha1s)
 
333
 
230
334
    def get_text(self, version_id):
231
335
        """Return version contents as a text string.
232
336
 
236
340
        return ''.join(self.get_lines(version_id))
237
341
    get_string = get_text
238
342
 
 
343
    def get_texts(self, version_ids):
 
344
        """Return the texts of listed versions as a list of strings.
 
345
 
 
346
        Raises RevisionNotPresent if version is not present in
 
347
        file history.
 
348
        """
 
349
        return [''.join(self.get_lines(v)) for v in version_ids]
 
350
 
239
351
    def get_lines(self, version_id):
240
352
        """Return version contents as a sequence of lines.
241
353
 
244
356
        """
245
357
        raise NotImplementedError(self.get_lines)
246
358
 
247
 
    def get_ancestry(self, version_ids):
 
359
    def _get_lf_split_line_list(self, version_ids):
 
360
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
 
361
 
 
362
    def get_ancestry(self, version_ids, topo_sorted=True):
248
363
        """Return a list of all ancestors of given version(s). This
249
364
        will not include the null revision.
250
365
 
 
366
        This list will not be topologically sorted if topo_sorted=False is
 
367
        passed.
 
368
 
251
369
        Must raise RevisionNotPresent if any of the given versions are
252
370
        not present in file history."""
253
371
        if isinstance(version_ids, basestring):
265
383
        but are not explicitly marked.
266
384
        """
267
385
        raise NotImplementedError(self.get_ancestry_with_ghosts)
268
 
        
269
 
    def get_graph(self):
270
 
        """Return a graph for the entire versioned file.
271
 
        
272
 
        Ghosts are not listed or referenced in the graph.
273
 
        """
274
 
        result = {}
275
 
        for version in self.versions():
276
 
            result[version] = self.get_parents(version)
277
 
        return result
278
 
 
279
 
    def get_graph_with_ghosts(self):
280
 
        """Return a graph for the entire versioned file.
281
 
        
282
 
        Ghosts are referenced in parents list but are not
283
 
        explicitly listed.
284
 
        """
285
 
        raise NotImplementedError(self.get_graph_with_ghosts)
286
 
 
287
 
    @deprecated_method(zero_eight)
288
 
    def parent_names(self, version):
289
 
        """Return version names for parents of a version.
290
 
        
291
 
        See get_parents for the current api.
292
 
        """
293
 
        return self.get_parents(version)
294
 
 
295
 
    def get_parents(self, version_id):
296
 
        """Return version names for parents of a version.
297
 
 
298
 
        Must raise RevisionNotPresent if version is not present in
299
 
        file history.
300
 
        """
301
 
        raise NotImplementedError(self.get_parents)
 
386
    
 
387
    def get_parent_map(self, version_ids):
 
388
        """Get a map of the parents of version_ids.
 
389
 
 
390
        :param version_ids: The version ids to look up parents for.
 
391
        :return: A mapping from version id to parents.
 
392
        """
 
393
        raise NotImplementedError(self.get_parent_map)
302
394
 
303
395
    def get_parents_with_ghosts(self, version_id):
304
396
        """Return version names for parents of version_id.
309
401
        Ghosts that are known about will be included in the parent list,
310
402
        but are not explicitly marked.
311
403
        """
312
 
        raise NotImplementedError(self.get_parents_with_ghosts)
313
 
 
314
 
    def annotate_iter(self, version_id):
315
 
        """Yield list of (version-id, line) pairs for the specified
316
 
        version.
317
 
 
318
 
        Must raise RevisionNotPresent if any of the given versions are
319
 
        not present in file history.
320
 
        """
321
 
        raise NotImplementedError(self.annotate_iter)
 
404
        try:
 
405
            return list(self.get_parent_map([version_id])[version_id])
 
406
        except KeyError:
 
407
            raise errors.RevisionNotPresent(version_id, self)
322
408
 
323
409
    def annotate(self, version_id):
324
 
        return list(self.annotate_iter(version_id))
325
 
 
326
 
    def _apply_delta(self, lines, delta):
327
 
        """Apply delta to lines."""
328
 
        lines = list(lines)
329
 
        offset = 0
330
 
        for start, end, count, delta_lines in delta:
331
 
            lines[offset+start:offset+end] = delta_lines
332
 
            offset = offset + (start - end) + count
333
 
        return lines
334
 
 
 
410
        """Return a list of (version-id, line) tuples for version_id.
 
411
 
 
412
        :raise RevisionNotPresent: If the given version is
 
413
        not present in file history.
 
414
        """
 
415
        raise NotImplementedError(self.annotate)
 
416
 
 
417
    @deprecated_method(one_five)
335
418
    def join(self, other, pb=None, msg=None, version_ids=None,
336
419
             ignore_missing=False):
337
420
        """Integrate versions from other into this versioned file.
340
423
        incorporated into this versioned file.
341
424
 
342
425
        Must raise RevisionNotPresent if any of the specified versions
343
 
        are not present in the other files history unless ignore_missing
344
 
        is supplied when they are silently skipped.
 
426
        are not present in the other file's history unless ignore_missing
 
427
        is supplied in which case they are silently skipped.
345
428
        """
346
429
        self._check_write_ok()
347
430
        return InterVersionedFile.get(other, self).join(
350
433
            version_ids,
351
434
            ignore_missing)
352
435
 
353
 
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
 
436
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
 
437
                                                pb=None):
354
438
        """Iterate over the lines in the versioned file from version_ids.
355
439
 
356
 
        This may return lines from other versions, and does not return the
357
 
        specific version marker at this point. The api may be changed
358
 
        during development to include the version that the versioned file
359
 
        thinks is relevant, but given that such hints are just guesses,
360
 
        its better not to have it if we dont need it.
 
440
        This may return lines from other versions. Each item the returned
 
441
        iterator yields is a tuple of a line and a text version that that line
 
442
        is present in (not introduced in).
 
443
 
 
444
        Ordering of results is in whatever order is most suitable for the
 
445
        underlying storage format.
 
446
 
 
447
        If a progress bar is supplied, it may be used to indicate progress.
 
448
        The caller is responsible for cleaning up progress bars (because this
 
449
        is an iterator).
361
450
 
362
451
        NOTES: Lines are normalised: they will all have \n terminators.
363
452
               Lines are returned in arbitrary order.
 
453
 
 
454
        :return: An iterator over (line, version_id).
364
455
        """
365
456
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
366
457
 
367
 
    def transaction_finished(self):
368
 
        """The transaction that this file was opened in has finished.
369
 
 
370
 
        This records self.finished = True and should cause all mutating
371
 
        operations to error.
372
 
        """
373
 
        self.finished = True
374
 
 
375
 
    @deprecated_method(zero_eight)
376
 
    def walk(self, version_ids=None):
377
 
        """Walk the versioned file as a weave-like structure, for
378
 
        versions relative to version_ids.  Yields sequence of (lineno,
379
 
        insert, deletes, text) for each relevant line.
380
 
 
381
 
        Must raise RevisionNotPresent if any of the specified versions
382
 
        are not present in the file history.
383
 
 
384
 
        :param version_ids: the version_ids to walk with respect to. If not
385
 
                            supplied the entire weave-like structure is walked.
386
 
 
387
 
        walk is deprecated in favour of iter_lines_added_or_present_in_versions
388
 
        """
389
 
        raise NotImplementedError(self.walk)
390
 
 
391
 
    @deprecated_method(zero_eight)
392
 
    def iter_names(self):
393
 
        """Walk the names list."""
394
 
        return iter(self.versions())
395
 
 
396
458
    def plan_merge(self, ver_a, ver_b):
397
459
        """Return pseudo-annotation indicating how the two versions merge.
398
460
 
400
462
        base.
401
463
 
402
464
        Weave lines present in none of them are skipped entirely.
403
 
        """
404
 
        inc_a = set(self.get_ancestry([ver_a]))
405
 
        inc_b = set(self.get_ancestry([ver_b]))
406
 
        inc_c = inc_a & inc_b
407
 
 
408
 
        for lineno, insert, deleteset, line in self.walk([ver_a, ver_b]):
409
 
            if deleteset & inc_c:
410
 
                # killed in parent; can't be in either a or b
411
 
                # not relevant to our work
412
 
                yield 'killed-base', line
413
 
            elif insert in inc_c:
414
 
                # was inserted in base
415
 
                killed_a = bool(deleteset & inc_a)
416
 
                killed_b = bool(deleteset & inc_b)
417
 
                if killed_a and killed_b:
418
 
                    yield 'killed-both', line
419
 
                elif killed_a:
420
 
                    yield 'killed-a', line
421
 
                elif killed_b:
422
 
                    yield 'killed-b', line
423
 
                else:
424
 
                    yield 'unchanged', line
425
 
            elif insert in inc_a:
426
 
                if deleteset & inc_a:
427
 
                    yield 'ghost-a', line
428
 
                else:
429
 
                    # new in A; not in B
430
 
                    yield 'new-a', line
431
 
            elif insert in inc_b:
432
 
                if deleteset & inc_b:
433
 
                    yield 'ghost-b', line
434
 
                else:
435
 
                    yield 'new-b', line
 
465
 
 
466
        Legend:
 
467
        killed-base Dead in base revision
 
468
        killed-both Killed in each revision
 
469
        killed-a    Killed in a
 
470
        killed-b    Killed in b
 
471
        unchanged   Alive in both a and b (possibly created in both)
 
472
        new-a       Created in a
 
473
        new-b       Created in b
 
474
        ghost-a     Killed in a, unborn in b    
 
475
        ghost-b     Killed in b, unborn in a
 
476
        irrelevant  Not in either revision
 
477
        """
 
478
        raise NotImplementedError(VersionedFile.plan_merge)
 
479
        
 
480
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
 
481
                    b_marker=TextMerge.B_MARKER):
 
482
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
 
483
 
 
484
 
 
485
class RecordingVersionedFileDecorator(object):
 
486
    """A minimal versioned file that records calls made on it.
 
487
    
 
488
    Only enough methods have been added to support tests using it to date.
 
489
 
 
490
    :ivar calls: A list of the calls made; can be reset at any time by
 
491
        assigning [] to it.
 
492
    """
 
493
 
 
494
    def __init__(self, backing_vf):
 
495
        """Create a RecordingVersionedFileDecorator decorating backing_vf.
 
496
        
 
497
        :param backing_vf: The versioned file to answer all methods.
 
498
        """
 
499
        self._backing_vf = backing_vf
 
500
        self.calls = []
 
501
 
 
502
    def get_lines(self, version_ids):
 
503
        self.calls.append(("get_lines", version_ids))
 
504
        return self._backing_vf.get_lines(version_ids)
 
505
 
 
506
 
 
507
class _PlanMergeVersionedFile(object):
 
508
    """A VersionedFile for uncommitted and committed texts.
 
509
 
 
510
    It is intended to allow merges to be planned with working tree texts.
 
511
    It implements only the small part of the VersionedFile interface used by
 
512
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
 
513
    _PlanMergeVersionedFile itself.
 
514
    """
 
515
 
 
516
    def __init__(self, file_id, fallback_versionedfiles=None):
 
517
        """Constuctor
 
518
 
 
519
        :param file_id: Used when raising exceptions.
 
520
        :param fallback_versionedfiles: If supplied, the set of fallbacks to
 
521
            use.  Otherwise, _PlanMergeVersionedFile.fallback_versionedfiles
 
522
            can be appended to later.
 
523
        """
 
524
        self._file_id = file_id
 
525
        if fallback_versionedfiles is None:
 
526
            self.fallback_versionedfiles = []
 
527
        else:
 
528
            self.fallback_versionedfiles = fallback_versionedfiles
 
529
        self._parents = {}
 
530
        self._lines = {}
 
531
 
 
532
    def plan_merge(self, ver_a, ver_b, base=None):
 
533
        """See VersionedFile.plan_merge"""
 
534
        from bzrlib.merge import _PlanMerge
 
535
        if base is None:
 
536
            return _PlanMerge(ver_a, ver_b, self).plan_merge()
 
537
        old_plan = list(_PlanMerge(ver_a, base, self).plan_merge())
 
538
        new_plan = list(_PlanMerge(ver_a, ver_b, self).plan_merge())
 
539
        return _PlanMerge._subtract_plans(old_plan, new_plan)
 
540
 
 
541
    def plan_lca_merge(self, ver_a, ver_b, base=None):
 
542
        from bzrlib.merge import _PlanLCAMerge
 
543
        graph = self._get_graph()
 
544
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, graph).plan_merge()
 
545
        if base is None:
 
546
            return new_plan
 
547
        old_plan = _PlanLCAMerge(ver_a, base, self, graph).plan_merge()
 
548
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
 
549
 
 
550
    def add_lines(self, version_id, parents, lines):
 
551
        """See VersionedFile.add_lines
 
552
 
 
553
        Lines are added locally, not fallback versionedfiles.  Also, ghosts are
 
554
        permitted.  Only reserved ids are permitted.
 
555
        """
 
556
        if not revision.is_reserved_id(version_id):
 
557
            raise ValueError('Only reserved ids may be used')
 
558
        if parents is None:
 
559
            raise ValueError('Parents may not be None')
 
560
        if lines is None:
 
561
            raise ValueError('Lines may not be None')
 
562
        self._parents[version_id] = tuple(parents)
 
563
        self._lines[version_id] = lines
 
564
 
 
565
    def get_lines(self, version_id):
 
566
        """See VersionedFile.get_ancestry"""
 
567
        lines = self._lines.get(version_id)
 
568
        if lines is not None:
 
569
            return lines
 
570
        for versionedfile in self.fallback_versionedfiles:
 
571
            try:
 
572
                return versionedfile.get_lines(version_id)
 
573
            except errors.RevisionNotPresent:
 
574
                continue
 
575
        else:
 
576
            raise errors.RevisionNotPresent(version_id, self._file_id)
 
577
 
 
578
    def get_ancestry(self, version_id, topo_sorted=False):
 
579
        """See VersionedFile.get_ancestry.
 
580
 
 
581
        Note that this implementation assumes that if a VersionedFile can
 
582
        answer get_ancestry at all, it can give an authoritative answer.  In
 
583
        fact, ghosts can invalidate this assumption.  But it's good enough
 
584
        99% of the time, and far cheaper/simpler.
 
585
 
 
586
        Also note that the results of this version are never topologically
 
587
        sorted, and are a set.
 
588
        """
 
589
        if topo_sorted:
 
590
            raise ValueError('This implementation does not provide sorting')
 
591
        parents = self._parents.get(version_id)
 
592
        if parents is None:
 
593
            for vf in self.fallback_versionedfiles:
 
594
                try:
 
595
                    return vf.get_ancestry(version_id, topo_sorted=False)
 
596
                except errors.RevisionNotPresent:
 
597
                    continue
436
598
            else:
437
 
                # not in either revision
438
 
                yield 'irrelevant', line
439
 
 
440
 
        yield 'unchanged', ''           # terminator
441
 
 
442
 
    def weave_merge(self, plan, a_marker='<<<<<<< \n', b_marker='>>>>>>> \n'):
 
599
                raise errors.RevisionNotPresent(version_id, self._file_id)
 
600
        ancestry = set([version_id])
 
601
        for parent in parents:
 
602
            ancestry.update(self.get_ancestry(parent, topo_sorted=False))
 
603
        return ancestry
 
604
 
 
605
    def get_parent_map(self, version_ids):
 
606
        """See VersionedFile.get_parent_map"""
 
607
        result = {}
 
608
        pending = set(version_ids)
 
609
        for key in version_ids:
 
610
            try:
 
611
                result[key] = self._parents[key]
 
612
            except KeyError:
 
613
                pass
 
614
        pending = pending - set(result.keys())
 
615
        for versionedfile in self.fallback_versionedfiles:
 
616
            parents = versionedfile.get_parent_map(pending)
 
617
            result.update(parents)
 
618
            pending = pending - set(parents.keys())
 
619
            if not pending:
 
620
                return result
 
621
        return result
 
622
 
 
623
    def _get_graph(self):
 
624
        from bzrlib.graph import (
 
625
            DictParentsProvider,
 
626
            Graph,
 
627
            _StackedParentsProvider,
 
628
            )
 
629
        from bzrlib.repofmt.knitrepo import _KnitParentsProvider
 
630
        parent_providers = [DictParentsProvider(self._parents)]
 
631
        for vf in self.fallback_versionedfiles:
 
632
            parent_providers.append(_KnitParentsProvider(vf))
 
633
        return Graph(_StackedParentsProvider(parent_providers))
 
634
 
 
635
 
 
636
class PlanWeaveMerge(TextMerge):
 
637
    """Weave merge that takes a plan as its input.
 
638
    
 
639
    This exists so that VersionedFile.plan_merge is implementable.
 
640
    Most callers will want to use WeaveMerge instead.
 
641
    """
 
642
 
 
643
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
 
644
                 b_marker=TextMerge.B_MARKER):
 
645
        TextMerge.__init__(self, a_marker, b_marker)
 
646
        self.plan = plan
 
647
 
 
648
    def _merge_struct(self):
443
649
        lines_a = []
444
650
        lines_b = []
445
651
        ch_a = ch_b = False
446
 
        # TODO: Return a structured form of the conflicts (e.g. 2-tuples for
447
 
        # conflicted regions), rather than just inserting the markers.
448
 
        # 
449
 
        # TODO: Show some version information (e.g. author, date) on 
450
 
        # conflicted regions.
451
 
        
 
652
 
 
653
        def outstanding_struct():
 
654
            if not lines_a and not lines_b:
 
655
                return
 
656
            elif ch_a and not ch_b:
 
657
                # one-sided change:
 
658
                yield(lines_a,)
 
659
            elif ch_b and not ch_a:
 
660
                yield (lines_b,)
 
661
            elif lines_a == lines_b:
 
662
                yield(lines_a,)
 
663
            else:
 
664
                yield (lines_a, lines_b)
 
665
       
452
666
        # We previously considered either 'unchanged' or 'killed-both' lines
453
667
        # to be possible places to resynchronize.  However, assuming agreement
454
 
        # on killed-both lines may be too agressive. -- mbp 20060324
455
 
        for state, line in plan:
 
668
        # on killed-both lines may be too aggressive. -- mbp 20060324
 
669
        for state, line in self.plan:
456
670
            if state == 'unchanged':
457
671
                # resync and flush queued conflicts changes if any
458
 
                if not lines_a and not lines_b:
459
 
                    pass
460
 
                elif ch_a and not ch_b:
461
 
                    # one-sided change:                    
462
 
                    for l in lines_a: yield l
463
 
                elif ch_b and not ch_a:
464
 
                    for l in lines_b: yield l
465
 
                elif lines_a == lines_b:
466
 
                    for l in lines_a: yield l
467
 
                else:
468
 
                    yield a_marker
469
 
                    for l in lines_a: yield l
470
 
                    yield '=======\n'
471
 
                    for l in lines_b: yield l
472
 
                    yield b_marker
473
 
 
474
 
                del lines_a[:]
475
 
                del lines_b[:]
 
672
                for struct in outstanding_struct():
 
673
                    yield struct
 
674
                lines_a = []
 
675
                lines_b = []
476
676
                ch_a = ch_b = False
477
677
                
478
678
            if state == 'unchanged':
479
679
                if line:
480
 
                    yield line
 
680
                    yield ([line],)
481
681
            elif state == 'killed-a':
482
682
                ch_a = True
483
683
                lines_b.append(line)
490
690
            elif state == 'new-b':
491
691
                ch_b = True
492
692
                lines_b.append(line)
 
693
            elif state == 'conflicted-a':
 
694
                ch_b = ch_a = True
 
695
                lines_a.append(line)
 
696
            elif state == 'conflicted-b':
 
697
                ch_b = ch_a = True
 
698
                lines_b.append(line)
493
699
            else:
494
 
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 'killed-base',
495
 
                                 'killed-both'), \
496
 
                       state
 
700
                if state not in ('irrelevant', 'ghost-a', 'ghost-b',
 
701
                        'killed-base', 'killed-both'):
 
702
                    raise AssertionError(state)
 
703
        for struct in outstanding_struct():
 
704
            yield struct
 
705
 
 
706
 
 
707
class WeaveMerge(PlanWeaveMerge):
 
708
    """Weave merge that takes a VersionedFile and two versions as its input."""
 
709
 
 
710
    def __init__(self, versionedfile, ver_a, ver_b, 
 
711
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
 
712
        plan = versionedfile.plan_merge(ver_a, ver_b)
 
713
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
497
714
 
498
715
 
499
716
class InterVersionedFile(InterObject):
500
 
    """This class represents operations taking place between two versionedfiles..
 
717
    """This class represents operations taking place between two VersionedFiles.
501
718
 
502
719
    Its instances have methods like join, and contain
503
720
    references to the source and target versionedfiles these operations can be 
508
725
    InterVersionedFile.get(other).method_name(parameters).
509
726
    """
510
727
 
511
 
    _optimisers = set()
 
728
    _optimisers = []
512
729
    """The available optimised InterVersionedFile types."""
513
730
 
514
731
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
518
735
        incorporated into this versioned file.
519
736
 
520
737
        Must raise RevisionNotPresent if any of the specified versions
521
 
        are not present in the other files history unless ignore_missing is 
522
 
        supplied when they are silently skipped.
 
738
        are not present in the other file's history unless ignore_missing is 
 
739
        supplied in which case they are silently skipped.
523
740
        """
524
 
        # the default join: 
525
 
        # - if the target is empty, just add all the versions from 
526
 
        #   source to target, otherwise:
527
 
        # - make a temporary versioned file of type target
528
 
        # - insert the source content into it one at a time
529
 
        # - join them
530
 
        if not self.target.versions():
531
 
            target = self.target
532
 
        else:
533
 
            # Make a new target-format versioned file. 
534
 
            temp_source = self.target.create_empty("temp", MemoryTransport())
535
 
            target = temp_source
536
 
        graph = self.source.get_graph()
537
 
        order = topo_sort(graph.items())
 
741
        target = self.target
 
742
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
 
743
        graph = Graph(self.source)
 
744
        search = graph._make_breadth_first_searcher(version_ids)
 
745
        transitive_ids = set()
 
746
        map(transitive_ids.update, list(search))
 
747
        parent_map = self.source.get_parent_map(transitive_ids)
 
748
        order = tsort.topo_sort(parent_map.items())
538
749
        pb = ui.ui_factory.nested_progress_bar()
539
750
        parent_texts = {}
540
751
        try:
551
762
            # TODO: remove parent texts when they are not relevant any more for 
552
763
            # memory pressure reduction. RBC 20060313
553
764
            # pb.update('Converting versioned data', 0, len(order))
554
 
            # deltas = self.source.get_deltas(order)
 
765
            total = len(order)
555
766
            for index, version in enumerate(order):
556
 
                pb.update('Converting versioned data', index, len(order))
557
 
                parent_text = target.add_lines(version,
558
 
                                               self.source.get_parents(version),
 
767
                pb.update('Converting versioned data', index, total)
 
768
                if version in target:
 
769
                    continue
 
770
                _, _, parent_text = target.add_lines(version,
 
771
                                               parent_map[version],
559
772
                                               self.source.get_lines(version),
560
773
                                               parent_texts=parent_texts)
561
774
                parent_texts[version] = parent_text
562
 
                #delta_parent, sha1, noeol, delta = deltas[version]
563
 
                #target.add_delta(version,
564
 
                #                 self.source.get_parents(version),
565
 
                #                 delta_parent,
566
 
                #                 sha1,
567
 
                #                 noeol,
568
 
                #                 delta)
569
 
                #target.get_lines(version)
570
 
            
571
 
            # this should hit the native code path for target
572
 
            if target is not self.target:
573
 
                return self.target.join(temp_source,
574
 
                                        pb,
575
 
                                        msg,
576
 
                                        version_ids,
577
 
                                        ignore_missing)
 
775
            return total
578
776
        finally:
579
777
            pb.finished()
580
778
 
581
 
 
582
 
class InterVersionedFileTestProviderAdapter(object):
583
 
    """A tool to generate a suite testing multiple inter versioned-file classes.
584
 
 
585
 
    This is done by copying the test once for each interversionedfile provider
586
 
    and injecting the transport_server, transport_readonly_server,
587
 
    versionedfile_factory and versionedfile_factory_to classes into each copy.
588
 
    Each copy is also given a new id() to make it easy to identify.
589
 
    """
590
 
 
591
 
    def __init__(self, transport_server, transport_readonly_server, formats):
592
 
        self._transport_server = transport_server
593
 
        self._transport_readonly_server = transport_readonly_server
594
 
        self._formats = formats
595
 
    
596
 
    def adapt(self, test):
597
 
        result = TestSuite()
598
 
        for (interversionedfile_class,
599
 
             versionedfile_factory,
600
 
             versionedfile_factory_to) in self._formats:
601
 
            new_test = deepcopy(test)
602
 
            new_test.transport_server = self._transport_server
603
 
            new_test.transport_readonly_server = self._transport_readonly_server
604
 
            new_test.interversionedfile_class = interversionedfile_class
605
 
            new_test.versionedfile_factory = versionedfile_factory
606
 
            new_test.versionedfile_factory_to = versionedfile_factory_to
607
 
            def make_new_test_id():
608
 
                new_id = "%s(%s)" % (new_test.id(), interversionedfile_class.__name__)
609
 
                return lambda: new_id
610
 
            new_test.id = make_new_test_id()
611
 
            result.addTest(new_test)
612
 
        return result
613
 
 
614
 
    @staticmethod
615
 
    def default_test_list():
616
 
        """Generate the default list of interversionedfile permutations to test."""
617
 
        from bzrlib.weave import WeaveFile
618
 
        from bzrlib.knit import KnitVersionedFile
619
 
        result = []
620
 
        # test the fallback InterVersionedFile from weave to annotated knits
621
 
        result.append((InterVersionedFile, 
622
 
                       WeaveFile,
623
 
                       KnitVersionedFile))
624
 
        for optimiser in InterVersionedFile._optimisers:
625
 
            result.append((optimiser,
626
 
                           optimiser._matching_file_factory,
627
 
                           optimiser._matching_file_factory
628
 
                           ))
629
 
        # if there are specific combinations we want to use, we can add them 
630
 
        # here.
631
 
        return result
 
779
    def _get_source_version_ids(self, version_ids, ignore_missing):
 
780
        """Determine the version ids to be used from self.source.
 
781
 
 
782
        :param version_ids: The caller-supplied version ids to check. (None 
 
783
                            for all). If None is in version_ids, it is stripped.
 
784
        :param ignore_missing: if True, remove missing ids from the version 
 
785
                               list. If False, raise RevisionNotPresent on
 
786
                               a missing version id.
 
787
        :return: A set of version ids.
 
788
        """
 
789
        if version_ids is None:
 
790
            # None cannot be in source.versions
 
791
            return set(self.source.versions())
 
792
        else:
 
793
            if ignore_missing:
 
794
                return set(self.source.versions()).intersection(set(version_ids))
 
795
            else:
 
796
                new_version_ids = set()
 
797
                for version in version_ids:
 
798
                    if version is None:
 
799
                        continue
 
800
                    if not self.source.has_version(version):
 
801
                        raise errors.RevisionNotPresent(version, str(self.source))
 
802
                    else:
 
803
                        new_version_ids.add(version)
 
804
                return new_version_ids