/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: Martin von Gagern
  • Date: 2010-04-20 08:47:38 UTC
  • mfrom: (5167 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5195.
  • Revision ID: martin.vgagern@gmx.net-20100420084738-ygymnqmdllzrhpfn
merge trunk

Show diffs side-by-side

added added

removed removed

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