~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: Tarmac
  • Author(s): Vincent Ladeuil
  • Date: 2017-01-30 14:42:05 UTC
  • mfrom: (6620.1.1 trunk)
  • Revision ID: tarmac-20170130144205-r8fh2xpmiuxyozpv
Merge  2.7 into trunk including fix for bug #1657238 [r=vila]

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