1
# Copyright (C) 2005 by Canonical Ltd
 
 
4
#   Johan Rydberg <jrydberg@gnu.org>
 
 
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.
 
 
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.
 
 
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
 
 
20
# Remaing to do is to figure out if get_graph should return a simple
 
 
21
# map, or a graph object of some kind.
 
 
24
"""Versioned text file storage api."""
 
 
27
from copy import deepcopy
 
 
28
from unittest import TestSuite
 
 
31
import bzrlib.errors as errors
 
 
32
from bzrlib.inter import InterObject
 
 
33
from bzrlib.symbol_versioning import *
 
 
34
from bzrlib.textmerge import TextMerge
 
 
35
from bzrlib.transport.memory import MemoryTransport
 
 
36
from bzrlib.tsort import topo_sort
 
 
40
class VersionedFile(object):
 
 
41
    """Versioned text file storage.
 
 
43
    A versioned file manages versions of line-based text files,
 
 
44
    keeping track of the originating version for each line.
 
 
46
    To clients the "lines" of the file are represented as a list of
 
 
47
    strings. These strings will typically have terminal newline
 
 
48
    characters, but this is not required.  In particular files commonly
 
 
49
    do not have a newline at the end of the file.
 
 
51
    Texts are identified by a version-id string.
 
 
54
    def __init__(self, access_mode):
 
 
56
        self._access_mode = access_mode
 
 
58
    def copy_to(self, name, transport):
 
 
59
        """Copy this versioned file to name on transport."""
 
 
60
        raise NotImplementedError(self.copy_to)
 
 
62
    @deprecated_method(zero_eight)
 
 
64
        """Return a list of all the versions in this versioned file.
 
 
66
        Please use versionedfile.versions() now.
 
 
68
        return self.versions()
 
 
71
        """Return a unsorted list of versions."""
 
 
72
        raise NotImplementedError(self.versions)
 
 
74
    def has_ghost(self, version_id):
 
 
75
        """Returns whether version is present as a ghost."""
 
 
76
        raise NotImplementedError(self.has_ghost)
 
 
78
    def has_version(self, version_id):
 
 
79
        """Returns whether version is present."""
 
 
80
        raise NotImplementedError(self.has_version)
 
 
82
    def add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
 
 
83
        """Add a text to the versioned file via a pregenerated delta.
 
 
85
        :param version_id: The version id being added.
 
 
86
        :param parents: The parents of the version_id.
 
 
87
        :param delta_parent: The parent this delta was created against.
 
 
88
        :param sha1: The sha1 of the full text.
 
 
89
        :param delta: The delta instructions. See get_delta for details.
 
 
91
        self._check_write_ok()
 
 
92
        if self.has_version(version_id):
 
 
93
            raise errors.RevisionAlreadyPresent(version_id, self)
 
 
94
        return self._add_delta(version_id, parents, delta_parent, sha1, noeol, delta)
 
 
96
    def _add_delta(self, version_id, parents, delta_parent, sha1, noeol, delta):
 
 
97
        """Class specific routine to add a delta.
 
 
99
        This generic version simply applies the delta to the delta_parent and
 
 
102
        # strip annotation from delta
 
 
104
        for start, stop, delta_len, delta_lines in delta:
 
 
105
            new_delta.append((start, stop, delta_len, [text for origin, text in delta_lines]))
 
 
106
        if delta_parent is not None:
 
 
107
            parent_full = self.get_lines(delta_parent)
 
 
110
        new_full = self._apply_delta(parent_full, new_delta)
 
 
111
        # its impossible to have noeol on an empty file
 
 
112
        if noeol and new_full[-1][-1] == '\n':
 
 
113
            new_full[-1] = new_full[-1][:-1]
 
 
114
        self.add_lines(version_id, parents, new_full)
 
 
116
    def add_lines(self, version_id, parents, lines, parent_texts=None):
 
 
117
        """Add a single text on top of the versioned file.
 
 
119
        Must raise RevisionAlreadyPresent if the new version is
 
 
120
        already present in file history.
 
 
122
        Must raise RevisionNotPresent if any of the given parents are
 
 
123
        not present in file history.
 
 
124
        :param parent_texts: An optional dictionary containing the opaque 
 
 
125
             representations of some or all of the parents of 
 
 
126
             version_id to allow delta optimisations. 
 
 
127
             VERY IMPORTANT: the texts must be those returned
 
 
128
             by add_lines or data corruption can be caused.
 
 
129
        :return: An opaque representation of the inserted version which can be
 
 
130
                 provided back to future add_lines calls in the parent_texts
 
 
133
        self._check_write_ok()
 
 
134
        return self._add_lines(version_id, parents, lines, parent_texts)
 
 
136
    def _add_lines(self, version_id, parents, lines, parent_texts):
 
 
137
        """Helper to do the class specific add_lines."""
 
 
138
        raise NotImplementedError(self.add_lines)
 
 
140
    def add_lines_with_ghosts(self, version_id, parents, lines,
 
 
142
        """Add lines to the versioned file, allowing ghosts to be present.
 
 
144
        This takes the same parameters as add_lines.
 
 
146
        self._check_write_ok()
 
 
147
        return self._add_lines_with_ghosts(version_id, parents, lines,
 
 
150
    def _add_lines_with_ghosts(self, version_id, parents, lines, parent_texts):
 
 
151
        """Helper to do class specific add_lines_with_ghosts."""
 
 
152
        raise NotImplementedError(self.add_lines_with_ghosts)
 
 
154
    def check(self, progress_bar=None):
 
 
155
        """Check the versioned file for integrity."""
 
 
156
        raise NotImplementedError(self.check)
 
 
158
    def _check_write_ok(self):
 
 
159
        """Is the versioned file marked as 'finished' ? Raise if it is."""
 
 
161
            raise errors.OutSideTransaction()
 
 
162
        if self._access_mode != 'w':
 
 
163
            raise errors.ReadOnlyObjectDirtiedError(self)
 
 
165
    def clear_cache(self):
 
 
166
        """Remove any data cached in the versioned file object."""
 
 
168
    def clone_text(self, new_version_id, old_version_id, parents):
 
 
169
        """Add an identical text to old_version_id as new_version_id.
 
 
171
        Must raise RevisionNotPresent if the old version or any of the
 
 
172
        parents are not present in file history.
 
 
174
        Must raise RevisionAlreadyPresent if the new version is
 
 
175
        already present in file history."""
 
 
176
        self._check_write_ok()
 
 
177
        return self._clone_text(new_version_id, old_version_id, parents)
 
 
179
    def _clone_text(self, new_version_id, old_version_id, parents):
 
 
180
        """Helper function to do the _clone_text work."""
 
 
181
        raise NotImplementedError(self.clone_text)
 
 
183
    def create_empty(self, name, transport, mode=None):
 
 
184
        """Create a new versioned file of this exact type.
 
 
186
        :param name: the file name
 
 
187
        :param transport: the transport
 
 
188
        :param mode: optional file mode.
 
 
190
        raise NotImplementedError(self.create_empty)
 
 
192
    def fix_parents(self, version, new_parents):
 
 
193
        """Fix the parents list for version.
 
 
195
        This is done by appending a new version to the index
 
 
196
        with identical data except for the parents list.
 
 
197
        the parents list must be a superset of the current
 
 
200
        self._check_write_ok()
 
 
201
        return self._fix_parents(version, new_parents)
 
 
203
    def _fix_parents(self, version, new_parents):
 
 
204
        """Helper for fix_parents."""
 
 
205
        raise NotImplementedError(self.fix_parents)
 
 
207
    def get_delta(self, version):
 
 
208
        """Get a delta for constructing version from some other version.
 
 
210
        :return: (delta_parent, sha1, noeol, delta)
 
 
211
        Where delta_parent is a version id or None to indicate no parent.
 
 
213
        raise NotImplementedError(self.get_delta)
 
 
215
    def get_deltas(self, versions):
 
 
216
        """Get multiple deltas at once for constructing versions.
 
 
218
        :return: dict(version_id:(delta_parent, sha1, noeol, delta))
 
 
219
        Where delta_parent is a version id or None to indicate no parent, and
 
 
220
        version_id is the version_id created by that delta.
 
 
223
        for version in versions:
 
 
224
            result[version] = self.get_delta(version)
 
 
227
    def get_suffixes(self):
 
 
228
        """Return the file suffixes associated with this versioned file."""
 
 
229
        raise NotImplementedError(self.get_suffixes)
 
 
231
    def get_text(self, version_id):
 
 
232
        """Return version contents as a text string.
 
 
234
        Raises RevisionNotPresent if version is not present in
 
 
237
        return ''.join(self.get_lines(version_id))
 
 
238
    get_string = get_text
 
 
240
    def get_lines(self, version_id):
 
 
241
        """Return version contents as a sequence of lines.
 
 
243
        Raises RevisionNotPresent if version is not present in
 
 
246
        raise NotImplementedError(self.get_lines)
 
 
248
    def get_ancestry(self, version_ids):
 
 
249
        """Return a list of all ancestors of given version(s). This
 
 
250
        will not include the null revision.
 
 
252
        Must raise RevisionNotPresent if any of the given versions are
 
 
253
        not present in file history."""
 
 
254
        if isinstance(version_ids, basestring):
 
 
255
            version_ids = [version_ids]
 
 
256
        raise NotImplementedError(self.get_ancestry)
 
 
258
    def get_ancestry_with_ghosts(self, version_ids):
 
 
259
        """Return a list of all ancestors of given version(s). This
 
 
260
        will not include the null revision.
 
 
262
        Must raise RevisionNotPresent if any of the given versions are
 
 
263
        not present in file history.
 
 
265
        Ghosts that are known about will be included in ancestry list,
 
 
266
        but are not explicitly marked.
 
 
268
        raise NotImplementedError(self.get_ancestry_with_ghosts)
 
 
271
        """Return a graph for the entire versioned file.
 
 
273
        Ghosts are not listed or referenced in the graph.
 
 
276
        for version in self.versions():
 
 
277
            result[version] = self.get_parents(version)
 
 
280
    def get_graph_with_ghosts(self):
 
 
281
        """Return a graph for the entire versioned file.
 
 
283
        Ghosts are referenced in parents list but are not
 
 
286
        raise NotImplementedError(self.get_graph_with_ghosts)
 
 
288
    @deprecated_method(zero_eight)
 
 
289
    def parent_names(self, version):
 
 
290
        """Return version names for parents of a version.
 
 
292
        See get_parents for the current api.
 
 
294
        return self.get_parents(version)
 
 
296
    def get_parents(self, version_id):
 
 
297
        """Return version names for parents of a version.
 
 
299
        Must raise RevisionNotPresent if version is not present in
 
 
302
        raise NotImplementedError(self.get_parents)
 
 
304
    def get_parents_with_ghosts(self, version_id):
 
 
305
        """Return version names for parents of version_id.
 
 
307
        Will raise RevisionNotPresent if version_id is not present
 
 
310
        Ghosts that are known about will be included in the parent list,
 
 
311
        but are not explicitly marked.
 
 
313
        raise NotImplementedError(self.get_parents_with_ghosts)
 
 
315
    def annotate_iter(self, version_id):
 
 
316
        """Yield list of (version-id, line) pairs for the specified
 
 
319
        Must raise RevisionNotPresent if any of the given versions are
 
 
320
        not present in file history.
 
 
322
        raise NotImplementedError(self.annotate_iter)
 
 
324
    def annotate(self, version_id):
 
 
325
        return list(self.annotate_iter(version_id))
 
 
327
    def _apply_delta(self, lines, delta):
 
 
328
        """Apply delta to lines."""
 
 
331
        for start, end, count, delta_lines in delta:
 
 
332
            lines[offset+start:offset+end] = delta_lines
 
 
333
            offset = offset + (start - end) + count
 
 
336
    def join(self, other, pb=None, msg=None, version_ids=None,
 
 
337
             ignore_missing=False):
 
 
338
        """Integrate versions from other into this versioned file.
 
 
340
        If version_ids is None all versions from other should be
 
 
341
        incorporated into this versioned file.
 
 
343
        Must raise RevisionNotPresent if any of the specified versions
 
 
344
        are not present in the other files history unless ignore_missing
 
 
345
        is supplied when they are silently skipped.
 
 
347
        self._check_write_ok()
 
 
348
        return InterVersionedFile.get(other, self).join(
 
 
354
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
 
 
355
        """Iterate over the lines in the versioned file from version_ids.
 
 
357
        This may return lines from other versions, and does not return the
 
 
358
        specific version marker at this point. The api may be changed
 
 
359
        during development to include the version that the versioned file
 
 
360
        thinks is relevant, but given that such hints are just guesses,
 
 
361
        its better not to have it if we dont need it.
 
 
363
        NOTES: Lines are normalised: they will all have \n terminators.
 
 
364
               Lines are returned in arbitrary order.
 
 
366
        raise NotImplementedError(self.iter_lines_added_or_present_in_versions)
 
 
368
    def transaction_finished(self):
 
 
369
        """The transaction that this file was opened in has finished.
 
 
371
        This records self.finished = True and should cause all mutating
 
 
376
    @deprecated_method(zero_eight)
 
 
377
    def walk(self, version_ids=None):
 
 
378
        """Walk the versioned file as a weave-like structure, for
 
 
379
        versions relative to version_ids.  Yields sequence of (lineno,
 
 
380
        insert, deletes, text) for each relevant line.
 
 
382
        Must raise RevisionNotPresent if any of the specified versions
 
 
383
        are not present in the file history.
 
 
385
        :param version_ids: the version_ids to walk with respect to. If not
 
 
386
                            supplied the entire weave-like structure is walked.
 
 
388
        walk is deprecated in favour of iter_lines_added_or_present_in_versions
 
 
390
        raise NotImplementedError(self.walk)
 
 
392
    @deprecated_method(zero_eight)
 
 
393
    def iter_names(self):
 
 
394
        """Walk the names list."""
 
 
395
        return iter(self.versions())
 
 
397
    def plan_merge(versionedfile, ver_a, ver_b):
 
 
398
        return PlanWeaveMerge.plan_merge(versionedfile, ver_a, ver_b)
 
 
400
    def weave_merge(self, plan, a_marker='<<<<<<< \n', b_marker='>>>>>>> \n'):
 
 
401
        return PlanWeaveMerge(plan, a_marker, b_marker).merge_lines()[0]
 
 
403
class PlanWeaveMerge(TextMerge):
 
 
404
    def __init__(self, plan, a_marker='<<<<<<< \n', b_marker='>>>>>>> \n'):
 
 
405
        TextMerge.__init__(self, a_marker, b_marker)
 
 
409
    def plan_merge(versionedfile, ver_a, ver_b):
 
 
410
        """Return pseudo-annotation indicating how the two versions merge.
 
 
412
        This is computed between versions a and b and their common
 
 
415
        Weave lines present in none of them are skipped entirely.
 
 
417
        inc_a = set(versionedfile.get_ancestry([ver_a]))
 
 
418
        inc_b = set(versionedfile.get_ancestry([ver_b]))
 
 
419
        inc_c = inc_a & inc_b
 
 
421
        for lineno, insert, deleteset, line in\
 
 
422
            versionedfile.walk([ver_a, ver_b]):
 
 
423
            if deleteset & inc_c:
 
 
424
                # killed in parent; can't be in either a or b
 
 
425
                # not relevant to our work
 
 
426
                yield 'killed-base', line
 
 
427
            elif insert in inc_c:
 
 
428
                # was inserted in base
 
 
429
                killed_a = bool(deleteset & inc_a)
 
 
430
                killed_b = bool(deleteset & inc_b)
 
 
431
                if killed_a and killed_b:
 
 
432
                    yield 'killed-both', line
 
 
434
                    yield 'killed-a', line
 
 
436
                    yield 'killed-b', line
 
 
438
                    yield 'unchanged', line
 
 
439
            elif insert in inc_a:
 
 
440
                if deleteset & inc_a:
 
 
441
                    yield 'ghost-a', line
 
 
445
            elif insert in inc_b:
 
 
446
                if deleteset & inc_b:
 
 
447
                    yield 'ghost-b', line
 
 
451
                # not in either revision
 
 
452
                yield 'irrelevant', line
 
 
454
        yield 'unchanged', ''           # terminator
 
 
456
    def _merge_struct(self):
 
 
460
        # TODO: Show some version information (e.g. author, date) on 
 
 
461
        # conflicted regions.
 
 
463
        # We previously considered either 'unchanged' or 'killed-both' lines
 
 
464
        # to be possible places to resynchronize.  However, assuming agreement
 
 
465
        # on killed-both lines may be too agressive. -- mbp 20060324
 
 
466
        for state, line in self.plan:
 
 
467
            if state == 'unchanged':
 
 
468
                # resync and flush queued conflicts changes if any
 
 
469
                if not lines_a and not lines_b:
 
 
471
                elif ch_a and not ch_b:
 
 
474
                elif ch_b and not ch_a:
 
 
476
                elif lines_a == lines_b:
 
 
479
                    yield (lines_a, lines_b)
 
 
485
            if state == 'unchanged':
 
 
488
            elif state == 'killed-a':
 
 
491
            elif state == 'killed-b':
 
 
494
            elif state == 'new-a':
 
 
497
            elif state == 'new-b':
 
 
501
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 
 
 
502
                                 'killed-base', 'killed-both'), state
 
 
505
class WeaveMerge(PlanWeaveMerge):
 
 
506
    def __init__(self, versionedfile, ver_a, ver_b, 
 
 
507
        a_marker='<<<<<<< \n', b_marker='>>>>>>> \n'):
 
 
508
        plan = self.plan_merge(versionedfile, ver_a, ver_b)
 
 
509
        PlanWeaveMerge.__init__(self, plan, a_marker, b_marker)
 
 
512
class InterVersionedFile(InterObject):
 
 
513
    """This class represents operations taking place between two versionedfiles..
 
 
515
    Its instances have methods like join, and contain
 
 
516
    references to the source and target versionedfiles these operations can be 
 
 
519
    Often we will provide convenience methods on 'versionedfile' which carry out
 
 
520
    operations with another versionedfile - they will always forward to
 
 
521
    InterVersionedFile.get(other).method_name(parameters).
 
 
525
    """The available optimised InterVersionedFile types."""
 
 
527
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
 
 
528
        """Integrate versions from self.source into self.target.
 
 
530
        If version_ids is None all versions from source should be
 
 
531
        incorporated into this versioned file.
 
 
533
        Must raise RevisionNotPresent if any of the specified versions
 
 
534
        are not present in the other files history unless ignore_missing is 
 
 
535
        supplied when they are silently skipped.
 
 
538
        # - if the target is empty, just add all the versions from 
 
 
539
        #   source to target, otherwise:
 
 
540
        # - make a temporary versioned file of type target
 
 
541
        # - insert the source content into it one at a time
 
 
543
        if not self.target.versions():
 
 
546
            # Make a new target-format versioned file. 
 
 
547
            temp_source = self.target.create_empty("temp", MemoryTransport())
 
 
549
        graph = self.source.get_graph()
 
 
550
        order = topo_sort(graph.items())
 
 
551
        pb = ui.ui_factory.nested_progress_bar()
 
 
554
            # TODO for incremental cross-format work:
 
 
555
            # make a versioned file with the following content:
 
 
556
            # all revisions we have been asked to join
 
 
557
            # all their ancestors that are *not* in target already.
 
 
558
            # the immediate parents of the above two sets, with 
 
 
559
            # empty parent lists - these versions are in target already
 
 
560
            # and the incorrect version data will be ignored.
 
 
561
            # TODO: for all ancestors that are present in target already,
 
 
562
            # check them for consistent data, this requires moving sha1 from
 
 
564
            # TODO: remove parent texts when they are not relevant any more for 
 
 
565
            # memory pressure reduction. RBC 20060313
 
 
566
            # pb.update('Converting versioned data', 0, len(order))
 
 
567
            # deltas = self.source.get_deltas(order)
 
 
568
            for index, version in enumerate(order):
 
 
569
                pb.update('Converting versioned data', index, len(order))
 
 
570
                parent_text = target.add_lines(version,
 
 
571
                                               self.source.get_parents(version),
 
 
572
                                               self.source.get_lines(version),
 
 
573
                                               parent_texts=parent_texts)
 
 
574
                parent_texts[version] = parent_text
 
 
575
                #delta_parent, sha1, noeol, delta = deltas[version]
 
 
576
                #target.add_delta(version,
 
 
577
                #                 self.source.get_parents(version),
 
 
582
                #target.get_lines(version)
 
 
584
            # this should hit the native code path for target
 
 
585
            if target is not self.target:
 
 
586
                return self.target.join(temp_source,
 
 
595
class InterVersionedFileTestProviderAdapter(object):
 
 
596
    """A tool to generate a suite testing multiple inter versioned-file classes.
 
 
598
    This is done by copying the test once for each interversionedfile provider
 
 
599
    and injecting the transport_server, transport_readonly_server,
 
 
600
    versionedfile_factory and versionedfile_factory_to classes into each copy.
 
 
601
    Each copy is also given a new id() to make it easy to identify.
 
 
604
    def __init__(self, transport_server, transport_readonly_server, formats):
 
 
605
        self._transport_server = transport_server
 
 
606
        self._transport_readonly_server = transport_readonly_server
 
 
607
        self._formats = formats
 
 
609
    def adapt(self, test):
 
 
611
        for (interversionedfile_class,
 
 
612
             versionedfile_factory,
 
 
613
             versionedfile_factory_to) in self._formats:
 
 
614
            new_test = deepcopy(test)
 
 
615
            new_test.transport_server = self._transport_server
 
 
616
            new_test.transport_readonly_server = self._transport_readonly_server
 
 
617
            new_test.interversionedfile_class = interversionedfile_class
 
 
618
            new_test.versionedfile_factory = versionedfile_factory
 
 
619
            new_test.versionedfile_factory_to = versionedfile_factory_to
 
 
620
            def make_new_test_id():
 
 
621
                new_id = "%s(%s)" % (new_test.id(), interversionedfile_class.__name__)
 
 
622
                return lambda: new_id
 
 
623
            new_test.id = make_new_test_id()
 
 
624
            result.addTest(new_test)
 
 
628
    def default_test_list():
 
 
629
        """Generate the default list of interversionedfile permutations to test."""
 
 
630
        from bzrlib.weave import WeaveFile
 
 
631
        from bzrlib.knit import KnitVersionedFile
 
 
633
        # test the fallback InterVersionedFile from weave to annotated knits
 
 
634
        result.append((InterVersionedFile, 
 
 
637
        for optimiser in InterVersionedFile._optimisers:
 
 
638
            result.append((optimiser,
 
 
639
                           optimiser._matching_file_factory,
 
 
640
                           optimiser._matching_file_factory
 
 
642
        # if there are specific combinations we want to use, we can add them