/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 03:39:43 UTC
  • mto: This revision was merged to the branch mainline in revision 3350.
  • Revision ID: robertc@robertcollins.net-20080408033943-ihbgs5wyqnh61bit
 * ``VersionedFile.get_sha1`` is deprecated, please use
   ``VersionedFile.get_sha1s``. (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
    @deprecated_method(one_four)
 
275
    def get_sha1(self, version_id):
 
276
        """Get the stored sha1 sum for the given revision.
 
277
        
 
278
        :param version_id: The name of the version to lookup
 
279
        """
 
280
        return self.get_sha1s([version_id])[0]
 
281
 
 
282
    def get_sha1s(self, version_ids):
 
283
        """Get the stored sha1 sums for the given revisions.
 
284
 
 
285
        :param version_ids: The names of the versions to lookup
 
286
        :return: a list of sha1s in order according to the version_ids
 
287
        """
 
288
        raise NotImplementedError(self.get_sha1s)
 
289
 
 
290
    def get_text(self, version_id):
 
291
        """Return version contents as a text string.
 
292
 
 
293
        Raises RevisionNotPresent if version is not present in
 
294
        file history.
 
295
        """
 
296
        return ''.join(self.get_lines(version_id))
 
297
    get_string = get_text
 
298
 
 
299
    def get_texts(self, version_ids):
 
300
        """Return the texts of listed versions as a list of strings.
 
301
 
 
302
        Raises RevisionNotPresent if version is not present in
 
303
        file history.
 
304
        """
 
305
        return [''.join(self.get_lines(v)) for v in version_ids]
 
306
 
 
307
    def get_lines(self, version_id):
 
308
        """Return version contents as a sequence of lines.
 
309
 
 
310
        Raises RevisionNotPresent if version is not present in
 
311
        file history.
 
312
        """
 
313
        raise NotImplementedError(self.get_lines)
 
314
 
 
315
    def _get_lf_split_line_list(self, version_ids):
 
316
        return [StringIO(t).readlines() for t in self.get_texts(version_ids)]
 
317
 
 
318
    def get_ancestry(self, version_ids, topo_sorted=True):
 
319
        """Return a list of all ancestors of given version(s). This
 
320
        will not include the null revision.
 
321
 
 
322
        This list will not be topologically sorted if topo_sorted=False is
 
323
        passed.
 
324
 
 
325
        Must raise RevisionNotPresent if any of the given versions are
 
326
        not present in file history."""
 
327
        if isinstance(version_ids, basestring):
 
328
            version_ids = [version_ids]
 
329
        raise NotImplementedError(self.get_ancestry)
 
330
        
 
331
    def get_ancestry_with_ghosts(self, version_ids):
 
332
        """Return a list of all ancestors of given version(s). This
 
333
        will not include the null revision.
 
334
 
 
335
        Must raise RevisionNotPresent if any of the given versions are
 
336
        not present in file history.
 
337
        
 
338
        Ghosts that are known about will be included in ancestry list,
 
339
        but are not explicitly marked.
 
340
        """
 
341
        raise NotImplementedError(self.get_ancestry_with_ghosts)
 
342
    
 
343
    @deprecated_method(one_four)
 
344
    def get_graph(self, version_ids=None):
 
345
        """Return a graph from the versioned file. 
 
346
        
 
347
        Ghosts are not listed or referenced in the graph.
 
348
        :param version_ids: Versions to select.
 
349
                            None means retrieve all versions.
 
350
        """
 
351
        if version_ids is None:
 
352
            result = self.get_parent_map(self.versions())
 
353
        else:
 
354
            result = {}
 
355
            pending = set(version_ids)
 
356
            while pending:
 
357
                this_iteration = pending
 
358
                pending = set()
 
359
                parents = self.get_parent_map(this_iteration)
 
360
                for version, parents in parents.iteritems():
 
361
                    result[version] = parents
 
362
                    for parent in parents:
 
363
                        if parent in result:
 
364
                            continue
 
365
                        pending.add(parent)
 
366
        references = set()
 
367
        for parents in result.itervalues():
 
368
            references.update(parents)
 
369
        existing_parents = self.get_parent_map(references)
 
370
        for key, parents in result.iteritems():
 
371
            present_parents = [parent for parent in parents if parent in
 
372
                existing_parents]
 
373
            result[key] = tuple(present_parents)
 
374
        return result
 
375
 
 
376
    @deprecated_method(one_four)
 
377
    def get_graph_with_ghosts(self):
 
378
        """Return a graph for the entire versioned file.
 
379
        
 
380
        Ghosts are referenced in parents list but are not
 
381
        explicitly listed.
 
382
        """
 
383
        raise NotImplementedError(self.get_graph_with_ghosts)
 
384
 
 
385
    def get_parent_map(self, version_ids):
 
386
        """Get a map of the parents of version_ids.
 
387
 
 
388
        :param version_ids: The version ids to look up parents for.
 
389
        :return: A mapping from version id to parents.
 
390
        """
 
391
        raise NotImplementedError(self.get_parent_map)
 
392
 
 
393
    @deprecated_method(one_four)
 
394
    def get_parents(self, version_id):
 
395
        """Return version names for parents of a version.
 
396
 
 
397
        Must raise RevisionNotPresent if version is not present in
 
398
        file history.
 
399
        """
 
400
        try:
 
401
            all = self.get_parent_map([version_id])[version_id]
 
402
        except KeyError:
 
403
            raise errors.RevisionNotPresent(version_id, self)
 
404
        result = []
 
405
        parent_parents = self.get_parent_map(all)
 
406
        for version_id in all:
 
407
            if version_id in parent_parents:
 
408
                result.append(version_id)
 
409
        return result
 
410
 
 
411
    def get_parents_with_ghosts(self, version_id):
 
412
        """Return version names for parents of version_id.
 
413
 
 
414
        Will raise RevisionNotPresent if version_id is not present
 
415
        in the history.
 
416
 
 
417
        Ghosts that are known about will be included in the parent list,
 
418
        but are not explicitly marked.
 
419
        """
 
420
        try:
 
421
            return list(self.get_parent_map([version_id])[version_id])
 
422
        except KeyError:
 
423
            raise errors.RevisionNotPresent(version_id, self)
 
424
 
 
425
    def annotate_iter(self, version_id):
 
426
        """Yield list of (version-id, line) pairs for the specified
 
427
        version.
 
428
 
 
429
        Must raise RevisionNotPresent if the given version is
 
430
        not present in file history.
 
431
        """
 
432
        raise NotImplementedError(self.annotate_iter)
 
433
 
 
434
    def annotate(self, version_id):
 
435
        return list(self.annotate_iter(version_id))
 
436
 
 
437
    def join(self, other, pb=None, msg=None, version_ids=None,
 
438
             ignore_missing=False):
 
439
        """Integrate versions from other into this versioned file.
 
440
 
 
441
        If version_ids is None all versions from other should be
 
442
        incorporated into this versioned file.
 
443
 
 
444
        Must raise RevisionNotPresent if any of the specified versions
 
445
        are not present in the other file's history unless ignore_missing
 
446
        is supplied in which case they are silently skipped.
 
447
        """
 
448
        self._check_write_ok()
 
449
        return InterVersionedFile.get(other, self).join(
 
450
            pb,
 
451
            msg,
 
452
            version_ids,
 
453
            ignore_missing)
 
454
 
 
455
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
 
456
                                                pb=None):
 
457
        """Iterate over the lines in the versioned file from version_ids.
 
458
 
 
459
        This may return lines from other versions. Each item the returned
 
460
        iterator yields is a tuple of a line and a text version that that line
 
461
        is present in (not introduced in).
 
462
 
 
463
        Ordering of results is in whatever order is most suitable for the
 
464
        underlying storage format.
 
465
 
 
466
        If a progress bar is supplied, it may be used to indicate progress.
 
467
        The caller is responsible for cleaning up progress bars (because this
 
468
        is an iterator).
 
469
 
 
470
        NOTES: Lines are normalised: they will all have \n terminators.
 
471
               Lines are returned in arbitrary order.
 
472
 
 
473
        :return: An iterator over (line, version_id).
 
474
        """
 
475
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
 
476
 
 
477
    @deprecated_method(one_four)
 
478
    def iter_parents(self, version_ids):
 
479
        """Iterate through the parents for many version ids.
 
480
 
 
481
        :param version_ids: An iterable yielding version_ids.
 
482
        :return: An iterator that yields (version_id, parents). Requested 
 
483
            version_ids not present in the versioned file are simply skipped.
 
484
            The order is undefined, allowing for different optimisations in
 
485
            the underlying implementation.
 
486
        """
 
487
        return self.get_parent_map(version_ids).iteritems()
 
488
 
 
489
    def plan_merge(self, ver_a, ver_b):
 
490
        """Return pseudo-annotation indicating how the two versions merge.
 
491
 
 
492
        This is computed between versions a and b and their common
 
493
        base.
 
494
 
 
495
        Weave lines present in none of them are skipped entirely.
 
496
 
 
497
        Legend:
 
498
        killed-base Dead in base revision
 
499
        killed-both Killed in each revision
 
500
        killed-a    Killed in a
 
501
        killed-b    Killed in b
 
502
        unchanged   Alive in both a and b (possibly created in both)
 
503
        new-a       Created in a
 
504
        new-b       Created in b
 
505
        ghost-a     Killed in a, unborn in b    
 
506
        ghost-b     Killed in b, unborn in a
 
507
        irrelevant  Not in either revision
 
508
        """
 
509
        raise NotImplementedError(VersionedFile.plan_merge)
 
510
        
 
511
    def weave_merge(self, plan, a_marker=TextMerge.A_MARKER,
 
512
                    b_marker=TextMerge.B_MARKER):
 
513
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
 
514
 
 
515
 
 
516
class _PlanMergeVersionedFile(object):
 
517
    """A VersionedFile for uncommitted and committed texts.
 
518
 
 
519
    It is intended to allow merges to be planned with working tree texts.
 
520
    It implements only the small part of the VersionedFile interface used by
 
521
    PlanMerge.  It falls back to multiple versionedfiles for data not stored in
 
522
    _PlanMergeVersionedFile itself.
 
523
    """
 
524
 
 
525
    def __init__(self, file_id, fallback_versionedfiles=None):
 
526
        """Constuctor
 
527
 
 
528
        :param file_id: Used when raising exceptions.
 
529
        :param fallback_versionedfiles: If supplied, the set of fallbacks to
 
530
            use.  Otherwise, _PlanMergeVersionedFile.fallback_versionedfiles
 
531
            can be appended to later.
 
532
        """
 
533
        self._file_id = file_id
 
534
        if fallback_versionedfiles is None:
 
535
            self.fallback_versionedfiles = []
 
536
        else:
 
537
            self.fallback_versionedfiles = fallback_versionedfiles
 
538
        self._parents = {}
 
539
        self._lines = {}
 
540
 
 
541
    def plan_merge(self, ver_a, ver_b, base=None):
 
542
        """See VersionedFile.plan_merge"""
 
543
        from bzrlib.merge import _PlanMerge
 
544
        if base is None:
 
545
            return _PlanMerge(ver_a, ver_b, self).plan_merge()
 
546
        old_plan = list(_PlanMerge(ver_a, base, self).plan_merge())
 
547
        new_plan = list(_PlanMerge(ver_a, ver_b, self).plan_merge())
 
548
        return _PlanMerge._subtract_plans(old_plan, new_plan)
 
549
 
 
550
    def plan_lca_merge(self, ver_a, ver_b, base=None):
 
551
        from bzrlib.merge import _PlanLCAMerge
 
552
        graph = self._get_graph()
 
553
        new_plan = _PlanLCAMerge(ver_a, ver_b, self, graph).plan_merge()
 
554
        if base is None:
 
555
            return new_plan
 
556
        old_plan = _PlanLCAMerge(ver_a, base, self, graph).plan_merge()
 
557
        return _PlanLCAMerge._subtract_plans(list(old_plan), list(new_plan))
 
558
 
 
559
    def add_lines(self, version_id, parents, lines):
 
560
        """See VersionedFile.add_lines
 
561
 
 
562
        Lines are added locally, not fallback versionedfiles.  Also, ghosts are
 
563
        permitted.  Only reserved ids are permitted.
 
564
        """
 
565
        if not revision.is_reserved_id(version_id):
 
566
            raise ValueError('Only reserved ids may be used')
 
567
        if parents is None:
 
568
            raise ValueError('Parents may not be None')
 
569
        if lines is None:
 
570
            raise ValueError('Lines may not be None')
 
571
        self._parents[version_id] = tuple(parents)
 
572
        self._lines[version_id] = lines
 
573
 
 
574
    def get_lines(self, version_id):
 
575
        """See VersionedFile.get_ancestry"""
 
576
        lines = self._lines.get(version_id)
 
577
        if lines is not None:
 
578
            return lines
 
579
        for versionedfile in self.fallback_versionedfiles:
 
580
            try:
 
581
                return versionedfile.get_lines(version_id)
 
582
            except errors.RevisionNotPresent:
 
583
                continue
 
584
        else:
 
585
            raise errors.RevisionNotPresent(version_id, self._file_id)
 
586
 
 
587
    def get_ancestry(self, version_id, topo_sorted=False):
 
588
        """See VersionedFile.get_ancestry.
 
589
 
 
590
        Note that this implementation assumes that if a VersionedFile can
 
591
        answer get_ancestry at all, it can give an authoritative answer.  In
 
592
        fact, ghosts can invalidate this assumption.  But it's good enough
 
593
        99% of the time, and far cheaper/simpler.
 
594
 
 
595
        Also note that the results of this version are never topologically
 
596
        sorted, and are a set.
 
597
        """
 
598
        if topo_sorted:
 
599
            raise ValueError('This implementation does not provide sorting')
 
600
        parents = self._parents.get(version_id)
 
601
        if parents is None:
 
602
            for vf in self.fallback_versionedfiles:
 
603
                try:
 
604
                    return vf.get_ancestry(version_id, topo_sorted=False)
 
605
                except errors.RevisionNotPresent:
 
606
                    continue
 
607
            else:
 
608
                raise errors.RevisionNotPresent(version_id, self._file_id)
 
609
        ancestry = set([version_id])
 
610
        for parent in parents:
 
611
            ancestry.update(self.get_ancestry(parent, topo_sorted=False))
 
612
        return ancestry
 
613
 
 
614
    def get_parent_map(self, version_ids):
 
615
        """See VersionedFile.get_parent_map"""
 
616
        result = {}
 
617
        pending = set(version_ids)
 
618
        for key in version_ids:
 
619
            try:
 
620
                result[key] = self._parents[key]
 
621
            except KeyError:
 
622
                pass
 
623
        pending = pending - set(result.keys())
 
624
        for versionedfile in self.fallback_versionedfiles:
 
625
            parents = versionedfile.get_parent_map(pending)
 
626
            result.update(parents)
 
627
            pending = pending - set(parents.keys())
 
628
            if not pending:
 
629
                return result
 
630
        return result
 
631
 
 
632
    def _get_graph(self):
 
633
        from bzrlib.graph import (
 
634
            DictParentsProvider,
 
635
            Graph,
 
636
            _StackedParentsProvider,
 
637
            )
 
638
        from bzrlib.repofmt.knitrepo import _KnitParentsProvider
 
639
        parent_providers = [DictParentsProvider(self._parents)]
 
640
        for vf in self.fallback_versionedfiles:
 
641
            parent_providers.append(_KnitParentsProvider(vf))
 
642
        return Graph(_StackedParentsProvider(parent_providers))
 
643
 
 
644
 
 
645
class PlanWeaveMerge(TextMerge):
 
646
    """Weave merge that takes a plan as its input.
 
647
    
 
648
    This exists so that VersionedFile.plan_merge is implementable.
 
649
    Most callers will want to use WeaveMerge instead.
 
650
    """
 
651
 
 
652
    def __init__(self, plan, a_marker=TextMerge.A_MARKER,
 
653
                 b_marker=TextMerge.B_MARKER):
 
654
        TextMerge.__init__(self, a_marker, b_marker)
 
655
        self.plan = plan
 
656
 
 
657
    def _merge_struct(self):
 
658
        lines_a = []
 
659
        lines_b = []
 
660
        ch_a = ch_b = False
 
661
 
 
662
        def outstanding_struct():
 
663
            if not lines_a and not lines_b:
 
664
                return
 
665
            elif ch_a and not ch_b:
 
666
                # one-sided change:
 
667
                yield(lines_a,)
 
668
            elif ch_b and not ch_a:
 
669
                yield (lines_b,)
 
670
            elif lines_a == lines_b:
 
671
                yield(lines_a,)
 
672
            else:
 
673
                yield (lines_a, lines_b)
 
674
       
 
675
        # We previously considered either 'unchanged' or 'killed-both' lines
 
676
        # to be possible places to resynchronize.  However, assuming agreement
 
677
        # on killed-both lines may be too aggressive. -- mbp 20060324
 
678
        for state, line in self.plan:
 
679
            if state == 'unchanged':
 
680
                # resync and flush queued conflicts changes if any
 
681
                for struct in outstanding_struct():
 
682
                    yield struct
 
683
                lines_a = []
 
684
                lines_b = []
 
685
                ch_a = ch_b = False
 
686
                
 
687
            if state == 'unchanged':
 
688
                if line:
 
689
                    yield ([line],)
 
690
            elif state == 'killed-a':
 
691
                ch_a = True
 
692
                lines_b.append(line)
 
693
            elif state == 'killed-b':
 
694
                ch_b = True
 
695
                lines_a.append(line)
 
696
            elif state == 'new-a':
 
697
                ch_a = True
 
698
                lines_a.append(line)
 
699
            elif state == 'new-b':
 
700
                ch_b = True
 
701
                lines_b.append(line)
 
702
            elif state == 'conflicted-a':
 
703
                ch_b = ch_a = True
 
704
                lines_a.append(line)
 
705
            elif state == 'conflicted-b':
 
706
                ch_b = ch_a = True
 
707
                lines_b.append(line)
 
708
            else:
 
709
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
 
710
                                 'killed-base', 'killed-both'), state
 
711
        for struct in outstanding_struct():
 
712
            yield struct
 
713
 
 
714
 
 
715
class WeaveMerge(PlanWeaveMerge):
 
716
    """Weave merge that takes a VersionedFile and two versions as its input."""
 
717
 
 
718
    def __init__(self, versionedfile, ver_a, ver_b, 
 
719
        a_marker=PlanWeaveMerge.A_MARKER, b_marker=PlanWeaveMerge.B_MARKER):
 
720
        plan = versionedfile.plan_merge(ver_a, ver_b)
 
721
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
 
722
 
 
723
 
 
724
class InterVersionedFile(InterObject):
 
725
    """This class represents operations taking place between two VersionedFiles.
 
726
 
 
727
    Its instances have methods like join, and contain
 
728
    references to the source and target versionedfiles these operations can be 
 
729
    carried out on.
 
730
 
 
731
    Often we will provide convenience methods on 'versionedfile' which carry out
 
732
    operations with another versionedfile - they will always forward to
 
733
    InterVersionedFile.get(other).method_name(parameters).
 
734
    """
 
735
 
 
736
    _optimisers = []
 
737
    """The available optimised InterVersionedFile types."""
 
738
 
 
739
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
740
        """Integrate versions from self.source into self.target.
 
741
 
 
742
        If version_ids is None all versions from source should be
 
743
        incorporated into this versioned file.
 
744
 
 
745
        Must raise RevisionNotPresent if any of the specified versions
 
746
        are not present in the other file's history unless ignore_missing is 
 
747
        supplied in which case they are silently skipped.
 
748
        """
 
749
        target = self.target
 
750
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
 
751
        graph = Graph(self.source)
 
752
        search = graph._make_breadth_first_searcher(version_ids)
 
753
        transitive_ids = set()
 
754
        map(transitive_ids.update, list(search))
 
755
        parent_map = self.source.get_parent_map(transitive_ids)
 
756
        order = tsort.topo_sort(parent_map.items())
 
757
        pb = ui.ui_factory.nested_progress_bar()
 
758
        parent_texts = {}
 
759
        try:
 
760
            # TODO for incremental cross-format work:
 
761
            # make a versioned file with the following content:
 
762
            # all revisions we have been asked to join
 
763
            # all their ancestors that are *not* in target already.
 
764
            # the immediate parents of the above two sets, with 
 
765
            # empty parent lists - these versions are in target already
 
766
            # and the incorrect version data will be ignored.
 
767
            # TODO: for all ancestors that are present in target already,
 
768
            # check them for consistent data, this requires moving sha1 from
 
769
            # 
 
770
            # TODO: remove parent texts when they are not relevant any more for 
 
771
            # memory pressure reduction. RBC 20060313
 
772
            # pb.update('Converting versioned data', 0, len(order))
 
773
            total = len(order)
 
774
            for index, version in enumerate(order):
 
775
                pb.update('Converting versioned data', index, total)
 
776
                if version in target:
 
777
                    continue
 
778
                _, _, parent_text = target.add_lines(version,
 
779
                                               parent_map[version],
 
780
                                               self.source.get_lines(version),
 
781
                                               parent_texts=parent_texts)
 
782
                parent_texts[version] = parent_text
 
783
            return total
 
784
        finally:
 
785
            pb.finished()
 
786
 
 
787
    def _get_source_version_ids(self, version_ids, ignore_missing):
 
788
        """Determine the version ids to be used from self.source.
 
789
 
 
790
        :param version_ids: The caller-supplied version ids to check. (None 
 
791
                            for all). If None is in version_ids, it is stripped.
 
792
        :param ignore_missing: if True, remove missing ids from the version 
 
793
                               list. If False, raise RevisionNotPresent on
 
794
                               a missing version id.
 
795
        :return: A set of version ids.
 
796
        """
 
797
        if version_ids is None:
 
798
            # None cannot be in source.versions
 
799
            return set(self.source.versions())
 
800
        else:
 
801
            if ignore_missing:
 
802
                return set(self.source.versions()).intersection(set(version_ids))
 
803
            else:
 
804
                new_version_ids = set()
 
805
                for version in version_ids:
 
806
                    if version is None:
 
807
                        continue
 
808
                    if not self.source.has_version(version):
 
809
                        raise errors.RevisionNotPresent(version, str(self.source))
 
810
                    else:
 
811
                        new_version_ids.add(version)
 
812
                return new_version_ids