/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/weave.py

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
# Author: Martin Pool <mbp@canonical.com>
18
18
 
 
19
 
19
20
"""Weave - storage of related text file versions"""
20
21
 
21
 
from __future__ import absolute_import
22
22
 
23
23
# XXX: If we do weaves this way, will a merge still behave the same
24
24
# way if it's done in a different order?  That's a pretty desirable
67
67
# FIXME: the conflict markers should be *7* characters
68
68
 
69
69
from copy import copy
 
70
from cStringIO import StringIO
70
71
import os
71
72
 
72
 
from ..lazy_import import lazy_import
 
73
from bzrlib.lazy_import import lazy_import
73
74
lazy_import(globals(), """
74
 
from breezy import tsort
 
75
from bzrlib import tsort
75
76
""")
76
 
from .. import (
 
77
from bzrlib import (
77
78
    errors,
78
79
    osutils,
79
80
    )
80
 
from ..errors import (
81
 
    RevisionAlreadyPresent,
82
 
    RevisionNotPresent,
83
 
    UnavailableRepresentation,
84
 
    )
85
 
from ..osutils import dirname, sha, sha_strings, split_lines
86
 
from .. import patiencediff
87
 
from ..revision import NULL_REVISION
88
 
from ..sixish import (
89
 
    BytesIO,
90
 
    )
91
 
from ..trace import mutter
92
 
from .versionedfile import (
 
81
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
 
82
        RevisionAlreadyPresent,
 
83
        RevisionNotPresent,
 
84
        UnavailableRepresentation,
 
85
        )
 
86
from bzrlib.osutils import dirname, sha, sha_strings, split_lines
 
87
import bzrlib.patiencediff
 
88
from bzrlib.revision import NULL_REVISION
 
89
from bzrlib.symbol_versioning import *
 
90
from bzrlib.trace import mutter
 
91
from bzrlib.versionedfile import (
93
92
    AbsentContentFactory,
94
93
    adapter_registry,
95
94
    ContentFactory,
96
95
    sort_groupcompress,
97
96
    VersionedFile,
98
97
    )
99
 
from .weavefile import _read_weave_v5, write_weave_v5
100
 
 
101
 
 
102
 
class WeaveError(errors.BzrError):
103
 
 
104
 
    _fmt = "Error in processing weave: %(msg)s"
105
 
 
106
 
    def __init__(self, msg=None):
107
 
        errors.BzrError.__init__(self)
108
 
        self.msg = msg
109
 
 
110
 
 
111
 
class WeaveRevisionAlreadyPresent(WeaveError):
112
 
 
113
 
    _fmt = "Revision {%(revision_id)s} already present in %(weave)s"
114
 
 
115
 
    def __init__(self, revision_id, weave):
116
 
 
117
 
        WeaveError.__init__(self)
118
 
        self.revision_id = revision_id
119
 
        self.weave = weave
120
 
 
121
 
 
122
 
class WeaveRevisionNotPresent(WeaveError):
123
 
 
124
 
    _fmt = "Revision {%(revision_id)s} not present in %(weave)s"
125
 
 
126
 
    def __init__(self, revision_id, weave):
127
 
        WeaveError.__init__(self)
128
 
        self.revision_id = revision_id
129
 
        self.weave = weave
130
 
 
131
 
 
132
 
class WeaveFormatError(WeaveError):
133
 
 
134
 
    _fmt = "Weave invariant violated: %(what)s"
135
 
 
136
 
    def __init__(self, what):
137
 
        WeaveError.__init__(self)
138
 
        self.what = what
139
 
 
140
 
 
141
 
class WeaveParentMismatch(WeaveError):
142
 
 
143
 
    _fmt = "Parents are mismatched between two revisions. %(msg)s"
144
 
 
145
 
 
146
 
class WeaveInvalidChecksum(WeaveError):
147
 
 
148
 
    _fmt = "Text did not match its checksum: %(msg)s"
149
 
 
150
 
 
151
 
class WeaveTextDiffers(WeaveError):
152
 
 
153
 
    _fmt = ("Weaves differ on text content. Revision:"
154
 
            " {%(revision_id)s}, %(weave_a)s, %(weave_b)s")
155
 
 
156
 
    def __init__(self, revision_id, weave_a, weave_b):
157
 
        WeaveError.__init__(self)
158
 
        self.revision_id = revision_id
159
 
        self.weave_a = weave_a
160
 
        self.weave_b = weave_b
161
 
 
162
 
 
163
 
class WeaveTextDiffers(WeaveError):
164
 
 
165
 
    _fmt = ("Weaves differ on text content. Revision:"
166
 
            " {%(revision_id)s}, %(weave_a)s, %(weave_b)s")
167
 
 
168
 
    def __init__(self, revision_id, weave_a, weave_b):
169
 
        WeaveError.__init__(self)
170
 
        self.revision_id = revision_id
171
 
        self.weave_a = weave_a
172
 
        self.weave_b = weave_b
 
98
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
173
99
 
174
100
 
175
101
class WeaveContentFactory(ContentFactory):
305
231
        self._name_map = {}
306
232
        self._weave_name = weave_name
307
233
        if matcher is None:
308
 
            self._matcher = patiencediff.PatienceSequenceMatcher
 
234
            self._matcher = bzrlib.patiencediff.PatienceSequenceMatcher
309
235
        else:
310
236
            self._matcher = matcher
311
237
        if get_scope is None:
465
391
    def _add_lines(self, version_id, parents, lines, parent_texts,
466
392
       left_matching_blocks, nostore_sha, random_id, check_content):
467
393
        """See VersionedFile.add_lines."""
468
 
        idx = self._add(version_id, lines, list(map(self._lookup, parents)),
 
394
        idx = self._add(version_id, lines, map(self._lookup, parents),
469
395
            nostore_sha=nostore_sha)
470
396
        return sha_strings(lines), sum(map(len, lines)), idx
471
397
 
494
420
        if sha1 == nostore_sha:
495
421
            raise errors.ExistingContent
496
422
        if version_id is None:
497
 
            version_id = b"sha1:" + sha1
 
423
            version_id = "sha1:" + sha1
498
424
        if version_id in self._name_map:
499
425
            return self._check_repeated_add(version_id, parents, lines, sha1)
500
426
 
501
427
        self._check_versions(parents)
 
428
        ## self._check_lines(lines)
502
429
        new_version = len(self._parents)
503
430
 
504
431
        # if we abort after here the (in-memory) weave will be corrupt because only
510
437
        self._names.append(version_id)
511
438
        self._name_map[version_id] = new_version
512
439
 
 
440
 
513
441
        if not parents:
514
442
            # special case; adding with no parents revision; can do
515
443
            # this more quickly by just appending unconditionally.
516
444
            # even more specially, if we're adding an empty text we
517
445
            # need do nothing at all.
518
446
            if lines:
519
 
                self._weave.append((b'{', new_version))
 
447
                self._weave.append(('{', new_version))
520
448
                self._weave.extend(lines)
521
 
                self._weave.append((b'}', None))
 
449
                self._weave.append(('}', None))
522
450
            return new_version
523
451
 
524
452
        if len(parents) == 1:
572
500
            # the deletion and insertion are handled separately.
573
501
            # first delete the region.
574
502
            if i1 != i2:
575
 
                self._weave.insert(i1+offset, (b'[', new_version))
576
 
                self._weave.insert(i2+offset+1, (b']', new_version))
 
503
                self._weave.insert(i1+offset, ('[', new_version))
 
504
                self._weave.insert(i2+offset+1, (']', new_version))
577
505
                offset += 2
578
506
 
579
507
            if j1 != j2:
581
509
                # i2; we want to insert after this region to make sure
582
510
                # we don't destroy ourselves
583
511
                i = i2 + offset
584
 
                self._weave[i:i] = ([(b'{', new_version)]
 
512
                self._weave[i:i] = ([('{', new_version)]
585
513
                                    + lines[j1:j2]
586
 
                                    + [(b'}', None)])
 
514
                                    + [('}', None)])
587
515
                offset += 2 + (j2 - j1)
588
516
        return new_version
589
517
 
592
520
        if not len(versions):
593
521
            return []
594
522
        i = set(versions)
595
 
        for v in range(max(versions), 0, -1):
 
523
        for v in xrange(max(versions), 0, -1):
596
524
            if v in i:
597
525
                # include all its parents
598
526
                i.update(self._parents[v])
599
527
        return i
 
528
        ## except IndexError:
 
529
        ##     raise ValueError("version %d not present in weave" % v)
600
530
 
601
531
    def get_ancestry(self, version_ids, topo_sorted=True):
602
532
        """See VersionedFile.get_ancestry."""
603
 
        if isinstance(version_ids, bytes):
 
533
        if isinstance(version_ids, basestring):
604
534
            version_ids = [version_ids]
605
535
        i = self._inclusions([self._lookup(v) for v in version_ids])
606
536
        return [self._idx_to_name(v) for v in i]
607
537
 
 
538
    def _check_lines(self, text):
 
539
        if not isinstance(text, list):
 
540
            raise ValueError("text should be a list, not %s" % type(text))
 
541
 
 
542
        for l in text:
 
543
            if not isinstance(l, basestring):
 
544
                raise ValueError("text line should be a string or unicode, not %s"
 
545
                                 % type(l))
 
546
 
 
547
 
 
548
 
608
549
    def _check_versions(self, indexes):
609
550
        """Check everything in the sequence of indexes is valid"""
610
551
        for i in indexes:
637
578
        version_ids = set(version_ids)
638
579
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
639
580
            if inserted not in version_ids: continue
640
 
            if not line.endswith(b'\n'):
641
 
                yield line + b'\n', inserted
 
581
            if line[-1] != '\n':
 
582
                yield line + '\n', inserted
642
583
            else:
643
584
                yield line, inserted
644
585
 
654
595
            if l.__class__ == tuple:
655
596
                c, v = l
656
597
                isactive = None
657
 
                if c == b'{':
 
598
                if c == '{':
658
599
                    istack.append(self._names[v])
659
 
                elif c == b'}':
 
600
                elif c == '}':
660
601
                    istack.pop()
661
 
                elif c == b'[':
 
602
                elif c == '[':
662
603
                    dset.add(self._names[v])
663
 
                elif c == b']':
 
604
                elif c == ']':
664
605
                    dset.remove(self._names[v])
665
606
                else:
666
607
                    raise WeaveFormatError('unexpected instruction %r' % v)
747
688
        WFE = WeaveFormatError
748
689
 
749
690
        # wow.
750
 
        #  449       0   4474.6820   2356.5590   breezy.weave:556(_extract)
 
691
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
751
692
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
752
693
        # 1.6 seconds in 'isinstance'.
753
694
        # changing the first isinstance:
754
 
        #  449       0   2814.2660   1577.1760   breezy.weave:556(_extract)
 
695
        #  449       0   2814.2660   1577.1760   bzrlib.weave:556(_extract)
755
696
        #  +140414   0    762.8050    762.8050   +<isinstance>
756
697
        # note that the inline time actually dropped (less function calls)
757
698
        # and total processing time was halved.
758
699
        # we're still spending ~1/4 of the method in isinstance though.
759
700
        # so lets hard code the acceptable string classes we expect:
760
 
        #  449       0   1202.9420    786.2930   breezy.weave:556(_extract)
 
701
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
761
702
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list'
762
703
        #                                          objects>
763
704
        # yay, down to ~1/4 the initial extract time, and our inline time
764
705
        # has shrunk again, with isinstance no longer dominating.
765
706
        # tweaking the stack inclusion test to use a set gives:
766
 
        #  449       0   1122.8030    713.0080   breezy.weave:556(_extract)
 
707
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
767
708
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list'
768
709
        #                                          objects>
769
710
        # - a 5% win, or possibly just noise. However with large istacks that
770
711
        # 'in' test could dominate, so I'm leaving this change in place -
771
712
        # when its fast enough to consider profiling big datasets we can review.
772
713
 
 
714
 
 
715
 
 
716
 
773
717
        for l in self._weave:
774
718
            if l.__class__ == tuple:
775
719
                c, v = l
776
720
                isactive = None
777
 
                if c == b'{':
 
721
                if c == '{':
778
722
                    istack.append(v)
779
723
                    iset.add(v)
780
 
                elif c == b'}':
 
724
                elif c == '}':
781
725
                    iset.remove(istack.pop())
782
 
                elif c == b'[':
 
726
                elif c == '[':
783
727
                    if v in included:
784
728
                        dset.add(v)
785
 
                elif c == b']':
 
729
                elif c == ']':
786
730
                    if v in included:
787
731
                        dset.remove(v)
788
732
                else:
806
750
 
807
751
        NOT FOR PUBLIC USE.
808
752
        """
809
 
        # GZ 2017-04-01: This used to check for long as well, but I don't think
810
 
        # there are python implementations with sys.maxsize > sys.maxint
811
 
        if isinstance(name_or_index, int):
 
753
        if isinstance(name_or_index, (int, long)):
812
754
            return name_or_index
813
755
        else:
814
756
            return self._lookup(name_or_index)
820
762
        expected_sha1 = self._sha1s[int_index]
821
763
        measured_sha1 = sha_strings(result)
822
764
        if measured_sha1 != expected_sha1:
823
 
            raise WeaveInvalidChecksum(
 
765
            raise errors.WeaveInvalidChecksum(
824
766
                    'file %s, revision %s, expected: %s, measured %s'
825
767
                    % (self._weave_name, version_id,
826
768
                       expected_sha1, measured_sha1))
863
805
            name = self._idx_to_name(i)
864
806
            sha1s[name] = sha()
865
807
            texts[name] = []
866
 
            new_inc = {name}
 
808
            new_inc = set([name])
867
809
            for p in self._parents[i]:
868
810
                new_inc.update(inclusions[self._idx_to_name(p)])
869
811
 
894
836
 
895
837
        for i in range(nv):
896
838
            version = self._idx_to_name(i)
897
 
            hd = sha1s[version].hexdigest().encode()
 
839
            hd = sha1s[version].hexdigest()
898
840
            expected = self._sha1s[i]
899
841
            if hd != expected:
900
 
                raise WeaveInvalidChecksum(
 
842
                raise errors.WeaveInvalidChecksum(
901
843
                        "mismatched sha1 for version %s: "
902
844
                        "got %s, expected %s"
903
845
                        % (version, hd, expected))
933
875
        this_idx = self._name_map.get(name, -1)
934
876
        if this_idx != -1:
935
877
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
936
 
                raise WeaveTextDiffers(name, self, other)
 
878
                raise errors.WeaveTextDiffers(name, self, other)
937
879
            self_parents = self._parents[this_idx]
938
880
            other_parents = other._parents[other_idx]
939
 
            n1 = {self._names[i] for i in self_parents}
940
 
            n2 = {other._names[i] for i in other_parents}
 
881
            n1 = set([self._names[i] for i in self_parents])
 
882
            n2 = set([other._names[i] for i in other_parents])
941
883
            if not self._compatible_parents(n1, n2):
942
884
                raise WeaveParentMismatch("inconsistent parents "
943
885
                    "for version {%s}: %s vs %s" % (name, n1, n2))
978
920
        self._transport = transport
979
921
        self._filemode = filemode
980
922
        try:
981
 
            f = self._transport.get(name + WeaveFile.WEAVE_SUFFIX)
982
 
            _read_weave_v5(BytesIO(f.read()), self)
 
923
            _read_weave_v5(self._transport.get(name + WeaveFile.WEAVE_SUFFIX), self)
983
924
        except errors.NoSuchFile:
984
925
            if not create:
985
926
                raise
999
940
    def copy_to(self, name, transport):
1000
941
        """See VersionedFile.copy_to()."""
1001
942
        # as we are all in memory always, just serialise to the new place.
1002
 
        sio = BytesIO()
 
943
        sio = StringIO()
1003
944
        write_weave_v5(self, sio)
1004
945
        sio.seek(0)
1005
946
        transport.put_file(name + WeaveFile.WEAVE_SUFFIX, sio, self._filemode)
1007
948
    def _save(self):
1008
949
        """Save the weave."""
1009
950
        self._check_write_ok()
1010
 
        sio = BytesIO()
 
951
        sio = StringIO()
1011
952
        write_weave_v5(self, sio)
1012
953
        sio.seek(0)
1013
954
        bytes = sio.getvalue()
1044
985
    :param msg: An optional message for the progress
1045
986
    """
1046
987
    wr = Weave()
 
988
    ia = ib = 0
 
989
    queue_a = range(wa.num_versions())
 
990
    queue_b = range(wb.num_versions())
1047
991
    # first determine combined parents of all versions
1048
992
    # map from version name -> all parent names
1049
993
    combined_parents = _reweave_parent_graphs(wa, wb)
1050
994
    mutter("combined parents: %r", combined_parents)
1051
 
    order = tsort.topo_sort(combined_parents.items())
 
995
    order = tsort.topo_sort(combined_parents.iteritems())
1052
996
    mutter("order to reweave: %r", order)
1053
997
 
1054
998
    if pb and not msg:
1068
1012
                    lines = list(difflib.unified_diff(lines, lines_b,
1069
1013
                            wa._weave_name, wb._weave_name))
1070
1014
                    mutter('lines:\n%s', ''.join(lines))
1071
 
                    raise WeaveTextDiffers(name, wa, wb)
 
1015
                    raise errors.WeaveTextDiffers(name, wa, wb)
1072
1016
        else:
1073
1017
            lines = wb.get_lines(name)
1074
1018
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])