3
# Copyright (C) 2005 Canonical Ltd
 
 
5
# This program is free software; you can redistribute it and/or modify
 
 
6
# it under the terms of the GNU General Public License as published by
 
 
7
# the Free Software Foundation; either version 2 of the License, or
 
 
8
# (at your option) any later version.
 
 
10
# This program is distributed in the hope that it will be useful,
 
 
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
13
# GNU General Public License for more details.
 
 
15
# You should have received a copy of the GNU General Public License
 
 
16
# along with this program; if not, write to the Free Software
 
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
19
# Author: Martin Pool <mbp@canonical.com>
 
 
22
"""Weave - storage of related text file versions"""
 
 
24
# before intset (r923) 2000 versions in 41.5s
 
 
25
# with intset (r926) 2000 versions in 93s !!!
 
 
26
# better to just use plain sets.
 
 
28
# making _extract build and return a list, rather than being a generator
 
 
31
# with python -O, r923 does 2000 versions in 36.87s
 
 
33
# with optimizations to avoid mutating lists - 35.75!  I guess copying
 
 
34
# all the elements every time costs more than the small manipulations.
 
 
35
# a surprisingly small change.
 
 
37
# r931, which avoids using a generator for extract, does 36.98s
 
 
39
# with memoized inclusions, takes 41.49s; not very good
 
 
41
# with slots, takes 37.35s; without takes 39.16, a bit surprising
 
 
43
# with the delta calculation mixed in with the add method, rather than
 
 
44
# separated, takes 36.78s
 
 
46
# with delta folded in and mutation of the list, 36.13s
 
 
48
# with all this and simplification of add code, 33s 
 
 
51
# TODO: Perhaps have copy method for Weave instances?
 
 
53
# XXX: If we do weaves this way, will a merge still behave the same
 
 
54
# way if it's done in a different order?  That's a pretty desirable
 
 
57
# TODO: Nothing here so far assumes the lines are really \n newlines,
 
 
58
# rather than being split up in some other way.  We could accomodate
 
 
59
# binaries, perhaps by naively splitting on \n or perhaps using
 
 
60
# something like a rolling checksum.
 
 
62
# TODO: Track version names as well as indexes. 
 
 
64
# TODO: End marker for each version so we can stop reading?
 
 
66
# TODO: Check that no insertion occurs inside a deletion that was
 
 
67
# active in the version of the insertion.
 
 
69
# TODO: In addition to the SHA-1 check, perhaps have some code that
 
 
70
# checks structural constraints of the weave: ie that insertions are
 
 
71
# properly nested, that there is no text outside of an insertion, that
 
 
72
# insertions or deletions are not repeated, etc.
 
 
74
# TODO: Parallel-extract that passes back each line along with a
 
 
75
# description of which revisions include it.  Nice for checking all
 
 
81
class WeaveError(Exception):
 
 
82
    """Exception in processing weave"""
 
 
85
class WeaveFormatError(WeaveError):
 
 
86
    """Weave invariant violated"""
 
 
90
    """weave - versioned text file storage.
 
 
92
    A Weave manages versions of line-based text files, keeping track
 
 
93
    of the originating version for each line.
 
 
95
    To clients the "lines" of the file are represented as a list of strings.
 
 
96
    These strings  will typically have terminal newline characters, but
 
 
97
    this is not required.  In particular files commonly do not have a newline
 
 
98
    at the end of the file.
 
 
100
    Texts can be identified in either of two ways:
 
 
102
    * a nonnegative index number.
 
 
104
    * a version-id string.
 
 
106
    Typically the index number will be valid only inside this weave and
 
 
107
    the version-id is used to reference it in the larger world.
 
 
109
    The weave is represented as a list mixing edit instructions and
 
 
110
    literal text.  Each entry in _weave can be either a string (or
 
 
111
    unicode), or a tuple.  If a string, it means that the given line
 
 
112
    should be output in the currently active revisions.
 
 
114
    If a tuple, it gives a processing instruction saying in which
 
 
115
    revisions the enclosed lines are active.  The tuple has the form
 
 
116
    (instruction, version).
 
 
118
    The instruction can be '{' or '}' for an insertion block, and '['
 
 
119
    and ']' for a deletion block respectively.  The version is the
 
 
120
    integer version index.  There is no replace operator, only deletes
 
 
125
    * A later version can delete lines that were introduced by any
 
 
126
      number of ancestor versions; this implies that deletion
 
 
127
      instructions can span insertion blocks without regard to the
 
 
128
      insertion block's nesting.
 
 
130
    * Similarly, deletions need not be properly nested with regard to
 
 
131
      each other, because they might have been generated by
 
 
132
      independent revisions.
 
 
134
    * Insertions are always made by inserting a new bracketed block
 
 
135
      into a single point in the previous weave.  This implies they
 
 
136
      can nest but not overlap, and the nesting must always have later
 
 
137
      insertions on the inside.
 
 
139
    * It doesn't seem very useful to have an active insertion
 
 
140
      inside an inactive insertion, but it might happen.
 
 
142
    * Therefore, all instructions are always"considered"; that
 
 
143
      is passed onto and off the stack.  An outer inactive block
 
 
144
      doesn't disable an inner block.
 
 
146
    * Lines are enabled if the most recent enclosing insertion is
 
 
147
      active and none of the enclosing deletions are active.
 
 
149
    * There is no point having a deletion directly inside its own
 
 
150
      insertion; you might as well just not write it.  And there
 
 
151
      should be no way to get an earlier version deleting a later
 
 
155
        Text of the weave; list of control instruction tuples and strings.
 
 
158
        List of parents, indexed by version number.
 
 
159
        It is only necessary to store the minimal set of parents for
 
 
160
        each version; the parent's parents are implied.
 
 
163
        List of hex SHA-1 of each version, or None if not recorded.
 
 
166
    __slots__ = ['_weave', '_parents', '_sha1s']
 
 
174
    def __eq__(self, other):
 
 
175
        if not isinstance(other, Weave):
 
 
177
        return self._parents == other._parents \
 
 
178
               and self._weave == other._weave
 
 
181
    def __ne__(self, other):
 
 
182
        return not self.__eq__(other)
 
 
185
    def add(self, parents, text):
 
 
186
        """Add a single text on top of the weave.
 
 
188
        Returns the index number of the newly added version.
 
 
191
            List or set of direct parent version numbers.
 
 
194
            Sequence of lines to be added in the new version."""
 
 
196
        self._check_versions(parents)
 
 
197
        ## self._check_lines(text)
 
 
198
        new_version = len(self._parents)
 
 
206
        # if we abort after here the weave will be corrupt
 
 
207
        self._parents.append(frozenset(parents))
 
 
208
        self._sha1s.append(sha1)
 
 
212
            # special case; adding with no parents revision; can do
 
 
213
            # this more quickly by just appending unconditionally.
 
 
214
            # even more specially, if we're adding an empty text we
 
 
215
            # need do nothing at all.
 
 
217
                self._weave.append(('{', new_version))
 
 
218
                self._weave.extend(text)
 
 
219
                self._weave.append(('}', new_version))
 
 
223
        if len(parents) == 1:
 
 
224
            pv = list(parents)[0]
 
 
225
            if sha1 == self._sha1s[pv]:
 
 
226
                # special case: same as the single parent
 
 
230
        ancestors = self.inclusions(parents)
 
 
234
        # basis a list of (origin, lineno, line)
 
 
237
        for origin, lineno, line in self._extract(ancestors):
 
 
238
            basis_lineno.append(lineno)
 
 
239
            basis_lines.append(line)
 
 
241
        # another small special case: a merge, producing the same text
 
 
243
        if text == basis_lines:
 
 
246
        # add a sentinal, because we can also match against the final line
 
 
247
        basis_lineno.append(len(self._weave))
 
 
249
        # XXX: which line of the weave should we really consider
 
 
250
        # matches the end of the file?  the current code says it's the
 
 
251
        # last line of the weave?
 
 
253
        #print 'basis_lines:', basis_lines
 
 
254
        #print 'new_lines:  ', lines
 
 
256
        from difflib import SequenceMatcher
 
 
257
        s = SequenceMatcher(None, basis_lines, text)
 
 
259
        # offset gives the number of lines that have been inserted
 
 
260
        # into the weave up to the current point; if the original edit instruction
 
 
261
        # says to change line A then we actually change (A+offset)
 
 
264
        for tag, i1, i2, j1, j2 in s.get_opcodes():
 
 
265
            # i1,i2 are given in offsets within basis_lines; we need to map them
 
 
266
            # back to offsets within the entire weave
 
 
267
            #print 'raw match', tag, i1, i2, j1, j2
 
 
271
            i1 = basis_lineno[i1]
 
 
272
            i2 = basis_lineno[i2]
 
 
274
            assert 0 <= j1 <= j2 <= len(text)
 
 
276
            #print tag, i1, i2, j1, j2
 
 
278
            # the deletion and insertion are handled separately.
 
 
279
            # first delete the region.
 
 
281
                self._weave.insert(i1+offset, ('[', new_version))
 
 
282
                self._weave.insert(i2+offset+1, (']', new_version))
 
 
286
                # there may have been a deletion spanning up to
 
 
287
                # i2; we want to insert after this region to make sure
 
 
288
                # we don't destroy ourselves
 
 
290
                self._weave[i:i] = ([('{', new_version)] 
 
 
292
                                + [('}', new_version)])
 
 
293
                offset += 2 + (j2 - j1)
 
 
298
    def inclusions(self, versions):
 
 
299
        """Return set of all ancestors of given version(s)."""
 
 
305
                    # include all its parents
 
 
306
                    i.update(self._parents[v])
 
 
310
            raise ValueError("version %d not present in weave" % v)
 
 
313
    def minimal_parents(self, version):
 
 
314
        """Find the minimal set of parents for the version."""
 
 
315
        included = self._parents[version]
 
 
320
        li.sort(reverse=True)
 
 
328
                gotit.update(self.inclusions(pv))
 
 
330
        assert mininc[0] >= 0
 
 
331
        assert mininc[-1] < version
 
 
336
    def _check_lines(self, text):
 
 
337
        if not isinstance(text, list):
 
 
338
            raise ValueError("text should be a list, not %s" % type(text))
 
 
341
            if not isinstance(l, basestring):
 
 
342
                raise ValueError("text line should be a string or unicode, not %s"
 
 
347
    def _check_versions(self, indexes):
 
 
348
        """Check everything in the sequence of indexes is valid"""
 
 
353
                raise IndexError("invalid version number %r" % i)
 
 
356
    def annotate(self, index):
 
 
357
        return list(self.annotate_iter(index))
 
 
360
    def annotate_iter(self, version):
 
 
361
        """Yield list of (index-id, line) pairs for the specified version.
 
 
363
        The index indicates when the line originated in the weave."""
 
 
364
        for origin, lineno, text in self._extract([version]):
 
 
372
        (lineno, insert, deletes, text)
 
 
373
        for each literal line.
 
 
379
        lineno = 0         # line of weave, 0-based
 
 
381
        for l in self._weave:
 
 
382
            if isinstance(l, tuple):
 
 
395
                    raise WeaveFormatError('unexpected instruction %r'
 
 
398
                assert isinstance(l, basestring)
 
 
400
                yield lineno, istack[-1], dset, l
 
 
405
    def _extract(self, versions):
 
 
406
        """Yield annotation of lines in included set.
 
 
408
        Yields a sequence of tuples (origin, lineno, text), where
 
 
409
        origin is the origin version, lineno the index in the weave,
 
 
410
        and text the text of the line.
 
 
412
        The set typically but not necessarily corresponds to a version.
 
 
414
        included = self.inclusions(versions)
 
 
419
        lineno = 0         # line of weave, 0-based
 
 
425
        WFE = WeaveFormatError
 
 
427
        for l in self._weave:
 
 
428
            if isinstance(l, tuple):
 
 
432
                    assert v not in istack
 
 
447
                assert isinstance(l, basestring)
 
 
449
                    isactive = (not dset) and istack and (istack[-1] in included)
 
 
451
                    result.append((istack[-1], lineno, l))
 
 
455
            raise WFE("unclosed insertion blocks at end of weave",
 
 
458
            raise WFE("unclosed deletion blocks at end of weave",
 
 
465
    def get_iter(self, version):
 
 
466
        """Yield lines for the specified version."""
 
 
467
        for origin, lineno, line in self._extract([version]):
 
 
471
    def get(self, index):
 
 
472
        return list(self.get_iter(index))
 
 
475
    def mash_iter(self, included):
 
 
476
        """Return composed version of multiple included versions."""
 
 
477
        for origin, lineno, text in self._extract(included):
 
 
481
    def dump(self, to_file):
 
 
482
        from pprint import pprint
 
 
483
        print >>to_file, "Weave._weave = ",
 
 
484
        pprint(self._weave, to_file)
 
 
485
        print >>to_file, "Weave._parents = ",
 
 
486
        pprint(self._parents, to_file)
 
 
490
    def numversions(self):
 
 
491
        l = len(self._parents)
 
 
492
        assert l == len(self._sha1s)
 
 
497
        return self.numversions()
 
 
500
    def check(self, progress_bar=None):
 
 
501
        # check no circular inclusions
 
 
502
        for version in range(self.numversions()):
 
 
503
            inclusions = list(self._parents[version])
 
 
506
                if inclusions[-1] >= version:
 
 
507
                    raise WeaveFormatError("invalid included version %d for index %d"
 
 
508
                                           % (inclusions[-1], version))
 
 
510
        # try extracting all versions; this is a bit slow and parallel
 
 
511
        # extraction could be used
 
 
513
        nv = self.numversions()
 
 
514
        for version in range(nv):
 
 
516
                progress_bar.update('checking text', version, nv)
 
 
518
            for l in self.get_iter(version):
 
 
521
            expected = self._sha1s[version]
 
 
523
                raise WeaveError("mismatched sha1 for version %d; "
 
 
524
                                 "got %s, expected %s"
 
 
525
                                 % (version, hd, expected))
 
 
527
        # TODO: check insertions are properly nested, that there are
 
 
528
        # no lines outside of insertion blocks, that deletions are
 
 
529
        # properly paired, etc.
 
 
533
    def merge(self, merge_versions):
 
 
534
        """Automerge and mark conflicts between versions.
 
 
536
        This returns a sequence, each entry describing alternatives
 
 
537
        for a chunk of the file.  Each of the alternatives is given as
 
 
540
        If there is a chunk of the file where there's no diagreement,
 
 
541
        only one alternative is given.
 
 
544
        # approach: find the included versions common to all the
 
 
546
        raise NotImplementedError()
 
 
550
    def _delta(self, included, lines):
 
 
551
        """Return changes from basis to new revision.
 
 
553
        The old text for comparison is the union of included revisions.
 
 
555
        This is used in inserting a new text.
 
 
557
        Delta is returned as a sequence of
 
 
558
        (weave1, weave2, newlines).
 
 
560
        This indicates that weave1:weave2 of the old weave should be
 
 
561
        replaced by the sequence of lines in newlines.  Note that
 
 
562
        these line numbers are positions in the total weave and don't
 
 
563
        correspond to the lines in any extracted version, or even the
 
 
564
        extracted union of included versions.
 
 
566
        If line1=line2, this is a pure insert; if newlines=[] this is a
 
 
567
        pure delete.  (Similar to difflib.)
 
 
572
    def plan_merge(self, ver_a, ver_b):
 
 
573
        """Return pseudo-annotation indicating how the two versions merge.
 
 
575
        This is computed between versions a and b and their common
 
 
578
        Weave lines present in none of them are skipped entirely.
 
 
580
        inc_a = self.inclusions([ver_a])
 
 
581
        inc_b = self.inclusions([ver_b])
 
 
582
        inc_c = inc_a & inc_b
 
 
584
        for lineno, insert, deleteset, line in self._walk():
 
 
585
            if deleteset & inc_c:
 
 
586
                # killed in parent; can't be in either a or b
 
 
587
                # not relevant to our work
 
 
588
                yield 'killed-base', line
 
 
589
            elif insert in inc_c:
 
 
590
                # was inserted in base
 
 
591
                killed_a = bool(deleteset & inc_a)
 
 
592
                killed_b = bool(deleteset & inc_b)
 
 
593
                if killed_a and killed_b:
 
 
594
                    yield 'killed-both', line
 
 
596
                    yield 'killed-a', line
 
 
598
                    yield 'killed-b', line
 
 
600
                    yield 'unchanged', line
 
 
601
            elif insert in inc_a:
 
 
602
                if deleteset & inc_a:
 
 
603
                    yield 'ghost-a', line
 
 
607
            elif insert in inc_b:
 
 
608
                if deleteset & inc_b:
 
 
609
                    yield 'ghost-b', line
 
 
613
                # not in either revision
 
 
614
                yield 'irrelevant', line
 
 
616
        yield 'unchanged', ''           # terminator
 
 
620
    def weave_merge(self, plan):
 
 
625
        for state, line in plan:
 
 
626
            if state == 'unchanged' or state == 'killed-both':
 
 
627
                # resync and flush queued conflicts changes if any
 
 
628
                if not lines_a and not lines_b:
 
 
630
                elif ch_a and not ch_b:
 
 
632
                    for l in lines_a: yield l
 
 
633
                elif ch_b and not ch_a:
 
 
634
                    for l in lines_b: yield l
 
 
635
                elif lines_a == lines_b:
 
 
636
                    for l in lines_a: yield l
 
 
639
                    for l in lines_a: yield l
 
 
641
                    for l in lines_b: yield l
 
 
648
            if state == 'unchanged':
 
 
651
            elif state == 'killed-a':
 
 
654
            elif state == 'killed-b':
 
 
657
            elif state == 'new-a':
 
 
660
            elif state == 'new-b':
 
 
664
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 'killed-base',
 
 
675
    """Show some text information about the weave."""
 
 
676
    print '%6s %40s %20s' % ('ver', 'sha1', 'parents')
 
 
677
    for i in (6, 40, 20):
 
 
680
    for i in range(w.numversions()):
 
 
682
        print '%6d %40s %s' % (i, sha1, ' '.join(map(str, w._parents[i])))
 
 
686
def weave_stats(weave_file):
 
 
687
    from bzrlib.progress import ProgressBar
 
 
688
    from bzrlib.weavefile import read_weave
 
 
692
    wf = file(weave_file, 'rb')
 
 
694
    # FIXME: doesn't work on pipes
 
 
695
    weave_size = wf.tell()
 
 
699
    for i in range(vers):
 
 
700
        pb.update('checking sizes', i, vers)
 
 
701
        for line in w.get_iter(i):
 
 
706
    print 'versions          %9d' % vers
 
 
707
    print 'weave file        %9d bytes' % weave_size
 
 
708
    print 'total contents    %9d bytes' % total
 
 
709
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
 
 
712
        print 'average size      %9d bytes' % avg
 
 
713
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
 
 
717
    print """bzr weave tool
 
 
719
Experimental tool for weave algorithm.
 
 
723
        Create an empty weave file
 
 
724
    weave get WEAVEFILE VERSION
 
 
725
        Write out specified version.
 
 
726
    weave check WEAVEFILE
 
 
727
        Check consistency of all versions.
 
 
729
        Display table of contents.
 
 
730
    weave add WEAVEFILE [BASE...] < NEWTEXT
 
 
731
        Add NEWTEXT, with specified parent versions.
 
 
732
    weave annotate WEAVEFILE VERSION
 
 
733
        Display origin of each line.
 
 
734
    weave mash WEAVEFILE VERSION...
 
 
735
        Display composite of all selected versions.
 
 
736
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
 
 
737
        Auto-merge two versions and display conflicts.
 
 
741
    % weave init foo.weave
 
 
743
    % weave add foo.weave < foo.txt
 
 
746
    (create updated version)
 
 
748
    % weave get foo.weave 0 | diff -u - foo.txt
 
 
749
    % weave add foo.weave 0 < foo.txt
 
 
752
    % weave get foo.weave 0 > foo.txt       (create forked version)
 
 
754
    % weave add foo.weave 0 < foo.txt
 
 
757
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
 
 
758
    % vi foo.txt                            (resolve conflicts)
 
 
759
    % weave add foo.weave 1 2 < foo.txt     (commit merged version)     
 
 
768
    from weavefile import write_weave, read_weave
 
 
769
    from bzrlib.progress import ProgressBar
 
 
777
        return read_weave(file(argv[2], 'rb'))
 
 
783
        # at the moment, based on everything in the file
 
 
784
        parents = map(int, argv[3:])
 
 
785
        lines = sys.stdin.readlines()
 
 
786
        ver = w.add(parents, lines)
 
 
787
        write_weave(w, file(argv[2], 'wb'))
 
 
788
        print 'added version %d' % ver
 
 
791
        if os.path.exists(fn):
 
 
792
            raise IOError("file exists")
 
 
794
        write_weave(w, file(fn, 'wb'))
 
 
795
    elif cmd == 'get': # get one version
 
 
797
        sys.stdout.writelines(w.get_iter(int(argv[3])))
 
 
799
    elif cmd == 'mash': # get composite
 
 
801
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
 
 
803
    elif cmd == 'annotate':
 
 
805
        # newline is added to all lines regardless; too hard to get
 
 
806
        # reasonable formatting otherwise
 
 
808
        for origin, text in w.annotate(int(argv[3])):
 
 
809
            text = text.rstrip('\r\n')
 
 
811
                print '      | %s' % (text)
 
 
813
                print '%5d | %s' % (origin, text)
 
 
827
        print '%d versions ok' % w.numversions()
 
 
829
    elif cmd == 'inclusions':
 
 
831
        print ' '.join(map(str, w.inclusions([int(argv[3])])))
 
 
833
    elif cmd == 'parents':
 
 
835
        print ' '.join(map(str, w._parents[int(argv[3])]))
 
 
837
    elif cmd == 'plan-merge':
 
 
839
        for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
 
 
841
                print '%14s | %s' % (state, line),
 
 
845
        p = w.plan_merge(int(argv[3]), int(argv[4]))
 
 
846
        sys.stdout.writelines(w.weave_merge(p))
 
 
848
    elif cmd == 'mash-merge':
 
 
854
        v1, v2 = map(int, argv[3:5])
 
 
856
        basis = w.inclusions([v1]).intersection(w.inclusions([v2]))
 
 
858
        base_lines = list(w.mash_iter(basis))
 
 
859
        a_lines = list(w.get(v1))
 
 
860
        b_lines = list(w.get(v2))
 
 
862
        from bzrlib.merge3 import Merge3
 
 
863
        m3 = Merge3(base_lines, a_lines, b_lines)
 
 
865
        name_a = 'version %d' % v1
 
 
866
        name_b = 'version %d' % v2
 
 
867
        sys.stdout.writelines(m3.merge_lines(name_a=name_a, name_b=name_b))
 
 
869
        raise ValueError('unknown command %r' % cmd)
 
 
872
if __name__ == '__main__':
 
 
874
    sys.exit(main(sys.argv))