~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: Martin Pool
  • Date: 2008-10-20 23:58:12 UTC
  • mto: This revision was merged to the branch mainline in revision 3787.
  • Revision ID: mbp@sourcefrog.net-20081020235812-itg90mk0u4dez92z
lp-upload-release now handles names like bzr-1.8.tar.gz

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
 
77
79
from bzrlib import tsort
78
80
""")
79
81
from bzrlib import (
80
 
    errors,
81
 
    osutils,
82
82
    progress,
83
83
    )
84
84
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
88
88
        WeaveRevisionAlreadyPresent,
89
89
        WeaveRevisionNotPresent,
90
90
        )
 
91
import bzrlib.errors as errors
91
92
from bzrlib.osutils import dirname, sha, sha_strings, split_lines
92
93
import bzrlib.patiencediff
93
94
from bzrlib.revision import NULL_REVISION
97
98
    AbsentContentFactory,
98
99
    adapter_registry,
99
100
    ContentFactory,
100
 
    sort_groupcompress,
101
101
    VersionedFile,
102
102
    )
103
103
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
122
122
    def get_bytes_as(self, storage_kind):
123
123
        if storage_kind == 'fulltext':
124
124
            return self._weave.get_text(self.key[-1])
125
 
        elif storage_kind == 'chunked':
126
 
            return self._weave.get_lines(self.key[-1])
127
125
        else:
128
126
            raise UnavailableRepresentation(self.key, storage_kind, 'fulltext')
129
127
 
130
128
 
131
129
class Weave(VersionedFile):
132
130
    """weave - versioned text file storage.
133
 
 
 
131
    
134
132
    A Weave manages versions of line-based text files, keeping track
135
133
    of the originating version for each line.
136
134
 
182
180
 
183
181
    * It doesn't seem very useful to have an active insertion
184
182
      inside an inactive insertion, but it might happen.
185
 
 
 
183
      
186
184
    * Therefore, all instructions are always"considered"; that
187
185
      is passed onto and off the stack.  An outer inactive block
188
186
      doesn't disable an inner block.
258
256
 
259
257
    def copy(self):
260
258
        """Return a deep copy of self.
261
 
 
 
259
        
262
260
        The copy can be modified without affecting the original weave."""
263
261
        other = Weave()
264
262
        other._weave = self._weave[:]
274
272
            return False
275
273
        return self._parents == other._parents \
276
274
               and self._weave == other._weave \
277
 
               and self._sha1s == other._sha1s
278
 
 
 
275
               and self._sha1s == other._sha1s 
 
276
    
279
277
    def __ne__(self, other):
280
278
        return not self.__eq__(other)
281
279
 
320
318
            new_versions = tsort.topo_sort(parents)
321
319
            new_versions.extend(set(versions).difference(set(parents)))
322
320
            versions = new_versions
323
 
        elif ordering == 'groupcompress':
324
 
            parents = self.get_parent_map(versions)
325
 
            new_versions = sort_groupcompress(parents)
326
 
            new_versions.extend(set(versions).difference(set(parents)))
327
 
            versions = new_versions
328
321
        for version in versions:
329
322
            if version in self:
330
323
                yield WeaveContentFactory(version, self)
353
346
    def insert_record_stream(self, stream):
354
347
        """Insert a record stream into this versioned file.
355
348
 
356
 
        :param stream: A stream of records to insert.
 
349
        :param stream: A stream of records to insert. 
357
350
        :return: None
358
351
        :seealso VersionedFile.get_record_stream:
359
352
        """
364
357
                raise RevisionNotPresent([record.key[0]], self)
365
358
            # adapt to non-tuple interface
366
359
            parents = [parent[0] for parent in record.parents]
367
 
            if (record.storage_kind == 'fulltext'
368
 
                or record.storage_kind == 'chunked'):
 
360
            if record.storage_kind == 'fulltext':
369
361
                self.add_lines(record.key[0], parents,
370
 
                    osutils.chunks_to_lines(record.get_bytes_as('chunked')))
 
362
                    split_lines(record.get_bytes_as('fulltext')))
371
363
            else:
372
364
                adapter_key = record.storage_kind, 'fulltext'
373
365
                try:
376
368
                    adapter_factory = adapter_registry.get(adapter_key)
377
369
                    adapter = adapter_factory(self)
378
370
                    adapters[adapter_key] = adapter
379
 
                lines = split_lines(adapter.get_bytes(record))
 
371
                lines = split_lines(adapter.get_bytes(
 
372
                    record, record.get_bytes_as(record.storage_kind)))
380
373
                try:
381
374
                    self.add_lines(record.key[0], parents, lines)
382
375
                except RevisionAlreadyPresent:
402
395
 
403
396
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
404
397
        """Add a single text on top of the weave.
405
 
 
 
398
  
406
399
        Returns the index number of the newly added version.
407
400
 
408
401
        version_id
409
402
            Symbolic name for this version.
410
403
            (Typically the revision-id of the revision that added it.)
411
 
            If None, a name will be allocated based on the hash. (sha1:SHAHASH)
412
404
 
413
405
        parents
414
406
            List or set of direct parent version numbers.
415
 
 
 
407
            
416
408
        lines
417
409
            Sequence of lines to be added in the new version.
418
410
 
424
416
            sha1 = sha_strings(lines)
425
417
        if sha1 == nostore_sha:
426
418
            raise errors.ExistingContent
427
 
        if version_id is None:
428
 
            version_id = "sha1:" + sha1
429
419
        if version_id in self._name_map:
430
420
            return self._check_repeated_add(version_id, parents, lines, sha1)
431
421
 
442
432
        self._names.append(version_id)
443
433
        self._name_map[version_id] = new_version
444
434
 
445
 
 
 
435
            
446
436
        if not parents:
447
437
            # special case; adding with no parents revision; can do
448
438
            # this more quickly by just appending unconditionally.
459
449
            if sha1 == self._sha1s[pv]:
460
450
                # special case: same as the single parent
461
451
                return new_version
462
 
 
 
452
            
463
453
 
464
454
        ancestors = self._inclusions(parents)
465
455
 
514
504
                # i2; we want to insert after this region to make sure
515
505
                # we don't destroy ourselves
516
506
                i = i2 + offset
517
 
                self._weave[i:i] = ([('{', new_version)]
518
 
                                    + lines[j1:j2]
 
507
                self._weave[i:i] = ([('{', new_version)] 
 
508
                                    + lines[j1:j2] 
519
509
                                    + [('}', None)])
520
510
                offset += 2 + (j2 - j1)
521
511
        return new_version
548
538
            if not isinstance(l, basestring):
549
539
                raise ValueError("text line should be a string or unicode, not %s"
550
540
                                 % type(l))
551
 
 
 
541
        
552
542
 
553
543
 
554
544
    def _check_versions(self, indexes):
562
552
    def _compatible_parents(self, my_parents, other_parents):
563
553
        """During join check that other_parents are joinable with my_parents.
564
554
 
565
 
        Joinable is defined as 'is a subset of' - supersets may require
 
555
        Joinable is defined as 'is a subset of' - supersets may require 
566
556
        regeneration of diffs, but subsets do not.
567
557
        """
568
558
        return len(other_parents.difference(my_parents)) == 0
582
572
            version_ids = self.versions()
583
573
        version_ids = set(version_ids)
584
574
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
585
 
            if inserted not in version_ids: continue
 
575
            # if inserted not in version_ids then it was inserted before the
 
576
            # versions we care about, but because weaves cannot represent ghosts
 
577
            # properly, we do not filter down to that
 
578
            # if inserted not in version_ids: continue
586
579
            if line[-1] != '\n':
587
580
                yield line + '\n', inserted
588
581
            else:
590
583
 
591
584
    def _walk_internal(self, version_ids=None):
592
585
        """Helper method for weave actions."""
593
 
 
 
586
        
594
587
        istack = []
595
588
        dset = set()
596
589
 
677
670
        for i in versions:
678
671
            if not isinstance(i, int):
679
672
                raise ValueError(i)
680
 
 
 
673
            
681
674
        included = self._inclusions(versions)
682
675
 
683
676
        istack = []
692
685
 
693
686
        WFE = WeaveFormatError
694
687
 
695
 
        # wow.
 
688
        # wow. 
696
689
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
697
690
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
698
691
        # 1.6 seconds in 'isinstance'.
704
697
        # we're still spending ~1/4 of the method in isinstance though.
705
698
        # so lets hard code the acceptable string classes we expect:
706
699
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
707
 
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list'
 
700
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list' 
708
701
        #                                          objects>
709
702
        # yay, down to ~1/4 the initial extract time, and our inline time
710
703
        # has shrunk again, with isinstance no longer dominating.
711
704
        # tweaking the stack inclusion test to use a set gives:
712
705
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
713
 
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list'
 
706
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list' 
714
707
        #                                          objects>
715
708
        # - a 5% win, or possibly just noise. However with large istacks that
716
709
        # 'in' test could dominate, so I'm leaving this change in place -
717
710
        # when its fast enough to consider profiling big datasets we can review.
718
711
 
719
 
 
720
 
 
 
712
              
 
713
             
721
714
 
722
715
        for l in self._weave:
723
716
            if l.__class__ == tuple:
752
745
 
753
746
    def _maybe_lookup(self, name_or_index):
754
747
        """Convert possible symbolic name to index, or pass through indexes.
755
 
 
 
748
        
756
749
        NOT FOR PUBLIC USE.
757
750
        """
758
751
        if isinstance(name_or_index, (int, long)):
768
761
        measured_sha1 = sha_strings(result)
769
762
        if measured_sha1 != expected_sha1:
770
763
            raise errors.WeaveInvalidChecksum(
771
 
                    'file %s, revision %s, expected: %s, measured %s'
 
764
                    'file %s, revision %s, expected: %s, measured %s' 
772
765
                    % (self._weave_name, version_id,
773
766
                       expected_sha1, measured_sha1))
774
767
        return result
816
809
 
817
810
            if set(new_inc) != set(self.get_ancestry(name)):
818
811
                raise AssertionError(
819
 
                    'failed %s != %s'
 
812
                    'failed %s != %s' 
820
813
                    % (set(new_inc), set(self.get_ancestry(name))))
821
814
            inclusions[name] = new_inc
822
815
 
860
853
            parent_name = other._names[parent_idx]
861
854
            if parent_name not in self._name_map:
862
855
                # should not be possible
863
 
                raise WeaveError("missing parent {%s} of {%s} in %r"
 
856
                raise WeaveError("missing parent {%s} of {%s} in %r" 
864
857
                                 % (parent_name, other._name_map[other_idx], self))
865
858
            new_parents.append(self._name_map[parent_name])
866
859
        return new_parents
873
866
         * the same text
874
867
         * the same direct parents (by name, not index, and disregarding
875
868
           order)
876
 
 
 
869
        
877
870
        If present & correct return True;
878
 
        if not present in self return False;
 
871
        if not present in self return False; 
879
872
        if inconsistent raise error."""
880
873
        this_idx = self._name_map.get(name, -1)
881
874
        if this_idx != -1:
914
907
    """A WeaveFile represents a Weave on disk and writes on change."""
915
908
 
916
909
    WEAVE_SUFFIX = '.weave'
917
 
 
 
910
    
918
911
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
919
912
        """Create a WeaveFile.
920
 
 
 
913
        
921
914
        :param create: If not True, only open an existing knit.
922
915
        """
923
916
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
973
966
        super(WeaveFile, self).insert_record_stream(stream)
974
967
        self._save()
975
968
 
 
969
    @deprecated_method(one_five)
 
970
    def join(self, other, pb=None, msg=None, version_ids=None,
 
971
             ignore_missing=False):
 
972
        """Join other into self and save."""
 
973
        super(WeaveFile, self).join(other, pb, msg, version_ids, ignore_missing)
 
974
        self._save()
 
975
 
976
976
 
977
977
def _reweave(wa, wb, pb=None, msg=None):
978
978
    """Combine two weaves and return the result.
979
979
 
980
 
    This works even if a revision R has different parents in
 
980
    This works even if a revision R has different parents in 
981
981
    wa and wb.  In the resulting weave all the parents are given.
982
982
 
983
 
    This is done by just building up a new weave, maintaining ordering
 
983
    This is done by just building up a new weave, maintaining ordering 
984
984
    of the versions in the two inputs.  More efficient approaches
985
 
    might be possible but it should only be necessary to do
986
 
    this operation rarely, when a new previously ghost version is
 
985
    might be possible but it should only be necessary to do 
 
986
    this operation rarely, when a new previously ghost version is 
987
987
    inserted.
988
988
 
989
989
    :param pb: An optional progress bar, indicating how far done we are
1023
1023
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
1024
1024
    return wr
1025
1025
 
1026
 
 
1027
1026
def _reweave_parent_graphs(wa, wb):
1028
1027
    """Return combined parent ancestry for two weaves.
1029
 
 
 
1028
    
1030
1029
    Returned as a list of (version_name, set(parent_names))"""
1031
1030
    combined = {}
1032
1031
    for weave in [wa, wb]:
1034
1033
            p = combined.setdefault(name, set())
1035
1034
            p.update(map(weave._idx_to_name, weave._parents[idx]))
1036
1035
    return combined
 
1036
 
 
1037
 
 
1038
def weave_toc(w):
 
1039
    """Show the weave's table-of-contents"""
 
1040
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
 
1041
    for i in (6, 50, 10, 10):
 
1042
        print '-' * i,
 
1043
    print
 
1044
    for i in range(w.num_versions()):
 
1045
        sha1 = w._sha1s[i]
 
1046
        name = w._names[i]
 
1047
        parent_str = ' '.join(map(str, w._parents[i]))
 
1048
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
 
1049
 
 
1050
 
 
1051
 
 
1052
def weave_stats(weave_file, pb):
 
1053
    from bzrlib.weavefile import read_weave
 
1054
 
 
1055
    wf = file(weave_file, 'rb')
 
1056
    w = read_weave(wf)
 
1057
    # FIXME: doesn't work on pipes
 
1058
    weave_size = wf.tell()
 
1059
 
 
1060
    total = 0
 
1061
    vers = len(w)
 
1062
    for i in range(vers):
 
1063
        pb.update('checking sizes', i, vers)
 
1064
        for origin, lineno, line in w._extract([i]):
 
1065
            total += len(line)
 
1066
 
 
1067
    pb.clear()
 
1068
 
 
1069
    print 'versions          %9d' % vers
 
1070
    print 'weave file        %9d bytes' % weave_size
 
1071
    print 'total contents    %9d bytes' % total
 
1072
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
 
1073
    if vers:
 
1074
        avg = total/vers
 
1075
        print 'average size      %9d bytes' % avg
 
1076
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
 
1077
 
 
1078
 
 
1079
def usage():
 
1080
    print """bzr weave tool
 
1081
 
 
1082
Experimental tool for weave algorithm.
 
1083
 
 
1084
usage:
 
1085
    weave init WEAVEFILE
 
1086
        Create an empty weave file
 
1087
    weave get WEAVEFILE VERSION
 
1088
        Write out specified version.
 
1089
    weave check WEAVEFILE
 
1090
        Check consistency of all versions.
 
1091
    weave toc WEAVEFILE
 
1092
        Display table of contents.
 
1093
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
 
1094
        Add NEWTEXT, with specified parent versions.
 
1095
    weave annotate WEAVEFILE VERSION
 
1096
        Display origin of each line.
 
1097
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
 
1098
        Auto-merge two versions and display conflicts.
 
1099
    weave diff WEAVEFILE VERSION1 VERSION2 
 
1100
        Show differences between two versions.
 
1101
 
 
1102
example:
 
1103
 
 
1104
    % weave init foo.weave
 
1105
    % vi foo.txt
 
1106
    % weave add foo.weave ver0 < foo.txt
 
1107
    added version 0
 
1108
 
 
1109
    (create updated version)
 
1110
    % vi foo.txt
 
1111
    % weave get foo.weave 0 | diff -u - foo.txt
 
1112
    % weave add foo.weave ver1 0 < foo.txt
 
1113
    added version 1
 
1114
 
 
1115
    % weave get foo.weave 0 > foo.txt       (create forked version)
 
1116
    % vi foo.txt
 
1117
    % weave add foo.weave ver2 0 < foo.txt
 
1118
    added version 2
 
1119
 
 
1120
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
 
1121
    % vi foo.txt                            (resolve conflicts)
 
1122
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
 
1123
    
 
1124
"""
 
1125
    
 
1126
 
 
1127
 
 
1128
def main(argv):
 
1129
    import sys
 
1130
    import os
 
1131
    try:
 
1132
        import bzrlib
 
1133
    except ImportError:
 
1134
        # in case we're run directly from the subdirectory
 
1135
        sys.path.append('..')
 
1136
        import bzrlib
 
1137
    from bzrlib.weavefile import write_weave, read_weave
 
1138
    from bzrlib.progress import ProgressBar
 
1139
 
 
1140
    try:
 
1141
        import psyco
 
1142
        psyco.full()
 
1143
    except ImportError:
 
1144
        pass
 
1145
 
 
1146
    if len(argv) < 2:
 
1147
        usage()
 
1148
        return 0
 
1149
 
 
1150
    cmd = argv[1]
 
1151
 
 
1152
    def readit():
 
1153
        return read_weave(file(argv[2], 'rb'))
 
1154
    
 
1155
    if cmd == 'help':
 
1156
        usage()
 
1157
    elif cmd == 'add':
 
1158
        w = readit()
 
1159
        # at the moment, based on everything in the file
 
1160
        name = argv[3]
 
1161
        parents = map(int, argv[4:])
 
1162
        lines = sys.stdin.readlines()
 
1163
        ver = w.add(name, parents, lines)
 
1164
        write_weave(w, file(argv[2], 'wb'))
 
1165
        print 'added version %r %d' % (name, ver)
 
1166
    elif cmd == 'init':
 
1167
        fn = argv[2]
 
1168
        if os.path.exists(fn):
 
1169
            raise IOError("file exists")
 
1170
        w = Weave()
 
1171
        write_weave(w, file(fn, 'wb'))
 
1172
    elif cmd == 'get': # get one version
 
1173
        w = readit()
 
1174
        sys.stdout.writelines(w.get_iter(int(argv[3])))
 
1175
        
 
1176
    elif cmd == 'diff':
 
1177
        w = readit()
 
1178
        fn = argv[2]
 
1179
        v1, v2 = map(int, argv[3:5])
 
1180
        lines1 = w.get(v1)
 
1181
        lines2 = w.get(v2)
 
1182
        diff_gen = bzrlib.patiencediff.unified_diff(lines1, lines2,
 
1183
                                '%s version %d' % (fn, v1),
 
1184
                                '%s version %d' % (fn, v2))
 
1185
        sys.stdout.writelines(diff_gen)
 
1186
            
 
1187
    elif cmd == 'annotate':
 
1188
        w = readit()
 
1189
        # newline is added to all lines regardless; too hard to get
 
1190
        # reasonable formatting otherwise
 
1191
        lasto = None
 
1192
        for origin, text in w.annotate(int(argv[3])):
 
1193
            text = text.rstrip('\r\n')
 
1194
            if origin == lasto:
 
1195
                print '      | %s' % (text)
 
1196
            else:
 
1197
                print '%5d | %s' % (origin, text)
 
1198
                lasto = origin
 
1199
                
 
1200
    elif cmd == 'toc':
 
1201
        weave_toc(readit())
 
1202
 
 
1203
    elif cmd == 'stats':
 
1204
        weave_stats(argv[2], ProgressBar())
 
1205
        
 
1206
    elif cmd == 'check':
 
1207
        w = readit()
 
1208
        pb = ProgressBar()
 
1209
        w.check(pb)
 
1210
        pb.clear()
 
1211
        print '%d versions ok' % w.num_versions()
 
1212
 
 
1213
    elif cmd == 'inclusions':
 
1214
        w = readit()
 
1215
        print ' '.join(map(str, w.inclusions([int(argv[3])])))
 
1216
 
 
1217
    elif cmd == 'parents':
 
1218
        w = readit()
 
1219
        print ' '.join(map(str, w._parents[int(argv[3])]))
 
1220
 
 
1221
    elif cmd == 'plan-merge':
 
1222
        # replaced by 'bzr weave-plan-merge'
 
1223
        w = readit()
 
1224
        for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
 
1225
            if line:
 
1226
                print '%14s | %s' % (state, line),
 
1227
    elif cmd == 'merge':
 
1228
        # replaced by 'bzr weave-merge-text'
 
1229
        w = readit()
 
1230
        p = w.plan_merge(int(argv[3]), int(argv[4]))
 
1231
        sys.stdout.writelines(w.weave_merge(p))
 
1232
    else:
 
1233
        raise ValueError('unknown command %r' % cmd)
 
1234
    
 
1235
 
 
1236
if __name__ == '__main__':
 
1237
    import sys
 
1238
    sys.exit(main(sys.argv))