~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: Robert Collins
  • Date: 2009-02-20 10:48:51 UTC
  • mfrom: (4027 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4028.
  • Revision ID: robertc@robertcollins.net-20090220104851-m0s7qwe6jzqkgj1f
Merge bzr.dev (avoids criss-cross for PQM.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2009 Canonical Ltd
 
1
#! /usr/bin/python
 
2
 
 
3
# Copyright (C) 2005 Canonical Ltd
2
4
#
3
5
# This program is free software; you can redistribute it and/or modify
4
6
# it under the terms of the GNU General Public License as published by
12
14
#
13
15
# You should have received a copy of the GNU General Public License
14
16
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
18
 
17
19
# Author: Martin Pool <mbp@canonical.com>
18
20
 
59
61
# where the basis and destination are unchanged.
60
62
 
61
63
# FIXME: Sometimes we will be given a parents list for a revision
62
 
# that includes some redundant parents (i.e. already a parent of
63
 
# something in the list.)  We should eliminate them.  This can
 
64
# that includes some redundant parents (i.e. already a parent of 
 
65
# something in the list.)  We should eliminate them.  This can 
64
66
# be done fairly efficiently because the sequence numbers constrain
65
67
# the possible relationships.
66
68
 
69
71
from copy import copy
70
72
from cStringIO import StringIO
71
73
import os
 
74
import time
 
75
import warnings
72
76
 
73
77
from bzrlib.lazy_import import lazy_import
74
78
lazy_import(globals(), """
77
81
from bzrlib import (
78
82
    errors,
79
83
    osutils,
 
84
    progress,
80
85
    )
81
86
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
82
87
        RevisionAlreadyPresent,
83
88
        RevisionNotPresent,
84
89
        UnavailableRepresentation,
 
90
        WeaveRevisionAlreadyPresent,
 
91
        WeaveRevisionNotPresent,
85
92
        )
86
93
from bzrlib.osutils import dirname, sha, sha_strings, split_lines
87
94
import bzrlib.patiencediff
92
99
    AbsentContentFactory,
93
100
    adapter_registry,
94
101
    ContentFactory,
95
 
    sort_groupcompress,
96
102
    VersionedFile,
97
103
    )
98
104
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
125
131
 
126
132
class Weave(VersionedFile):
127
133
    """weave - versioned text file storage.
128
 
 
 
134
    
129
135
    A Weave manages versions of line-based text files, keeping track
130
136
    of the originating version for each line.
131
137
 
177
183
 
178
184
    * It doesn't seem very useful to have an active insertion
179
185
      inside an inactive insertion, but it might happen.
180
 
 
 
186
      
181
187
    * Therefore, all instructions are always"considered"; that
182
188
      is passed onto and off the stack.  An outer inactive block
183
189
      doesn't disable an inner block.
253
259
 
254
260
    def copy(self):
255
261
        """Return a deep copy of self.
256
 
 
 
262
        
257
263
        The copy can be modified without affecting the original weave."""
258
264
        other = Weave()
259
265
        other._weave = self._weave[:]
269
275
            return False
270
276
        return self._parents == other._parents \
271
277
               and self._weave == other._weave \
272
 
               and self._sha1s == other._sha1s
273
 
 
 
278
               and self._sha1s == other._sha1s 
 
279
    
274
280
    def __ne__(self, other):
275
281
        return not self.__eq__(other)
276
282
 
315
321
            new_versions = tsort.topo_sort(parents)
316
322
            new_versions.extend(set(versions).difference(set(parents)))
317
323
            versions = new_versions
318
 
        elif ordering == 'groupcompress':
319
 
            parents = self.get_parent_map(versions)
320
 
            new_versions = sort_groupcompress(parents)
321
 
            new_versions.extend(set(versions).difference(set(parents)))
322
 
            versions = new_versions
323
324
        for version in versions:
324
325
            if version in self:
325
326
                yield WeaveContentFactory(version, self)
348
349
    def insert_record_stream(self, stream):
349
350
        """Insert a record stream into this versioned file.
350
351
 
351
 
        :param stream: A stream of records to insert.
 
352
        :param stream: A stream of records to insert. 
352
353
        :return: None
353
354
        :seealso VersionedFile.get_record_stream:
354
355
        """
397
398
 
398
399
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
399
400
        """Add a single text on top of the weave.
400
 
 
 
401
  
401
402
        Returns the index number of the newly added version.
402
403
 
403
404
        version_id
404
405
            Symbolic name for this version.
405
406
            (Typically the revision-id of the revision that added it.)
406
 
            If None, a name will be allocated based on the hash. (sha1:SHAHASH)
407
407
 
408
408
        parents
409
409
            List or set of direct parent version numbers.
410
 
 
 
410
            
411
411
        lines
412
412
            Sequence of lines to be added in the new version.
413
413
 
419
419
            sha1 = sha_strings(lines)
420
420
        if sha1 == nostore_sha:
421
421
            raise errors.ExistingContent
422
 
        if version_id is None:
423
 
            version_id = "sha1:" + sha1
424
422
        if version_id in self._name_map:
425
423
            return self._check_repeated_add(version_id, parents, lines, sha1)
426
424
 
437
435
        self._names.append(version_id)
438
436
        self._name_map[version_id] = new_version
439
437
 
440
 
 
 
438
            
441
439
        if not parents:
442
440
            # special case; adding with no parents revision; can do
443
441
            # this more quickly by just appending unconditionally.
454
452
            if sha1 == self._sha1s[pv]:
455
453
                # special case: same as the single parent
456
454
                return new_version
457
 
 
 
455
            
458
456
 
459
457
        ancestors = self._inclusions(parents)
460
458
 
509
507
                # i2; we want to insert after this region to make sure
510
508
                # we don't destroy ourselves
511
509
                i = i2 + offset
512
 
                self._weave[i:i] = ([('{', new_version)]
513
 
                                    + lines[j1:j2]
 
510
                self._weave[i:i] = ([('{', new_version)] 
 
511
                                    + lines[j1:j2] 
514
512
                                    + [('}', None)])
515
513
                offset += 2 + (j2 - j1)
516
514
        return new_version
543
541
            if not isinstance(l, basestring):
544
542
                raise ValueError("text line should be a string or unicode, not %s"
545
543
                                 % type(l))
546
 
 
 
544
        
547
545
 
548
546
 
549
547
    def _check_versions(self, indexes):
557
555
    def _compatible_parents(self, my_parents, other_parents):
558
556
        """During join check that other_parents are joinable with my_parents.
559
557
 
560
 
        Joinable is defined as 'is a subset of' - supersets may require
 
558
        Joinable is defined as 'is a subset of' - supersets may require 
561
559
        regeneration of diffs, but subsets do not.
562
560
        """
563
561
        return len(other_parents.difference(my_parents)) == 0
577
575
            version_ids = self.versions()
578
576
        version_ids = set(version_ids)
579
577
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
580
 
            if inserted not in version_ids: continue
 
578
            # if inserted not in version_ids then it was inserted before the
 
579
            # versions we care about, but because weaves cannot represent ghosts
 
580
            # properly, we do not filter down to that
 
581
            # if inserted not in version_ids: continue
581
582
            if line[-1] != '\n':
582
583
                yield line + '\n', inserted
583
584
            else:
585
586
 
586
587
    def _walk_internal(self, version_ids=None):
587
588
        """Helper method for weave actions."""
588
 
 
 
589
        
589
590
        istack = []
590
591
        dset = set()
591
592
 
672
673
        for i in versions:
673
674
            if not isinstance(i, int):
674
675
                raise ValueError(i)
675
 
 
 
676
            
676
677
        included = self._inclusions(versions)
677
678
 
678
679
        istack = []
687
688
 
688
689
        WFE = WeaveFormatError
689
690
 
690
 
        # wow.
 
691
        # wow. 
691
692
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
692
693
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
693
694
        # 1.6 seconds in 'isinstance'.
699
700
        # we're still spending ~1/4 of the method in isinstance though.
700
701
        # so lets hard code the acceptable string classes we expect:
701
702
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
702
 
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list'
 
703
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list' 
703
704
        #                                          objects>
704
705
        # yay, down to ~1/4 the initial extract time, and our inline time
705
706
        # has shrunk again, with isinstance no longer dominating.
706
707
        # tweaking the stack inclusion test to use a set gives:
707
708
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
708
 
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list'
 
709
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list' 
709
710
        #                                          objects>
710
711
        # - a 5% win, or possibly just noise. However with large istacks that
711
712
        # 'in' test could dominate, so I'm leaving this change in place -
712
713
        # when its fast enough to consider profiling big datasets we can review.
713
714
 
714
 
 
715
 
 
 
715
              
 
716
             
716
717
 
717
718
        for l in self._weave:
718
719
            if l.__class__ == tuple:
747
748
 
748
749
    def _maybe_lookup(self, name_or_index):
749
750
        """Convert possible symbolic name to index, or pass through indexes.
750
 
 
 
751
        
751
752
        NOT FOR PUBLIC USE.
752
753
        """
753
754
        if isinstance(name_or_index, (int, long)):
763
764
        measured_sha1 = sha_strings(result)
764
765
        if measured_sha1 != expected_sha1:
765
766
            raise errors.WeaveInvalidChecksum(
766
 
                    'file %s, revision %s, expected: %s, measured %s'
 
767
                    'file %s, revision %s, expected: %s, measured %s' 
767
768
                    % (self._weave_name, version_id,
768
769
                       expected_sha1, measured_sha1))
769
770
        return result
811
812
 
812
813
            if set(new_inc) != set(self.get_ancestry(name)):
813
814
                raise AssertionError(
814
 
                    'failed %s != %s'
 
815
                    'failed %s != %s' 
815
816
                    % (set(new_inc), set(self.get_ancestry(name))))
816
817
            inclusions[name] = new_inc
817
818
 
855
856
            parent_name = other._names[parent_idx]
856
857
            if parent_name not in self._name_map:
857
858
                # should not be possible
858
 
                raise WeaveError("missing parent {%s} of {%s} in %r"
 
859
                raise WeaveError("missing parent {%s} of {%s} in %r" 
859
860
                                 % (parent_name, other._name_map[other_idx], self))
860
861
            new_parents.append(self._name_map[parent_name])
861
862
        return new_parents
868
869
         * the same text
869
870
         * the same direct parents (by name, not index, and disregarding
870
871
           order)
871
 
 
 
872
        
872
873
        If present & correct return True;
873
 
        if not present in self return False;
 
874
        if not present in self return False; 
874
875
        if inconsistent raise error."""
875
876
        this_idx = self._name_map.get(name, -1)
876
877
        if this_idx != -1:
909
910
    """A WeaveFile represents a Weave on disk and writes on change."""
910
911
 
911
912
    WEAVE_SUFFIX = '.weave'
912
 
 
 
913
    
913
914
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
914
915
        """Create a WeaveFile.
915
 
 
 
916
        
916
917
        :param create: If not True, only open an existing knit.
917
918
        """
918
919
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
968
969
        super(WeaveFile, self).insert_record_stream(stream)
969
970
        self._save()
970
971
 
 
972
    @deprecated_method(one_five)
 
973
    def join(self, other, pb=None, msg=None, version_ids=None,
 
974
             ignore_missing=False):
 
975
        """Join other into self and save."""
 
976
        super(WeaveFile, self).join(other, pb, msg, version_ids, ignore_missing)
 
977
        self._save()
 
978
 
971
979
 
972
980
def _reweave(wa, wb, pb=None, msg=None):
973
981
    """Combine two weaves and return the result.
974
982
 
975
 
    This works even if a revision R has different parents in
 
983
    This works even if a revision R has different parents in 
976
984
    wa and wb.  In the resulting weave all the parents are given.
977
985
 
978
 
    This is done by just building up a new weave, maintaining ordering
 
986
    This is done by just building up a new weave, maintaining ordering 
979
987
    of the versions in the two inputs.  More efficient approaches
980
 
    might be possible but it should only be necessary to do
981
 
    this operation rarely, when a new previously ghost version is
 
988
    might be possible but it should only be necessary to do 
 
989
    this operation rarely, when a new previously ghost version is 
982
990
    inserted.
983
991
 
984
992
    :param pb: An optional progress bar, indicating how far done we are
1018
1026
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
1019
1027
    return wr
1020
1028
 
1021
 
 
1022
1029
def _reweave_parent_graphs(wa, wb):
1023
1030
    """Return combined parent ancestry for two weaves.
1024
 
 
 
1031
    
1025
1032
    Returned as a list of (version_name, set(parent_names))"""
1026
1033
    combined = {}
1027
1034
    for weave in [wa, wb]:
1029
1036
            p = combined.setdefault(name, set())
1030
1037
            p.update(map(weave._idx_to_name, weave._parents[idx]))
1031
1038
    return combined
 
1039
 
 
1040
 
 
1041
def weave_toc(w):
 
1042
    """Show the weave's table-of-contents"""
 
1043
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
 
1044
    for i in (6, 50, 10, 10):
 
1045
        print '-' * i,
 
1046
    print
 
1047
    for i in range(w.num_versions()):
 
1048
        sha1 = w._sha1s[i]
 
1049
        name = w._names[i]
 
1050
        parent_str = ' '.join(map(str, w._parents[i]))
 
1051
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
 
1052
 
 
1053
 
 
1054
 
 
1055
def weave_stats(weave_file, pb):
 
1056
    from bzrlib.weavefile import read_weave
 
1057
 
 
1058
    wf = file(weave_file, 'rb')
 
1059
    w = read_weave(wf)
 
1060
    # FIXME: doesn't work on pipes
 
1061
    weave_size = wf.tell()
 
1062
 
 
1063
    total = 0
 
1064
    vers = len(w)
 
1065
    for i in range(vers):
 
1066
        pb.update('checking sizes', i, vers)
 
1067
        for origin, lineno, line in w._extract([i]):
 
1068
            total += len(line)
 
1069
 
 
1070
    pb.clear()
 
1071
 
 
1072
    print 'versions          %9d' % vers
 
1073
    print 'weave file        %9d bytes' % weave_size
 
1074
    print 'total contents    %9d bytes' % total
 
1075
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
 
1076
    if vers:
 
1077
        avg = total/vers
 
1078
        print 'average size      %9d bytes' % avg
 
1079
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
 
1080
 
 
1081
 
 
1082
def usage():
 
1083
    print """bzr weave tool
 
1084
 
 
1085
Experimental tool for weave algorithm.
 
1086
 
 
1087
usage:
 
1088
    weave init WEAVEFILE
 
1089
        Create an empty weave file
 
1090
    weave get WEAVEFILE VERSION
 
1091
        Write out specified version.
 
1092
    weave check WEAVEFILE
 
1093
        Check consistency of all versions.
 
1094
    weave toc WEAVEFILE
 
1095
        Display table of contents.
 
1096
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
 
1097
        Add NEWTEXT, with specified parent versions.
 
1098
    weave annotate WEAVEFILE VERSION
 
1099
        Display origin of each line.
 
1100
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
 
1101
        Auto-merge two versions and display conflicts.
 
1102
    weave diff WEAVEFILE VERSION1 VERSION2 
 
1103
        Show differences between two versions.
 
1104
 
 
1105
example:
 
1106
 
 
1107
    % weave init foo.weave
 
1108
    % vi foo.txt
 
1109
    % weave add foo.weave ver0 < foo.txt
 
1110
    added version 0
 
1111
 
 
1112
    (create updated version)
 
1113
    % vi foo.txt
 
1114
    % weave get foo.weave 0 | diff -u - foo.txt
 
1115
    % weave add foo.weave ver1 0 < foo.txt
 
1116
    added version 1
 
1117
 
 
1118
    % weave get foo.weave 0 > foo.txt       (create forked version)
 
1119
    % vi foo.txt
 
1120
    % weave add foo.weave ver2 0 < foo.txt
 
1121
    added version 2
 
1122
 
 
1123
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
 
1124
    % vi foo.txt                            (resolve conflicts)
 
1125
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
 
1126
    
 
1127
"""
 
1128
    
 
1129
 
 
1130
 
 
1131
def main(argv):
 
1132
    import sys
 
1133
    import os
 
1134
    try:
 
1135
        import bzrlib
 
1136
    except ImportError:
 
1137
        # in case we're run directly from the subdirectory
 
1138
        sys.path.append('..')
 
1139
        import bzrlib
 
1140
    from bzrlib.weavefile import write_weave, read_weave
 
1141
    from bzrlib.progress import ProgressBar
 
1142
 
 
1143
    try:
 
1144
        import psyco
 
1145
        psyco.full()
 
1146
    except ImportError:
 
1147
        pass
 
1148
 
 
1149
    if len(argv) < 2:
 
1150
        usage()
 
1151
        return 0
 
1152
 
 
1153
    cmd = argv[1]
 
1154
 
 
1155
    def readit():
 
1156
        return read_weave(file(argv[2], 'rb'))
 
1157
    
 
1158
    if cmd == 'help':
 
1159
        usage()
 
1160
    elif cmd == 'add':
 
1161
        w = readit()
 
1162
        # at the moment, based on everything in the file
 
1163
        name = argv[3]
 
1164
        parents = map(int, argv[4:])
 
1165
        lines = sys.stdin.readlines()
 
1166
        ver = w.add(name, parents, lines)
 
1167
        write_weave(w, file(argv[2], 'wb'))
 
1168
        print 'added version %r %d' % (name, ver)
 
1169
    elif cmd == 'init':
 
1170
        fn = argv[2]
 
1171
        if os.path.exists(fn):
 
1172
            raise IOError("file exists")
 
1173
        w = Weave()
 
1174
        write_weave(w, file(fn, 'wb'))
 
1175
    elif cmd == 'get': # get one version
 
1176
        w = readit()
 
1177
        sys.stdout.writelines(w.get_iter(int(argv[3])))
 
1178
        
 
1179
    elif cmd == 'diff':
 
1180
        w = readit()
 
1181
        fn = argv[2]
 
1182
        v1, v2 = map(int, argv[3:5])
 
1183
        lines1 = w.get(v1)
 
1184
        lines2 = w.get(v2)
 
1185
        diff_gen = bzrlib.patiencediff.unified_diff(lines1, lines2,
 
1186
                                '%s version %d' % (fn, v1),
 
1187
                                '%s version %d' % (fn, v2))
 
1188
        sys.stdout.writelines(diff_gen)
 
1189
            
 
1190
    elif cmd == 'annotate':
 
1191
        w = readit()
 
1192
        # newline is added to all lines regardless; too hard to get
 
1193
        # reasonable formatting otherwise
 
1194
        lasto = None
 
1195
        for origin, text in w.annotate(int(argv[3])):
 
1196
            text = text.rstrip('\r\n')
 
1197
            if origin == lasto:
 
1198
                print '      | %s' % (text)
 
1199
            else:
 
1200
                print '%5d | %s' % (origin, text)
 
1201
                lasto = origin
 
1202
                
 
1203
    elif cmd == 'toc':
 
1204
        weave_toc(readit())
 
1205
 
 
1206
    elif cmd == 'stats':
 
1207
        weave_stats(argv[2], ProgressBar())
 
1208
        
 
1209
    elif cmd == 'check':
 
1210
        w = readit()
 
1211
        pb = ProgressBar()
 
1212
        w.check(pb)
 
1213
        pb.clear()
 
1214
        print '%d versions ok' % w.num_versions()
 
1215
 
 
1216
    elif cmd == 'inclusions':
 
1217
        w = readit()
 
1218
        print ' '.join(map(str, w.inclusions([int(argv[3])])))
 
1219
 
 
1220
    elif cmd == 'parents':
 
1221
        w = readit()
 
1222
        print ' '.join(map(str, w._parents[int(argv[3])]))
 
1223
 
 
1224
    elif cmd == 'plan-merge':
 
1225
        # replaced by 'bzr weave-plan-merge'
 
1226
        w = readit()
 
1227
        for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
 
1228
            if line:
 
1229
                print '%14s | %s' % (state, line),
 
1230
    elif cmd == 'merge':
 
1231
        # replaced by 'bzr weave-merge-text'
 
1232
        w = readit()
 
1233
        p = w.plan_merge(int(argv[3]), int(argv[4]))
 
1234
        sys.stdout.writelines(w.weave_merge(p))
 
1235
    else:
 
1236
        raise ValueError('unknown command %r' % cmd)
 
1237
    
 
1238
 
 
1239
if __name__ == '__main__':
 
1240
    import sys
 
1241
    sys.exit(main(sys.argv))