~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

Refactored the export code to make it easier to add new export formats.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
 
22
22
"""Weave - storage of related text file versions"""
23
23
 
24
 
# before intset (r923) 2000 versions in 41.5s
25
 
# with intset (r926) 2000 versions in 93s !!!
26
 
# better to just use plain sets.
27
 
 
28
 
# making _extract build and return a list, rather than being a generator
29
 
# takes 37.94s
30
 
 
31
 
# with python -O, r923 does 2000 versions in 36.87s
32
 
 
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.
36
 
 
37
 
# r931, which avoids using a generator for extract, does 36.98s
38
 
 
39
 
# with memoized inclusions, takes 41.49s; not very good
40
 
 
41
 
# with slots, takes 37.35s; without takes 39.16, a bit surprising
42
 
 
43
 
# with the delta calculation mixed in with the add method, rather than
44
 
# separated, takes 36.78s
45
 
 
46
 
# with delta folded in and mutation of the list, 36.13s
47
 
 
48
 
# with all this and simplification of add code, 33s
49
 
 
50
 
 
51
 
 
52
 
 
53
 
 
54
 
# TODO: Perhaps have copy method for Weave instances?
55
24
 
56
25
# XXX: If we do weaves this way, will a merge still behave the same
57
26
# way if it's done in a different order?  That's a pretty desirable
74
43
 
75
44
# TODO: Parallel-extract that passes back each line along with a
76
45
# description of which revisions include it.  Nice for checking all
77
 
# shas in parallel.
 
46
# shas or calculating stats in parallel.
78
47
 
79
48
# TODO: Using a single _extract routine and then processing the output
80
49
# is probably inefficient.  It's simple enough that we can afford to
81
50
# have slight specializations for different ways its used: annotate,
82
51
# basis for add, get, etc.
83
52
 
84
 
# TODO: Perhaps the API should work only in names to hide the integer
85
 
# indexes from the user?
86
 
 
 
53
# TODO: Probably the API should work only in names to hide the integer
 
54
# indexes from the user.
 
55
 
 
56
# TODO: Is there any potential performance win by having an add()
 
57
# variant that is passed a pre-cooked version of the single basis
 
58
# version?
 
59
 
 
60
# TODO: Reweave can possibly be made faster by remembering diffs
 
61
# where the basis and destination are unchanged.
 
62
 
 
63
# FIXME: Sometimes we will be given a parents list for a revision
 
64
# that includes some redundant parents (i.e. already a parent of 
 
65
# something in the list.)  We should eliminate them.  This can 
 
66
# be done fairly efficiently because the sequence numbers constrain
 
67
# the possible relationships.
87
68
 
88
69
 
89
70
import sha
90
 
 
91
 
 
92
 
 
93
 
class WeaveError(Exception):
94
 
    """Exception in processing weave"""
95
 
 
96
 
 
97
 
class WeaveFormatError(WeaveError):
98
 
    """Weave invariant violated"""
99
 
    
 
71
from difflib import SequenceMatcher
 
72
 
 
73
from bzrlib.trace import mutter
 
74
from bzrlib.errors import WeaveError, WeaveFormatError, WeaveParentMismatch, \
 
75
        WeaveRevisionNotPresent, WeaveRevisionAlreadyPresent
 
76
from bzrlib.tsort import topo_sort
 
77
 
100
78
 
101
79
class Weave(object):
102
80
    """weave - versioned text file storage.
113
91
 
114
92
    * a nonnegative index number.
115
93
 
116
 
    * a version-id string. (not implemented yet)
 
94
    * a version-id string.
117
95
 
118
96
    Typically the index number will be valid only inside this weave and
119
97
    the version-id is used to reference it in the larger world.
181
159
 
182
160
    _name_map
183
161
        For each name, the version number.
 
162
 
 
163
    _weave_name
 
164
        Descriptive name of this weave; typically the filename if known.
 
165
        Set by read_weave.
184
166
    """
185
167
 
186
 
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map']
 
168
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
 
169
                 '_weave_name']
187
170
    
188
 
    def __init__(self):
 
171
    def __init__(self, weave_name=None):
189
172
        self._weave = []
190
173
        self._parents = []
191
174
        self._sha1s = []
192
175
        self._names = []
193
176
        self._name_map = {}
194
 
 
 
177
        self._weave_name = weave_name
 
178
 
 
179
 
 
180
    def copy(self):
 
181
        """Return a deep copy of self.
 
182
        
 
183
        The copy can be modified without affecting the original weave."""
 
184
        other = Weave()
 
185
        other._weave = self._weave[:]
 
186
        other._parents = self._parents[:]
 
187
        other._sha1s = self._sha1s[:]
 
188
        other._names = self._names[:]
 
189
        other._name_map = self._name_map.copy()
 
190
        other._weave_name = self._weave_name
 
191
        return other
195
192
 
196
193
    def __eq__(self, other):
197
194
        if not isinstance(other, Weave):
204
201
    def __ne__(self, other):
205
202
        return not self.__eq__(other)
206
203
 
207
 
 
 
204
    def __contains__(self, name):
 
205
        return self._name_map.has_key(name)
 
206
 
 
207
    def maybe_lookup(self, name_or_index):
 
208
        """Convert possible symbolic name to index, or pass through indexes."""
 
209
        if isinstance(name_or_index, (int, long)):
 
210
            return name_or_index
 
211
        else:
 
212
            return self.lookup(name_or_index)
 
213
 
 
214
        
208
215
    def lookup(self, name):
 
216
        """Convert symbolic version name to index."""
209
217
        try:
210
218
            return self._name_map[name]
211
219
        except KeyError:
212
 
            raise WeaveError("name %s not present in weave" % name)
213
 
 
 
220
            raise WeaveRevisionNotPresent(name, self)
 
221
 
 
222
    def names(self):
 
223
        return self._names[:]
 
224
 
 
225
    def iter_names(self):
 
226
        """Yield a list of all names in this weave."""
 
227
        return iter(self._names)
 
228
 
 
229
    def idx_to_name(self, version):
 
230
        return self._names[version]
 
231
 
 
232
    def _check_repeated_add(self, name, parents, text, sha1):
 
233
        """Check that a duplicated add is OK.
 
234
 
 
235
        If it is, return the (old) index; otherwise raise an exception.
 
236
        """
 
237
        idx = self.lookup(name)
 
238
        if sorted(self._parents[idx]) != sorted(parents) \
 
239
            or sha1 != self._sha1s[idx]:
 
240
            raise WeaveRevisionAlreadyPresent(name, self)
 
241
        return idx
214
242
        
215
 
    def add(self, name, parents, text):
 
243
    def add(self, name, parents, text, sha1=None):
216
244
        """Add a single text on top of the weave.
217
245
  
218
246
        Returns the index number of the newly added version.
225
253
            List or set of direct parent version numbers.
226
254
            
227
255
        text
228
 
            Sequence of lines to be added in the new version."""
 
256
            Sequence of lines to be added in the new version.
 
257
 
 
258
        sha -- SHA-1 of the file, if known.  This is trusted to be
 
259
            correct if supplied.
 
260
        """
 
261
        from bzrlib.osutils import sha_strings
229
262
 
230
263
        assert isinstance(name, basestring)
 
264
        if sha1 is None:
 
265
            sha1 = sha_strings(text)
231
266
        if name in self._name_map:
232
 
            raise WeaveError("name %r already present in weave" % name)
233
 
        
 
267
            return self._check_repeated_add(name, parents, text, sha1)
 
268
 
 
269
        parents = map(self.maybe_lookup, parents)
234
270
        self._check_versions(parents)
235
271
        ## self._check_lines(text)
236
272
        new_version = len(self._parents)
237
273
 
238
 
        s = sha.new()
239
 
        map(s.update, text)
240
 
        sha1 = s.hexdigest()
241
 
        del s
242
274
 
243
275
        # if we abort after here the (in-memory) weave will be corrupt because only
244
276
        # some fields are updated
293
325
        #print 'basis_lines:', basis_lines
294
326
        #print 'new_lines:  ', lines
295
327
 
296
 
        from difflib import SequenceMatcher
297
328
        s = SequenceMatcher(None, basis_lines, text)
298
329
 
299
330
        # offset gives the number of lines that have been inserted
334
365
 
335
366
        return new_version
336
367
 
 
368
    def add_identical(self, old_rev_id, new_rev_id, parents):
 
369
        """Add an identical text to old_rev_id as new_rev_id."""
 
370
        old_lines = self.get(self.lookup(old_rev_id))
 
371
        self.add(new_rev_id, parents, old_lines)
337
372
 
338
373
    def inclusions(self, versions):
339
374
        """Return set of all ancestors of given version(s)."""
340
375
        i = set(versions)
341
 
        v = max(versions)
342
 
        try:
343
 
            while v >= 0:
344
 
                if v in i:
345
 
                    # include all its parents
346
 
                    i.update(self._parents[v])
347
 
                v -= 1
348
 
            return i
349
 
        except IndexError:
350
 
            raise ValueError("version %d not present in weave" % v)
 
376
        for v in xrange(max(versions), 0, -1):
 
377
            if v in i:
 
378
                # include all its parents
 
379
                i.update(self._parents[v])
 
380
        return i
 
381
        ## except IndexError:
 
382
        ##     raise ValueError("version %d not present in weave" % v)
 
383
 
 
384
 
 
385
    def parents(self, version):
 
386
        return self._parents[version]
 
387
 
 
388
 
 
389
    def parent_names(self, version):
 
390
        """Return version names for parents of a version."""
 
391
        return map(self.idx_to_name, self._parents[self.lookup(version)])
351
392
 
352
393
 
353
394
    def minimal_parents(self, version):
393
434
                raise IndexError("invalid version number %r" % i)
394
435
 
395
436
    
396
 
    def annotate(self, index):
397
 
        return list(self.annotate_iter(index))
398
 
 
399
 
 
400
 
    def annotate_iter(self, version):
 
437
    def annotate(self, name_or_index):
 
438
        return list(self.annotate_iter(name_or_index))
 
439
 
 
440
 
 
441
    def annotate_iter(self, name_or_index):
401
442
        """Yield list of (index-id, line) pairs for the specified version.
402
443
 
403
444
        The index indicates when the line originated in the weave."""
404
 
        for origin, lineno, text in self._extract([version]):
 
445
        incls = [self.maybe_lookup(name_or_index)]
 
446
        for origin, lineno, text in self._extract(incls):
405
447
            yield origin, text
406
448
 
407
 
 
408
449
    def _walk(self):
409
450
        """Walk the weave.
410
451
 
432
473
                elif c == ']':
433
474
                    dset.remove(v)
434
475
                else:
435
 
                    raise WeaveFormatError('unexpected instruction %r'
436
 
                                           % v)
 
476
                    raise WeaveFormatError('unexpected instruction %r' % v)
437
477
            else:
438
478
                assert isinstance(l, basestring)
439
479
                assert istack
451
491
 
452
492
        The set typically but not necessarily corresponds to a version.
453
493
        """
 
494
        for i in versions:
 
495
            if not isinstance(i, int):
 
496
                raise ValueError(i)
 
497
            
454
498
        included = self.inclusions(versions)
455
499
 
456
500
        istack = []
489
533
                if isactive:
490
534
                    result.append((istack[-1], lineno, l))
491
535
            lineno += 1
492
 
 
493
536
        if istack:
494
 
            raise WFE("unclosed insertion blocks at end of weave",
495
 
                                   istack)
 
537
            raise WeaveFormatError("unclosed insertion blocks "
 
538
                    "at end of weave: %s" % istack)
496
539
        if dset:
497
 
            raise WFE("unclosed deletion blocks at end of weave",
498
 
                                   dset)
499
 
 
 
540
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
 
541
                                   % dset)
500
542
        return result
501
 
    
502
 
 
503
 
 
504
 
    def get_iter(self, version):
 
543
 
 
544
 
 
545
    def get_iter(self, name_or_index):
505
546
        """Yield lines for the specified version."""
506
 
        for origin, lineno, line in self._extract([version]):
 
547
        incls = [self.maybe_lookup(name_or_index)]
 
548
        for origin, lineno, line in self._extract(incls):
507
549
            yield line
508
550
 
509
551
 
510
 
    def get(self, index):
511
 
        return list(self.get_iter(index))
 
552
    def get_text(self, name_or_index):
 
553
        return ''.join(self.get_iter(name_or_index))
 
554
        assert isinstance(version, int)
 
555
 
 
556
 
 
557
    def get_lines(self, name_or_index):
 
558
        return list(self.get_iter(name_or_index))
 
559
 
 
560
 
 
561
    get = get_lines
512
562
 
513
563
 
514
564
    def mash_iter(self, included):
515
565
        """Return composed version of multiple included versions."""
 
566
        included = map(self.maybe_lookup, included)
516
567
        for origin, lineno, text in self._extract(included):
517
568
            yield text
518
569
 
578
629
        If there is a chunk of the file where there's no diagreement,
579
630
        only one alternative is given.
580
631
        """
581
 
 
582
632
        # approach: find the included versions common to all the
583
633
        # merged versions
584
634
        raise NotImplementedError()
604
654
        If line1=line2, this is a pure insert; if newlines=[] this is a
605
655
        pure delete.  (Similar to difflib.)
606
656
        """
607
 
 
 
657
        raise NotImplementedError()
608
658
 
609
659
            
610
660
    def plan_merge(self, ver_a, ver_b):
673
723
                elif lines_a == lines_b:
674
724
                    for l in lines_a: yield l
675
725
                else:
676
 
                    yield '<<<<\n'
 
726
                    yield '<<<<<<<\n'
677
727
                    for l in lines_a: yield l
678
 
                    yield '====\n'
 
728
                    yield '=======\n'
679
729
                    for l in lines_b: yield l
680
 
                    yield '>>>>\n'
 
730
                    yield '>>>>>>>\n'
681
731
 
682
732
                del lines_a[:]
683
733
                del lines_b[:]
704
754
                       state
705
755
 
706
756
                
707
 
 
708
 
 
709
 
 
 
757
    def join(self, other):
 
758
        """Integrate versions from other into this weave.
 
759
 
 
760
        The resulting weave contains all the history of both weaves; 
 
761
        any version you could retrieve from either self or other can be 
 
762
        retrieved from self after this call.
 
763
 
 
764
        It is illegal for the two weaves to contain different values 
 
765
        or different parents for any version.  See also reweave().
 
766
        """
 
767
        if other.numversions() == 0:
 
768
            return          # nothing to update, easy
 
769
        # two loops so that we do not change ourselves before verifying it
 
770
        # will be ok
 
771
        # work through in index order to make sure we get all dependencies
 
772
        for other_idx, name in enumerate(other._names):
 
773
            if self._check_version_consistent(other, other_idx, name):
 
774
                continue
 
775
        for other_idx, name in enumerate(other._names):
 
776
            # TODO: If all the parents of the other version are already 
 
777
            # present then we can avoid some work by just taking the delta
 
778
            # and adjusting the offsets.
 
779
            new_parents = self._imported_parents(other, other_idx)
 
780
            lines = other.get_lines(other_idx)
 
781
            sha1 = other._sha1s[other_idx]
 
782
            self.add(name, new_parents, lines, sha1)
 
783
 
 
784
 
 
785
    def _imported_parents(self, other, other_idx):
 
786
        """Return list of parents in self corresponding to indexes in other."""
 
787
        new_parents = []
 
788
        for parent_idx in other._parents[other_idx]:
 
789
            parent_name = other._names[parent_idx]
 
790
            if parent_name not in self._names:
 
791
                # should not be possible
 
792
                raise WeaveError("missing parent {%s} of {%s} in %r" 
 
793
                                 % (parent_name, other._name_map[other_idx], self))
 
794
            new_parents.append(self._name_map[parent_name])
 
795
        return new_parents
 
796
 
 
797
    def _check_version_consistent(self, other, other_idx, name):
 
798
        """Check if a version in consistent in this and other.
 
799
 
 
800
        To be consistent it must have:
 
801
 
 
802
         * the same text
 
803
         * the same direct parents (by name, not index, and disregarding
 
804
           order)
 
805
        
 
806
        If present & correct return True;
 
807
        if not present in self return False; 
 
808
        if inconsistent raise error."""
 
809
        this_idx = self._name_map.get(name, -1)
 
810
        if this_idx != -1:
 
811
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
 
812
                raise WeaveError("inconsistent texts for version {%s} "
 
813
                                 "when joining weaves"
 
814
                                 % (name))
 
815
            self_parents = self._parents[this_idx]
 
816
            other_parents = other._parents[other_idx]
 
817
            n1 = [self._names[i] for i in self_parents]
 
818
            n2 = [other._names[i] for i in other_parents]
 
819
            n1.sort()
 
820
            n2.sort()
 
821
            if n1 != n2:
 
822
                raise WeaveParentMismatch("inconsistent parents "
 
823
                    "for version {%s}: %s vs %s" % (name, n1, n2))
 
824
            else:
 
825
                return True         # ok!
 
826
        else:
 
827
            return False
 
828
 
 
829
    def reweave(self, other):
 
830
        """Reweave self with other."""
 
831
        new_weave = reweave(self, other)
 
832
        for attr in self.__slots__:
 
833
            setattr(self, attr, getattr(new_weave, attr))
 
834
 
 
835
 
 
836
def reweave(wa, wb):
 
837
    """Combine two weaves and return the result.
 
838
 
 
839
    This works even if a revision R has different parents in 
 
840
    wa and wb.  In the resulting weave all the parents are given.
 
841
 
 
842
    This is done by just building up a new weave, maintaining ordering 
 
843
    of the versions in the two inputs.  More efficient approaches
 
844
    might be possible but it should only be necessary to do 
 
845
    this operation rarely, when a new previously ghost version is 
 
846
    inserted.
 
847
    """
 
848
    wr = Weave()
 
849
    ia = ib = 0
 
850
    queue_a = range(wa.numversions())
 
851
    queue_b = range(wb.numversions())
 
852
    # first determine combined parents of all versions
 
853
    # map from version name -> all parent names
 
854
    combined_parents = _reweave_parent_graphs(wa, wb)
 
855
    mutter("combined parents: %r", combined_parents)
 
856
    order = topo_sort(combined_parents.iteritems())
 
857
    mutter("order to reweave: %r", order)
 
858
    for name in order:
 
859
        if name in wa._name_map:
 
860
            lines = wa.get_lines(name)
 
861
            if name in wb._name_map:
 
862
                assert lines == wb.get_lines(name)
 
863
        else:
 
864
            lines = wb.get_lines(name)
 
865
        wr.add(name, combined_parents[name], lines)
 
866
    return wr
 
867
 
 
868
 
 
869
def _reweave_parent_graphs(wa, wb):
 
870
    """Return combined parent ancestry for two weaves.
 
871
    
 
872
    Returned as a list of (version_name, set(parent_names))"""
 
873
    combined = {}
 
874
    for weave in [wa, wb]:
 
875
        for idx, name in enumerate(weave._names):
 
876
            p = combined.setdefault(name, set())
 
877
            p.update(map(weave.idx_to_name, weave._parents[idx]))
 
878
    return combined
710
879
 
711
880
 
712
881
def weave_toc(w):
723
892
 
724
893
 
725
894
 
726
 
def weave_stats(weave_file):
727
 
    from bzrlib.progress import ProgressBar
 
895
def weave_stats(weave_file, pb):
728
896
    from bzrlib.weavefile import read_weave
729
897
 
730
 
    pb = ProgressBar()
731
 
 
732
898
    wf = file(weave_file, 'rb')
733
899
    w = read_weave(wf)
734
900
    # FIXME: doesn't work on pipes
738
904
    vers = len(w)
739
905
    for i in range(vers):
740
906
        pb.update('checking sizes', i, vers)
741
 
        for line in w.get_iter(i):
 
907
        for origin, lineno, line in w._extract([i]):
742
908
            total += len(line)
743
909
 
744
910
    pb.clear()
775
941
        Display composite of all selected versions.
776
942
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
777
943
        Auto-merge two versions and display conflicts.
 
944
    weave diff WEAVEFILE VERSION1 VERSION2 
 
945
        Show differences between two versions.
778
946
 
779
947
example:
780
948
 
805
973
def main(argv):
806
974
    import sys
807
975
    import os
808
 
    from weavefile import write_weave, read_weave
 
976
    try:
 
977
        import bzrlib
 
978
    except ImportError:
 
979
        # in case we're run directly from the subdirectory
 
980
        sys.path.append('..')
 
981
        import bzrlib
 
982
    from bzrlib.weavefile import write_weave, read_weave
809
983
    from bzrlib.progress import ProgressBar
810
984
 
811
985
    try:
848
1022
        w = readit()
849
1023
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
850
1024
 
 
1025
    elif cmd == 'diff':
 
1026
        from difflib import unified_diff
 
1027
        w = readit()
 
1028
        fn = argv[2]
 
1029
        v1, v2 = map(int, argv[3:5])
 
1030
        lines1 = w.get(v1)
 
1031
        lines2 = w.get(v2)
 
1032
        diff_gen = unified_diff(lines1, lines2,
 
1033
                                '%s version %d' % (fn, v1),
 
1034
                                '%s version %d' % (fn, v2))
 
1035
        sys.stdout.writelines(diff_gen)
 
1036
            
851
1037
    elif cmd == 'annotate':
852
1038
        w = readit()
853
1039
        # newline is added to all lines regardless; too hard to get
865
1051
        weave_toc(readit())
866
1052
 
867
1053
    elif cmd == 'stats':
868
 
        weave_stats(argv[2])
 
1054
        weave_stats(argv[2], ProgressBar())
869
1055
        
870
1056
    elif cmd == 'check':
871
1057
        w = readit()