/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: Robert Collins
  • Date: 2008-04-08 00:57:07 UTC
  • mto: This revision was merged to the branch mainline in revision 3350.
  • Revision ID: robertc@robertcollins.net-20080408005707-jzx5nkcjvsiw7r12
 * ``VersionedFileStore`` no longer uses the transaction parameter given
   to most methods; amongst other things this means that the
   get_weave_or_empty method no longer guarantees errors on a missing weave
   in a readonly transaction, and no longer caches versioned file instances
   which reduces memory pressure (but requires more careful management by
   callers to preserve performance.  (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
#
 
3
# Authors:
 
4
#   Johan Rydberg <jrydberg@gnu.org>
 
5
#
 
6
# This program is free software; you can redistribute it and/or modify
 
7
# it under the terms of the GNU General Public License as published by
 
8
# the Free Software Foundation; either version 2 of the License, or
 
9
# (at your option) any later version.
 
10
#
 
11
# This program is distributed in the hope that it will be useful,
 
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
# GNU General Public License for more details.
 
15
#
 
16
# You should have received a copy of the GNU General Public License
 
17
# along with this program; if not, write to the Free Software
 
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
19
 
 
20
"""Versioned text file storage api."""
 
21
 
 
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
 
 
39
from bzrlib.inter import InterObject
 
40
from bzrlib.symbol_versioning import *
 
41
from bzrlib.textmerge import TextMerge
 
42
 
 
43
 
 
44
class VersionedFile(object):
 
45
    """Versioned text file storage.
 
46
    
 
47
    A versioned file manages versions of line-based text files,
 
48
    keeping track of the originating version for each line.
 
49
 
 
50
    To clients the "lines" of the file are represented as a list of
 
51
    strings. These strings will typically have terminal newline
 
52
    characters, but this is not required.  In particular files commonly
 
53
    do not have a newline at the end of the file.
 
54
 
 
55
    Texts are identified by a version-id string.
 
56
    """
 
57
 
 
58
    @staticmethod
 
59
    def check_not_reserved_id(version_id):
 
60
        revision.check_not_reserved_id(version_id)
 
61
 
 
62
    def copy_to(self, name, transport):
 
63
        """Copy this versioned file to name on transport."""
 
64
        raise NotImplementedError(self.copy_to)
 
65
 
 
66
    def versions(self):
 
67
        """Return a unsorted list of versions."""
 
68
        raise NotImplementedError(self.versions)
 
69
 
 
70
    @deprecated_method(one_four)
 
71
    def has_ghost(self, version_id):
 
72
        """Returns whether version is present as a ghost."""
 
73
        raise NotImplementedError(self.has_ghost)
 
74
 
 
75
    def has_version(self, version_id):
 
76
        """Returns whether version is present."""
 
77
        raise NotImplementedError(self.has_version)
 
78
 
 
79
    def add_lines(self, version_id, parents, lines, parent_texts=None,
 
80
        left_matching_blocks=None, nostore_sha=None, random_id=False,
 
81
        check_content=True):
 
82
        """Add a single text on top of the versioned file.
 
83
 
 
84
        Must raise RevisionAlreadyPresent if the new version is
 
85
        already present in file history.
 
86
 
 
87
        Must raise RevisionNotPresent if any of the given parents are
 
88
        not present in file history.
 
89
 
 
90
        :param lines: A list of lines. Each line must be a bytestring. And all
 
91
            of them except the last must be terminated with \n and contain no
 
92
            other \n's. The last line may either contain no \n's or a single
 
93
            terminated \n. If the lines list does meet this constraint the add
 
94
            routine may error or may succeed - but you will be unable to read
 
95
            the data back accurately. (Checking the lines have been split
 
96
            correctly is expensive and extremely unlikely to catch bugs so it
 
97
            is not done at runtime unless check_content is True.)
 
98
        :param parent_texts: An optional dictionary containing the opaque 
 
99
            representations of some or all of the parents of version_id to
 
100
            allow delta optimisations.  VERY IMPORTANT: the texts must be those
 
101
            returned by add_lines or data corruption can be caused.
 
102
        :param left_matching_blocks: a hint about which areas are common
 
103
            between the text and its left-hand-parent.  The format is
 
104
            the SequenceMatcher.get_matching_blocks format.
 
105
        :param nostore_sha: Raise ExistingContent and do not add the lines to
 
106
            the versioned file if the digest of the lines matches this.
 
107
        :param random_id: If True a random id has been selected rather than
 
108
            an id determined by some deterministic process such as a converter
 
109
            from a foreign VCS. When True the backend may choose not to check
 
110
            for uniqueness of the resulting key within the versioned file, so
 
111
            this should only be done when the result is expected to be unique
 
112
            anyway.
 
113
        :param check_content: If True, the lines supplied are verified to be
 
114
            bytestrings that are correctly formed lines.
 
115
        :return: The text sha1, the number of bytes in the text, and an opaque
 
116
                 representation of the inserted version which can be provided
 
117
                 back to future add_lines calls in the parent_texts dictionary.
 
118
        """
 
119
        self._check_write_ok()
 
120
        return self._add_lines(version_id, parents, lines, parent_texts,
 
121
            left_matching_blocks, nostore_sha, random_id, check_content)
 
122
 
 
123
    def _add_lines(self, version_id, parents, lines, parent_texts,
 
124
        left_matching_blocks, nostore_sha, random_id, check_content):
 
125
        """Helper to do the class specific add_lines."""
 
126
        raise NotImplementedError(self.add_lines)
 
127
 
 
128
    def add_lines_with_ghosts(self, version_id, parents, lines,
 
129
        parent_texts=None, nostore_sha=None, random_id=False,
 
130
        check_content=True, left_matching_blocks=None):
 
131
        """Add lines to the versioned file, allowing ghosts to be present.
 
132
        
 
133
        This takes the same parameters as add_lines and returns the same.
 
134
        """
 
135
        self._check_write_ok()
 
136
        return self._add_lines_with_ghosts(version_id, parents, lines,
 
137
            parent_texts, nostore_sha, random_id, check_content, left_matching_blocks)
 
138
 
 
139
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts,
 
140
        nostore_sha, random_id, check_content, left_matching_blocks):
 
141
        """Helper to do class specific add_lines_with_ghosts."""
 
142
        raise NotImplementedError(self.add_lines_with_ghosts)
 
143
 
 
144
    def check(self, progress_bar=None):
 
145
        """Check the versioned file for integrity."""
 
146
        raise NotImplementedError(self.check)
 
147
 
 
148
    def _check_lines_not_unicode(self, lines):
 
149
        """Check that lines being added to a versioned file are not unicode."""
 
150
        for line in lines:
 
151
            if line.__class__ is not str:
 
152
                raise errors.BzrBadParameterUnicode("lines")
 
153
 
 
154
    def _check_lines_are_lines(self, lines):
 
155
        """Check that the lines really are full lines without inline EOL."""
 
156
        for line in lines:
 
157
            if '\n' in line[:-1]:
 
158
                raise errors.BzrBadParameterContainsNewline("lines")
 
159
 
 
160
    def enable_cache(self):
 
161
        """Tell this versioned file that it should cache any data it reads.
 
162
        
 
163
        This is advisory, implementations do not have to support caching.
 
164
        """
 
165
        pass
 
166
    
 
167
    def clear_cache(self):
 
168
        """Remove any data cached in the versioned file object.
 
169
 
 
170
        This only needs to be supported if caches are supported
 
171
        """
 
172
        pass
 
173
 
 
174
    def clone_text(self, new_version_id, old_version_id, parents):
 
175
        """Add an identical text to old_version_id as new_version_id.
 
176
 
 
177
        Must raise RevisionNotPresent if the old version or any of the
 
178
        parents are not present in file history.
 
179
 
 
180
        Must raise RevisionAlreadyPresent if the new version is
 
181
        already present in file history."""
 
182
        self._check_write_ok()
 
183
        return self._clone_text(new_version_id, old_version_id, parents)
 
184
 
 
185
    def _clone_text(self, new_version_id, old_version_id, parents):
 
186
        """Helper function to do the _clone_text work."""
 
187
        raise NotImplementedError(self.clone_text)
 
188
 
 
189
    def get_format_signature(self):
 
190
        """Get a text description of the data encoding in this file.
 
191
        
 
192
        :since: 0.90
 
193
        """
 
194
        raise NotImplementedError(self.get_format_signature)
 
195
 
 
196
    def make_mpdiffs(self, version_ids):
 
197
        """Create multiparent diffs for specified versions."""
 
198
        knit_versions = set()
 
199
        knit_versions.update(version_ids)
 
200
        parent_map = self.get_parent_map(version_ids)
 
201
        for version_id in version_ids:
 
202
            try:
 
203
                knit_versions.update(parent_map[version_id])
 
204
            except KeyError:
 
205
                raise RevisionNotPresent(version_id, self)
 
206
        # We need to filter out ghosts, because we can't diff against them.
 
207
        knit_versions = set(self.get_parent_map(knit_versions).keys())
 
208
        lines = dict(zip(knit_versions,
 
209
            self._get_lf_split_line_list(knit_versions)))
 
210
        diffs = []
 
211
        for version_id in version_ids:
 
212
            target = lines[version_id]
 
213
            try:
 
214
                parents = [lines[p] for p in parent_map[version_id] if p in
 
215
                    knit_versions]
 
216
            except KeyError:
 
217
                raise RevisionNotPresent(version_id, self)
 
218
            if len(parents) > 0:
 
219
                left_parent_blocks = self._extract_blocks(version_id,
 
220
                                                          parents[0], target)
 
221
            else:
 
222
                left_parent_blocks = None
 
223
            diffs.append(multiparent.MultiParent.from_lines(target, parents,
 
224
                         left_parent_blocks))
 
225
        return diffs
 
226
 
 
227
    def _extract_blocks(self, version_id, source, target):
 
228
        return None
 
229
 
 
230
    def add_mpdiffs(self, records):
 
231
        """Add mpdiffs to this VersionedFile.
 
232
 
 
233
        Records should be iterables of version, parents, expected_sha1,
 
234
        mpdiff. mpdiff should be a MultiParent instance.
 
235
        """
 
236
        # Does this need to call self._check_write_ok()? (IanC 20070919)
 
237
        vf_parents = {}
 
238
        mpvf = multiparent.MultiMemoryVersionedFile()
 
239
        versions = []
 
240
        for version, parent_ids, expected_sha1, mpdiff in records:
 
241
            versions.append(version)
 
242
            mpvf.add_diff(mpdiff, version, parent_ids)
 
243
        needed_parents = set()
 
244
        for version, parent_ids, expected_sha1, mpdiff in records:
 
245
            needed_parents.update(p for p in parent_ids
 
246
                                  if not mpvf.has_version(p))
 
247
        present_parents = set(self.get_parent_map(needed_parents).keys())
 
248
        for parent_id, lines in zip(present_parents,
 
249
                                 self._get_lf_split_line_list(present_parents)):
 
250
            mpvf.add_version(lines, parent_id, [])
 
251
        for (version, parent_ids, expected_sha1, mpdiff), lines in\
 
252
            zip(records, mpvf.get_line_list(versions)):
 
253
            if len(parent_ids) == 1:
 
254
                left_matching_blocks = list(mpdiff.get_matching_blocks(0,
 
255
                    mpvf.get_diff(parent_ids[0]).num_lines()))
 
256
            else:
 
257
                left_matching_blocks = None
 
258
            try:
 
259
                _, _, version_text = self.add_lines_with_ghosts(version,
 
260
                    parent_ids, lines, vf_parents,
 
261
                    left_matching_blocks=left_matching_blocks)
 
262
            except NotImplementedError:
 
263
                # The vf can't handle ghosts, so add lines normally, which will
 
264
                # (reasonably) fail if there are ghosts in the data.
 
265
                _, _, version_text = self.add_lines(version,
 
266
                    parent_ids, lines, vf_parents,
 
267
                    left_matching_blocks=left_matching_blocks)
 
268
            vf_parents[version] = version_text
 
269
        for (version, parent_ids, expected_sha1, mpdiff), sha1 in\
 
270
             zip(records, self.get_sha1s(versions)):
 
271
            if expected_sha1 != sha1:
 
272
                raise errors.VersionedFileInvalidChecksum(version)
 
273
 
 
274
    def get_sha1(self, version_id):
 
275
        """Get the stored sha1 sum for the given revision.
 
276
        
 
277
        :param version_id: The name of the version to lookup
 
278
        """
 
279
        raise NotImplementedError(self.get_sha1)
 
280
 
 
281
    def get_sha1s(self, version_ids):
 
282
        """Get the stored sha1 sums for the given revisions.
 
283
 
 
284
        :param version_ids: The names of the versions to lookup
 
285
        :return: a list of sha1s in order according to the version_ids
 
286
        """
 
287
        raise NotImplementedError(self.get_sha1s)
 
288
 
 
289
    def get_text(self, version_id):
 
290
        """Return version contents as a text string.
 
291
 
 
292
        Raises RevisionNotPresent if version is not present in
 
293
        file history.
 
294
        """
 
295
        return ''.join(self.get_lines(version_id))
 
296
    get_string = get_text
 
297
 
 
298
    def get_texts(self, version_ids):
 
299
        """Return the texts of listed versions as a list of strings.
 
300
 
 
301
        Raises RevisionNotPresent if version is not present in
 
302
        file history.
 
303
        """
 
304
        return [''.join(self.get_lines(v)) for v in version_ids]
 
305
 
 
306
    def get_lines(self, version_id):
 
307
        """Return version contents as a sequence of lines.
 
308
 
 
309
        Raises RevisionNotPresent if version is not present in
 
310
        file history.
 
311
        """
 
312
        raise NotImplementedError(self.get_lines)
 
313
 
 
314
    def _get_lf_split_line_list(self, version_ids):
 
315
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
 
316
 
 
317
    def get_ancestry(self, version_ids, topo_sorted=True):
 
318
        """Return a list of all ancestors of given version(s). This
 
319
        will not include the null revision.
 
320
 
 
321
        This list will not be topologically sorted if topo_sorted=False is
 
322
        passed.
 
323
 
 
324
        Must raise RevisionNotPresent if any of the given versions are
 
325
        not present in file history."""
 
326
        if isinstance(version_ids, basestring):
 
327
            version_ids = [version_ids]
 
328
        raise NotImplementedError(self.get_ancestry)
 
329
        
 
330
    def get_ancestry_with_ghosts(self, version_ids):
 
331
        """Return a list of all ancestors of given version(s). This
 
332
        will not include the null revision.
 
333
 
 
334
        Must raise RevisionNotPresent if any of the given versions are
 
335
        not present in file history.
 
336
        
 
337
        Ghosts that are known about will be included in ancestry list,
 
338
        but are not explicitly marked.
 
339
        """
 
340
        raise NotImplementedError(self.get_ancestry_with_ghosts)
 
341
        
 
342
    def get_graph(self, version_ids=None):
 
343
        """Return a graph from the versioned file. 
 
344
        
 
345
        Ghosts are not listed or referenced in the graph.
 
346
        :param version_ids: Versions to select.
 
347
                            None means retrieve all versions.
 
348
        """
 
349
        if version_ids is None:
 
350
            return dict(self.iter_parents(self.versions()))
 
351
        result = {}
 
352
        pending = set(version_ids)
 
353
        while pending:
 
354
            this_iteration = pending
 
355
            pending = set()
 
356
            for version, parents in self.iter_parents(this_iteration):
 
357
                result[version] = parents
 
358
                for parent in parents:
 
359
                    if parent in result:
 
360
                        continue
 
361
                    pending.add(parent)
 
362
        return result
 
363
 
 
364
    @deprecated_method(one_four)
 
365
    def get_graph_with_ghosts(self):
 
366
        """Return a graph for the entire versioned file.
 
367
        
 
368
        Ghosts are referenced in parents list but are not
 
369
        explicitly listed.
 
370
        """
 
371
        raise NotImplementedError(self.get_graph_with_ghosts)
 
372
 
 
373
    def get_parent_map(self, version_ids):
 
374
        """Get a map of the parents of version_ids.
 
375
 
 
376
        :param version_ids: The version ids to look up parents for.
 
377
        :return: A mapping from version id to parents.
 
378
        """
 
379
        raise NotImplementedError(self.get_parent_map)
 
380
 
 
381
    @deprecated_method(one_four)
 
382
    def get_parents(self, version_id):
 
383
        """Return version names for parents of a version.
 
384
 
 
385
        Must raise RevisionNotPresent if version is not present in
 
386
        file history.
 
387
        """
 
388
        try:
 
389
            all = self.get_parent_map([version_id])[version_id]
 
390
        except KeyError:
 
391
            raise errors.RevisionNotPresent(version_id, self)
 
392
        result = []
 
393
        parent_parents = self.get_parent_map(all)
 
394
        for version_id in all:
 
395
            if version_id in parent_parents:
 
396
                result.append(version_id)
 
397
        return result
 
398
 
 
399
    def get_parents_with_ghosts(self, version_id):
 
400
        """Return version names for parents of version_id.
 
401
 
 
402
        Will raise RevisionNotPresent if version_id is not present
 
403
        in the history.
 
404
 
 
405
        Ghosts that are known about will be included in the parent list,
 
406
        but are not explicitly marked.
 
407
        """
 
408
        try:
 
409
            return list(self.get_parent_map([version_id])[version_id])
 
410
        except KeyError:
 
411
            raise errors.RevisionNotPresent(version_id, self)
 
412
 
 
413
    def annotate_iter(self, version_id):
 
414
        """Yield list of (version-id, line) pairs for the specified
 
415
        version.
 
416
 
 
417
        Must raise RevisionNotPresent if the given version is
 
418
        not present in file history.
 
419
        """
 
420
        raise NotImplementedError(self.annotate_iter)
 
421
 
 
422
    def annotate(self, version_id):
 
423
        return list(self.annotate_iter(version_id))
 
424
 
 
425
    def join(self, other, pb=None, msg=None, version_ids=None,
 
426
             ignore_missing=False):
 
427
        """Integrate versions from other into this versioned file.
 
428
 
 
429
        If version_ids is None all versions from other should be
 
430
        incorporated into this versioned file.
 
431
 
 
432
        Must raise RevisionNotPresent if any of the specified versions
 
433
        are not present in the other file's history unless ignore_missing
 
434
        is supplied in which case they are silently skipped.
 
435
        """
 
436
        self._check_write_ok()
 
437
        return InterVersionedFile.get(other, self).join(
 
438
            pb,
 
439
            msg,
 
440
            version_ids,
 
441
            ignore_missing)
 
442
 
 
443
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
 
444
                                                pb=None):
 
445
        """Iterate over the lines in the versioned file from version_ids.
 
446
 
 
447
        This may return lines from other versions. Each item the returned
 
448
        iterator yields is a tuple of a line and a text version that that line
 
449
        is present in (not introduced in).
 
450
 
 
451
        Ordering of results is in whatever order is most suitable for the
 
452
        underlying storage format.
 
453
 
 
454
        If a progress bar is supplied, it may be used to indicate progress.
 
455
        The caller is responsible for cleaning up progress bars (because this
 
456
        is an iterator).
 
457
 
 
458
        NOTES: Lines are normalised: they will all have \n terminators.
 
459
               Lines are returned in arbitrary order.
 
460
 
 
461
        :return: An iterator over (line, version_id).
 
462
        """
 
463
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
 
464
 
 
465
    def iter_parents(self, version_ids):
 
466
        """Iterate through the parents for many version ids.
 
467
 
 
468
        :param version_ids: An iterable yielding version_ids.
 
469
        :return: An iterator that yields (version_id, parents). Requested 
 
470
            version_ids not present in the versioned file are simply skipped.
 
471
            The order is undefined, allowing for different optimisations in
 
472
            the underlying implementation.
 
473
        """
 
474
        return self.get_parent_map(version_ids).iteritems()
 
475
 
 
476
    def plan_merge(self, ver_a, ver_b):
 
477
        """Return pseudo-annotation indicating how the two versions merge.
 
478
 
 
479
        This is computed between versions a and b and their common
 
480
        base.
 
481
 
 
482
        Weave lines present in none of them are skipped entirely.
 
483
 
 
484
        Legend:
 
485
        killed-base Dead in base revision
 
486
        killed-both Killed in each revision
 
487
        killed-a    Killed in a
 
488
        killed-b    Killed in b
 
489
        unchanged   Alive in both a and b (possibly created in both)
 
490
        new-a       Created in a
 
491
        new-b       Created in b
 
492
        ghost-a     Killed in a, unborn in b    
 
493
        ghost-b     Killed in b, unborn in a
 
494
        irrelevant  Not in either revision
 
495
        """
 
496
        raise NotImplementedError(VersionedFile.plan_merge)
 
497
        
 
498
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
 
499
                    b_marker=TextMerge.B_MARKER):
 
500
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
 
501
 
 
502
 
 
503
class _PlanMergeVersionedFile(object):
 
504
    """A VersionedFile for uncommitted and committed texts.
 
505
 
 
506
    It is intended to allow merges to be planned with working tree texts.
 
507
    It implements only the small part of the VersionedFile interface used by
 
508
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
 
509
    _PlanMergeVersionedFile itself.
 
510
    """
 
511
 
 
512
    def __init__(self, file_id, fallback_versionedfiles=None):
 
513
        """Constuctor
 
514
 
 
515
        :param file_id: Used when raising exceptions.
 
516
        :param fallback_versionedfiles: If supplied, the set of fallbacks to
 
517
            use.  Otherwise, _PlanMergeVersionedFile.fallback_versionedfiles
 
518
            can be appended to later.
 
519
        """
 
520
        self._file_id = file_id
 
521
        if fallback_versionedfiles is None:
 
522
            self.fallback_versionedfiles = []
 
523
        else:
 
524
            self.fallback_versionedfiles = fallback_versionedfiles
 
525
        self._parents = {}
 
526
        self._lines = {}
 
527
 
 
528
    def plan_merge(self, ver_a, ver_b, base=None):
 
529
        """See VersionedFile.plan_merge"""
 
530
        from bzrlib.merge import _PlanMerge
 
531
        if base is None:
 
532
            return _PlanMerge(ver_a, ver_b, self).plan_merge()
 
533
        old_plan = list(_PlanMerge(ver_a, base, self).plan_merge())
 
534
        new_plan = list(_PlanMerge(ver_a, ver_b, self).plan_merge())
 
535
        return _PlanMerge._subtract_plans(old_plan, new_plan)
 
536
 
 
537
    def plan_lca_merge(self, ver_a, ver_b, base=None):
 
538
        from bzrlib.merge import _PlanLCAMerge
 
539
        graph = self._get_graph()
 
540
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, graph).plan_merge()
 
541
        if base is None:
 
542
            return new_plan
 
543
        old_plan = _PlanLCAMerge(ver_a, base, self, graph).plan_merge()
 
544
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
 
545
 
 
546
    def add_lines(self, version_id, parents, lines):
 
547
        """See VersionedFile.add_lines
 
548
 
 
549
        Lines are added locally, not fallback versionedfiles.  Also, ghosts are
 
550
        permitted.  Only reserved ids are permitted.
 
551
        """
 
552
        if not revision.is_reserved_id(version_id):
 
553
            raise ValueError('Only reserved ids may be used')
 
554
        if parents is None:
 
555
            raise ValueError('Parents may not be None')
 
556
        if lines is None:
 
557
            raise ValueError('Lines may not be None')
 
558
        self._parents[version_id] = tuple(parents)
 
559
        self._lines[version_id] = lines
 
560
 
 
561
    def get_lines(self, version_id):
 
562
        """See VersionedFile.get_ancestry"""
 
563
        lines = self._lines.get(version_id)
 
564
        if lines is not None:
 
565
            return lines
 
566
        for versionedfile in self.fallback_versionedfiles:
 
567
            try:
 
568
                return versionedfile.get_lines(version_id)
 
569
            except errors.RevisionNotPresent:
 
570
                continue
 
571
        else:
 
572
            raise errors.RevisionNotPresent(version_id, self._file_id)
 
573
 
 
574
    def get_ancestry(self, version_id, topo_sorted=False):
 
575
        """See VersionedFile.get_ancestry.
 
576
 
 
577
        Note that this implementation assumes that if a VersionedFile can
 
578
        answer get_ancestry at all, it can give an authoritative answer.  In
 
579
        fact, ghosts can invalidate this assumption.  But it's good enough
 
580
        99% of the time, and far cheaper/simpler.
 
581
 
 
582
        Also note that the results of this version are never topologically
 
583
        sorted, and are a set.
 
584
        """
 
585
        if topo_sorted:
 
586
            raise ValueError('This implementation does not provide sorting')
 
587
        parents = self._parents.get(version_id)
 
588
        if parents is None:
 
589
            for vf in self.fallback_versionedfiles:
 
590
                try:
 
591
                    return vf.get_ancestry(version_id, topo_sorted=False)
 
592
                except errors.RevisionNotPresent:
 
593
                    continue
 
594
            else:
 
595
                raise errors.RevisionNotPresent(version_id, self._file_id)
 
596
        ancestry = set([version_id])
 
597
        for parent in parents:
 
598
            ancestry.update(self.get_ancestry(parent, topo_sorted=False))
 
599
        return ancestry
 
600
 
 
601
    def get_parent_map(self, version_ids):
 
602
        """See VersionedFile.get_parent_map"""
 
603
        result = {}
 
604
        pending = set(version_ids)
 
605
        for key in version_ids:
 
606
            try:
 
607
                result[key] = self._parents[key]
 
608
            except KeyError:
 
609
                pass
 
610
        pending = pending - set(result.keys())
 
611
        for versionedfile in self.fallback_versionedfiles:
 
612
            parents = versionedfile.get_parent_map(pending)
 
613
            result.update(parents)
 
614
            pending = pending - set(parents.keys())
 
615
            if not pending:
 
616
                return result
 
617
        return result
 
618
 
 
619
    def _get_graph(self):
 
620
        from bzrlib.graph import (
 
621
            DictParentsProvider,
 
622
            Graph,
 
623
            _StackedParentsProvider,
 
624
            )
 
625
        from bzrlib.repofmt.knitrepo import _KnitParentsProvider
 
626
        parent_providers = [DictParentsProvider(self._parents)]
 
627
        for vf in self.fallback_versionedfiles:
 
628
            parent_providers.append(_KnitParentsProvider(vf))
 
629
        return Graph(_StackedParentsProvider(parent_providers))
 
630
 
 
631
 
 
632
class PlanWeaveMerge(TextMerge):
 
633
    """Weave merge that takes a plan as its input.
 
634
    
 
635
    This exists so that VersionedFile.plan_merge is implementable.
 
636
    Most callers will want to use WeaveMerge instead.
 
637
    """
 
638
 
 
639
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
 
640
                 b_marker=TextMerge.B_MARKER):
 
641
        TextMerge.__init__(self, a_marker, b_marker)
 
642
        self.plan = plan
 
643
 
 
644
    def _merge_struct(self):
 
645
        lines_a = []
 
646
        lines_b = []
 
647
        ch_a = ch_b = False
 
648
 
 
649
        def outstanding_struct():
 
650
            if not lines_a and not lines_b:
 
651
                return
 
652
            elif ch_a and not ch_b:
 
653
                # one-sided change:
 
654
                yield(lines_a,)
 
655
            elif ch_b and not ch_a:
 
656
                yield (lines_b,)
 
657
            elif lines_a == lines_b:
 
658
                yield(lines_a,)
 
659
            else:
 
660
                yield (lines_a, lines_b)
 
661
       
 
662
        # We previously considered either 'unchanged' or 'killed-both' lines
 
663
        # to be possible places to resynchronize.  However, assuming agreement
 
664
        # on killed-both lines may be too aggressive. -- mbp 20060324
 
665
        for state, line in self.plan:
 
666
            if state == 'unchanged':
 
667
                # resync and flush queued conflicts changes if any
 
668
                for struct in outstanding_struct():
 
669
                    yield struct
 
670
                lines_a = []
 
671
                lines_b = []
 
672
                ch_a = ch_b = False
 
673
                
 
674
            if state == 'unchanged':
 
675
                if line:
 
676
                    yield ([line],)
 
677
            elif state == 'killed-a':
 
678
                ch_a = True
 
679
                lines_b.append(line)
 
680
            elif state == 'killed-b':
 
681
                ch_b = True
 
682
                lines_a.append(line)
 
683
            elif state == 'new-a':
 
684
                ch_a = True
 
685
                lines_a.append(line)
 
686
            elif state == 'new-b':
 
687
                ch_b = True
 
688
                lines_b.append(line)
 
689
            elif state == 'conflicted-a':
 
690
                ch_b = ch_a = True
 
691
                lines_a.append(line)
 
692
            elif state == 'conflicted-b':
 
693
                ch_b = ch_a = True
 
694
                lines_b.append(line)
 
695
            else:
 
696
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
 
697
                                 'killed-base', 'killed-both'), state
 
698
        for struct in outstanding_struct():
 
699
            yield struct
 
700
 
 
701
 
 
702
class WeaveMerge(PlanWeaveMerge):
 
703
    """Weave merge that takes a VersionedFile and two versions as its input."""
 
704
 
 
705
    def __init__(self, versionedfile, ver_a, ver_b, 
 
706
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
 
707
        plan = versionedfile.plan_merge(ver_a, ver_b)
 
708
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
 
709
 
 
710
 
 
711
class InterVersionedFile(InterObject):
 
712
    """This class represents operations taking place between two VersionedFiles.
 
713
 
 
714
    Its instances have methods like join, and contain
 
715
    references to the source and target versionedfiles these operations can be 
 
716
    carried out on.
 
717
 
 
718
    Often we will provide convenience methods on 'versionedfile' which carry out
 
719
    operations with another versionedfile - they will always forward to
 
720
    InterVersionedFile.get(other).method_name(parameters).
 
721
    """
 
722
 
 
723
    _optimisers = []
 
724
    """The available optimised InterVersionedFile types."""
 
725
 
 
726
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
727
        """Integrate versions from self.source into self.target.
 
728
 
 
729
        If version_ids is None all versions from source should be
 
730
        incorporated into this versioned file.
 
731
 
 
732
        Must raise RevisionNotPresent if any of the specified versions
 
733
        are not present in the other file's history unless ignore_missing is 
 
734
        supplied in which case they are silently skipped.
 
735
        """
 
736
        target = self.target
 
737
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
 
738
        graph = Graph(self.source)
 
739
        search = graph._make_breadth_first_searcher(version_ids)
 
740
        transitive_ids = set()
 
741
        map(transitive_ids.update, list(search))
 
742
        parent_map = self.source.get_parent_map(transitive_ids)
 
743
        order = tsort.topo_sort(parent_map.items())
 
744
        pb = ui.ui_factory.nested_progress_bar()
 
745
        parent_texts = {}
 
746
        try:
 
747
            # TODO for incremental cross-format work:
 
748
            # make a versioned file with the following content:
 
749
            # all revisions we have been asked to join
 
750
            # all their ancestors that are *not* in target already.
 
751
            # the immediate parents of the above two sets, with 
 
752
            # empty parent lists - these versions are in target already
 
753
            # and the incorrect version data will be ignored.
 
754
            # TODO: for all ancestors that are present in target already,
 
755
            # check them for consistent data, this requires moving sha1 from
 
756
            # 
 
757
            # TODO: remove parent texts when they are not relevant any more for 
 
758
            # memory pressure reduction. RBC 20060313
 
759
            # pb.update('Converting versioned data', 0, len(order))
 
760
            total = len(order)
 
761
            for index, version in enumerate(order):
 
762
                pb.update('Converting versioned data', index, total)
 
763
                if version in target:
 
764
                    continue
 
765
                _, _, parent_text = target.add_lines(version,
 
766
                                               parent_map[version],
 
767
                                               self.source.get_lines(version),
 
768
                                               parent_texts=parent_texts)
 
769
                parent_texts[version] = parent_text
 
770
            return total
 
771
        finally:
 
772
            pb.finished()
 
773
 
 
774
    def _get_source_version_ids(self, version_ids, ignore_missing):
 
775
        """Determine the version ids to be used from self.source.
 
776
 
 
777
        :param version_ids: The caller-supplied version ids to check. (None 
 
778
                            for all). If None is in version_ids, it is stripped.
 
779
        :param ignore_missing: if True, remove missing ids from the version 
 
780
                               list. If False, raise RevisionNotPresent on
 
781
                               a missing version id.
 
782
        :return: A set of version ids.
 
783
        """
 
784
        if version_ids is None:
 
785
            # None cannot be in source.versions
 
786
            return set(self.source.versions())
 
787
        else:
 
788
            if ignore_missing:
 
789
                return set(self.source.versions()).intersection(set(version_ids))
 
790
            else:
 
791
                new_version_ids = set()
 
792
                for version in version_ids:
 
793
                    if version is None:
 
794
                        continue
 
795
                    if not self.source.has_version(version):
 
796
                        raise errors.RevisionNotPresent(version, str(self.source))
 
797
                    else:
 
798
                        new_version_ids.add(version)
 
799
                return new_version_ids