~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

NEWS section template into a separate file

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
 
71
69
from copy import copy
72
70
from cStringIO import StringIO
73
71
import os
74
 
import sha
75
72
import time
76
73
import warnings
77
74
 
 
75
from bzrlib.lazy_import import lazy_import
 
76
lazy_import(globals(), """
 
77
from bzrlib import tsort
 
78
""")
78
79
from bzrlib import (
 
80
    errors,
 
81
    osutils,
79
82
    progress,
80
83
    )
81
84
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
85
88
        WeaveRevisionAlreadyPresent,
86
89
        WeaveRevisionNotPresent,
87
90
        )
88
 
import bzrlib.errors as errors
89
 
from bzrlib.osutils import dirname, sha_strings, split_lines
 
91
from bzrlib.osutils import dirname, sha, sha_strings, split_lines
90
92
import bzrlib.patiencediff
91
93
from bzrlib.revision import NULL_REVISION
92
94
from bzrlib.symbol_versioning import *
93
95
from bzrlib.trace import mutter
94
 
from bzrlib.tsort import topo_sort
95
96
from bzrlib.versionedfile import (
96
97
    AbsentContentFactory,
97
98
    adapter_registry,
98
99
    ContentFactory,
 
100
    sort_groupcompress,
99
101
    VersionedFile,
100
102
    )
101
103
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
120
122
    def get_bytes_as(self, storage_kind):
121
123
        if storage_kind == 'fulltext':
122
124
            return self._weave.get_text(self.key[-1])
 
125
        elif storage_kind == 'chunked':
 
126
            return self._weave.get_lines(self.key[-1])
123
127
        else:
124
128
            raise UnavailableRepresentation(self.key, storage_kind, 'fulltext')
125
129
 
126
130
 
127
131
class Weave(VersionedFile):
128
132
    """weave - versioned text file storage.
129
 
    
 
133
 
130
134
    A Weave manages versions of line-based text files, keeping track
131
135
    of the originating version for each line.
132
136
 
178
182
 
179
183
    * It doesn't seem very useful to have an active insertion
180
184
      inside an inactive insertion, but it might happen.
181
 
      
 
185
 
182
186
    * Therefore, all instructions are always"considered"; that
183
187
      is passed onto and off the stack.  An outer inactive block
184
188
      doesn't disable an inner block.
214
218
    """
215
219
 
216
220
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
217
 
                 '_weave_name', '_matcher']
218
 
    
219
 
    def __init__(self, weave_name=None, access_mode='w', matcher=None, get_scope=None):
 
221
                 '_weave_name', '_matcher', '_allow_reserved']
 
222
 
 
223
    def __init__(self, weave_name=None, access_mode='w', matcher=None,
 
224
                 get_scope=None, allow_reserved=False):
220
225
        """Create a weave.
221
226
 
222
227
        :param get_scope: A callable that returns an opaque object to be used
223
228
            for detecting when this weave goes out of scope (should stop
224
229
            answering requests or allowing mutation).
225
230
        """
226
 
        super(Weave, self).__init__(access_mode)
 
231
        super(Weave, self).__init__()
227
232
        self._weave = []
228
233
        self._parents = []
229
234
        self._sha1s = []
239
244
        self._get_scope = get_scope
240
245
        self._scope = get_scope()
241
246
        self._access_mode = access_mode
 
247
        self._allow_reserved = allow_reserved
242
248
 
243
249
    def __repr__(self):
244
250
        return "Weave(%r)" % self._weave_name
252
258
 
253
259
    def copy(self):
254
260
        """Return a deep copy of self.
255
 
        
 
261
 
256
262
        The copy can be modified without affecting the original weave."""
257
263
        other = Weave()
258
264
        other._weave = self._weave[:]
268
274
            return False
269
275
        return self._parents == other._parents \
270
276
               and self._weave == other._weave \
271
 
               and self._sha1s == other._sha1s 
272
 
    
 
277
               and self._sha1s == other._sha1s
 
278
 
273
279
    def __ne__(self, other):
274
280
        return not self.__eq__(other)
275
281
 
278
284
 
279
285
    def _lookup(self, name):
280
286
        """Convert symbolic version name to index."""
281
 
        self.check_not_reserved_id(name)
 
287
        if not self._allow_reserved:
 
288
            self.check_not_reserved_id(name)
282
289
        try:
283
290
            return self._name_map[name]
284
291
        except KeyError:
310
317
        versions = [version[-1] for version in versions]
311
318
        if ordering == 'topological':
312
319
            parents = self.get_parent_map(versions)
313
 
            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)
314
326
            new_versions.extend(set(versions).difference(set(parents)))
315
327
            versions = new_versions
316
328
        for version in versions:
341
353
    def insert_record_stream(self, stream):
342
354
        """Insert a record stream into this versioned file.
343
355
 
344
 
        :param stream: A stream of records to insert. 
 
356
        :param stream: A stream of records to insert.
345
357
        :return: None
346
358
        :seealso VersionedFile.get_record_stream:
347
359
        """
352
364
                raise RevisionNotPresent([record.key[0]], self)
353
365
            # adapt to non-tuple interface
354
366
            parents = [parent[0] for parent in record.parents]
355
 
            if record.storage_kind == 'fulltext':
 
367
            if (record.storage_kind == 'fulltext'
 
368
                or record.storage_kind == 'chunked'):
356
369
                self.add_lines(record.key[0], parents,
357
 
                    split_lines(record.get_bytes_as('fulltext')))
 
370
                    osutils.chunks_to_lines(record.get_bytes_as('chunked')))
358
371
            else:
359
372
                adapter_key = record.storage_kind, 'fulltext'
360
373
                try:
363
376
                    adapter_factory = adapter_registry.get(adapter_key)
364
377
                    adapter = adapter_factory(self)
365
378
                    adapters[adapter_key] = adapter
366
 
                lines = split_lines(adapter.get_bytes(
367
 
                    record, record.get_bytes_as(record.storage_kind)))
 
379
                lines = split_lines(adapter.get_bytes(record))
368
380
                try:
369
381
                    self.add_lines(record.key[0], parents, lines)
370
382
                except RevisionAlreadyPresent:
390
402
 
391
403
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
392
404
        """Add a single text on top of the weave.
393
 
  
 
405
 
394
406
        Returns the index number of the newly added version.
395
407
 
396
408
        version_id
397
409
            Symbolic name for this version.
398
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)
399
412
 
400
413
        parents
401
414
            List or set of direct parent version numbers.
402
 
            
 
415
 
403
416
        lines
404
417
            Sequence of lines to be added in the new version.
405
418
 
411
424
            sha1 = sha_strings(lines)
412
425
        if sha1 == nostore_sha:
413
426
            raise errors.ExistingContent
 
427
        if version_id is None:
 
428
            version_id = "sha1:" + sha1
414
429
        if version_id in self._name_map:
415
430
            return self._check_repeated_add(version_id, parents, lines, sha1)
416
431
 
427
442
        self._names.append(version_id)
428
443
        self._name_map[version_id] = new_version
429
444
 
430
 
            
 
445
 
431
446
        if not parents:
432
447
            # special case; adding with no parents revision; can do
433
448
            # this more quickly by just appending unconditionally.
444
459
            if sha1 == self._sha1s[pv]:
445
460
                # special case: same as the single parent
446
461
                return new_version
447
 
            
 
462
 
448
463
 
449
464
        ancestors = self._inclusions(parents)
450
465
 
499
514
                # i2; we want to insert after this region to make sure
500
515
                # we don't destroy ourselves
501
516
                i = i2 + offset
502
 
                self._weave[i:i] = ([('{', new_version)] 
503
 
                                    + lines[j1:j2] 
 
517
                self._weave[i:i] = ([('{', new_version)]
 
518
                                    + lines[j1:j2]
504
519
                                    + [('}', None)])
505
520
                offset += 2 + (j2 - j1)
506
521
        return new_version
533
548
            if not isinstance(l, basestring):
534
549
                raise ValueError("text line should be a string or unicode, not %s"
535
550
                                 % type(l))
536
 
        
 
551
 
537
552
 
538
553
 
539
554
    def _check_versions(self, indexes):
547
562
    def _compatible_parents(self, my_parents, other_parents):
548
563
        """During join check that other_parents are joinable with my_parents.
549
564
 
550
 
        Joinable is defined as 'is a subset of' - supersets may require 
 
565
        Joinable is defined as 'is a subset of' - supersets may require
551
566
        regeneration of diffs, but subsets do not.
552
567
        """
553
568
        return len(other_parents.difference(my_parents)) == 0
567
582
            version_ids = self.versions()
568
583
        version_ids = set(version_ids)
569
584
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
570
 
            # if inserted not in version_ids then it was inserted before the
571
 
            # versions we care about, but because weaves cannot represent ghosts
572
 
            # properly, we do not filter down to that
573
 
            # if inserted not in version_ids: continue
 
585
            if inserted not in version_ids: continue
574
586
            if line[-1] != '\n':
575
587
                yield line + '\n', inserted
576
588
            else:
578
590
 
579
591
    def _walk_internal(self, version_ids=None):
580
592
        """Helper method for weave actions."""
581
 
        
 
593
 
582
594
        istack = []
583
595
        dset = set()
584
596
 
653
665
                # not in either revision
654
666
                yield 'irrelevant', line
655
667
 
656
 
        yield 'unchanged', ''           # terminator
657
 
 
658
668
    def _extract(self, versions):
659
669
        """Yield annotation of lines in included set.
660
670
 
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
798
808
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
799
809
            # The problem is that set membership is much more expensive
800
810
            name = self._idx_to_name(i)
801
 
            sha1s[name] = sha.new()
 
811
            sha1s[name] = sha()
802
812
            texts[name] = []
803
813
            new_inc = set([name])
804
814
            for p in self._parents[i]:
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
 
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope)
 
923
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
 
924
            allow_reserved=False)
914
925
        self._transport = transport
915
926
        self._filemode = filemode
916
927
        try:
962
973
        super(WeaveFile, self).insert_record_stream(stream)
963
974
        self._save()
964
975
 
965
 
    @deprecated_method(one_five)
966
 
    def join(self, other, pb=None, msg=None, version_ids=None,
967
 
             ignore_missing=False):
968
 
        """Join other into self and save."""
969
 
        super(WeaveFile, self).join(other, pb, msg, version_ids, ignore_missing)
970
 
        self._save()
971
 
 
972
976
 
973
977
def _reweave(wa, wb, pb=None, msg=None):
974
978
    """Combine two weaves and return the result.
975
979
 
976
 
    This works even if a revision R has different parents in 
 
980
    This works even if a revision R has different parents in
977
981
    wa and wb.  In the resulting weave all the parents are given.
978
982
 
979
 
    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
980
984
    of the versions in the two inputs.  More efficient approaches
981
 
    might be possible but it should only be necessary to do 
982
 
    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
983
987
    inserted.
984
988
 
985
989
    :param pb: An optional progress bar, indicating how far done we are
993
997
    # map from version name -> all parent names
994
998
    combined_parents = _reweave_parent_graphs(wa, wb)
995
999
    mutter("combined parents: %r", combined_parents)
996
 
    order = topo_sort(combined_parents.iteritems())
 
1000
    order = tsort.topo_sort(combined_parents.iteritems())
997
1001
    mutter("order to reweave: %r", order)
998
1002
 
999
1003
    if pb and not msg:
1019
1023
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
1020
1024
    return wr
1021
1025
 
 
1026
 
1022
1027
def _reweave_parent_graphs(wa, wb):
1023
1028
    """Return combined parent ancestry for two weaves.
1024
 
    
 
1029
 
1025
1030
    Returned as a list of (version_name, set(parent_names))"""
1026
1031
    combined = {}
1027
1032
    for weave in [wa, wb]:
1029
1034
            p = combined.setdefault(name, set())
1030
1035
            p.update(map(weave._idx_to_name, weave._parents[idx]))
1031
1036
    return combined
1032
 
 
1033
 
 
1034
 
def weave_toc(w):
1035
 
    """Show the weave's table-of-contents"""
1036
 
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
1037
 
    for i in (6, 50, 10, 10):
1038
 
        print '-' * i,
1039
 
    print
1040
 
    for i in range(w.num_versions()):
1041
 
        sha1 = w._sha1s[i]
1042
 
        name = w._names[i]
1043
 
        parent_str = ' '.join(map(str, w._parents[i]))
1044
 
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
1045
 
 
1046
 
 
1047
 
 
1048
 
def weave_stats(weave_file, pb):
1049
 
    from bzrlib.weavefile import read_weave
1050
 
 
1051
 
    wf = file(weave_file, 'rb')
1052
 
    w = read_weave(wf)
1053
 
    # FIXME: doesn't work on pipes
1054
 
    weave_size = wf.tell()
1055
 
 
1056
 
    total = 0
1057
 
    vers = len(w)
1058
 
    for i in range(vers):
1059
 
        pb.update('checking sizes', i, vers)
1060
 
        for origin, lineno, line in w._extract([i]):
1061
 
            total += len(line)
1062
 
 
1063
 
    pb.clear()
1064
 
 
1065
 
    print 'versions          %9d' % vers
1066
 
    print 'weave file        %9d bytes' % weave_size
1067
 
    print 'total contents    %9d bytes' % total
1068
 
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
1069
 
    if vers:
1070
 
        avg = total/vers
1071
 
        print 'average size      %9d bytes' % avg
1072
 
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
1073
 
 
1074
 
 
1075
 
def usage():
1076
 
    print """bzr weave tool
1077
 
 
1078
 
Experimental tool for weave algorithm.
1079
 
 
1080
 
usage:
1081
 
    weave init WEAVEFILE
1082
 
        Create an empty weave file
1083
 
    weave get WEAVEFILE VERSION
1084
 
        Write out specified version.
1085
 
    weave check WEAVEFILE
1086
 
        Check consistency of all versions.
1087
 
    weave toc WEAVEFILE
1088
 
        Display table of contents.
1089
 
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
1090
 
        Add NEWTEXT, with specified parent versions.
1091
 
    weave annotate WEAVEFILE VERSION
1092
 
        Display origin of each line.
1093
 
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
1094
 
        Auto-merge two versions and display conflicts.
1095
 
    weave diff WEAVEFILE VERSION1 VERSION2 
1096
 
        Show differences between two versions.
1097
 
 
1098
 
example:
1099
 
 
1100
 
    % weave init foo.weave
1101
 
    % vi foo.txt
1102
 
    % weave add foo.weave ver0 < foo.txt
1103
 
    added version 0
1104
 
 
1105
 
    (create updated version)
1106
 
    % vi foo.txt
1107
 
    % weave get foo.weave 0 | diff -u - foo.txt
1108
 
    % weave add foo.weave ver1 0 < foo.txt
1109
 
    added version 1
1110
 
 
1111
 
    % weave get foo.weave 0 > foo.txt       (create forked version)
1112
 
    % vi foo.txt
1113
 
    % weave add foo.weave ver2 0 < foo.txt
1114
 
    added version 2
1115
 
 
1116
 
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
1117
 
    % vi foo.txt                            (resolve conflicts)
1118
 
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
1119
 
    
1120
 
"""
1121
 
    
1122
 
 
1123
 
 
1124
 
def main(argv):
1125
 
    import sys
1126
 
    import os
1127
 
    try:
1128
 
        import bzrlib
1129
 
    except ImportError:
1130
 
        # in case we're run directly from the subdirectory
1131
 
        sys.path.append('..')
1132
 
        import bzrlib
1133
 
    from bzrlib.weavefile import write_weave, read_weave
1134
 
    from bzrlib.progress import ProgressBar
1135
 
 
1136
 
    try:
1137
 
        import psyco
1138
 
        psyco.full()
1139
 
    except ImportError:
1140
 
        pass
1141
 
 
1142
 
    if len(argv) < 2:
1143
 
        usage()
1144
 
        return 0
1145
 
 
1146
 
    cmd = argv[1]
1147
 
 
1148
 
    def readit():
1149
 
        return read_weave(file(argv[2], 'rb'))
1150
 
    
1151
 
    if cmd == 'help':
1152
 
        usage()
1153
 
    elif cmd == 'add':
1154
 
        w = readit()
1155
 
        # at the moment, based on everything in the file
1156
 
        name = argv[3]
1157
 
        parents = map(int, argv[4:])
1158
 
        lines = sys.stdin.readlines()
1159
 
        ver = w.add(name, parents, lines)
1160
 
        write_weave(w, file(argv[2], 'wb'))
1161
 
        print 'added version %r %d' % (name, ver)
1162
 
    elif cmd == 'init':
1163
 
        fn = argv[2]
1164
 
        if os.path.exists(fn):
1165
 
            raise IOError("file exists")
1166
 
        w = Weave()
1167
 
        write_weave(w, file(fn, 'wb'))
1168
 
    elif cmd == 'get': # get one version
1169
 
        w = readit()
1170
 
        sys.stdout.writelines(w.get_iter(int(argv[3])))
1171
 
        
1172
 
    elif cmd == 'diff':
1173
 
        w = readit()
1174
 
        fn = argv[2]
1175
 
        v1, v2 = map(int, argv[3:5])
1176
 
        lines1 = w.get(v1)
1177
 
        lines2 = w.get(v2)
1178
 
        diff_gen = bzrlib.patiencediff.unified_diff(lines1, lines2,
1179
 
                                '%s version %d' % (fn, v1),
1180
 
                                '%s version %d' % (fn, v2))
1181
 
        sys.stdout.writelines(diff_gen)
1182
 
            
1183
 
    elif cmd == 'annotate':
1184
 
        w = readit()
1185
 
        # newline is added to all lines regardless; too hard to get
1186
 
        # reasonable formatting otherwise
1187
 
        lasto = None
1188
 
        for origin, text in w.annotate(int(argv[3])):
1189
 
            text = text.rstrip('\r\n')
1190
 
            if origin == lasto:
1191
 
                print '      | %s' % (text)
1192
 
            else:
1193
 
                print '%5d | %s' % (origin, text)
1194
 
                lasto = origin
1195
 
                
1196
 
    elif cmd == 'toc':
1197
 
        weave_toc(readit())
1198
 
 
1199
 
    elif cmd == 'stats':
1200
 
        weave_stats(argv[2], ProgressBar())
1201
 
        
1202
 
    elif cmd == 'check':
1203
 
        w = readit()
1204
 
        pb = ProgressBar()
1205
 
        w.check(pb)
1206
 
        pb.clear()
1207
 
        print '%d versions ok' % w.num_versions()
1208
 
 
1209
 
    elif cmd == 'inclusions':
1210
 
        w = readit()
1211
 
        print ' '.join(map(str, w.inclusions([int(argv[3])])))
1212
 
 
1213
 
    elif cmd == 'parents':
1214
 
        w = readit()
1215
 
        print ' '.join(map(str, w._parents[int(argv[3])]))
1216
 
 
1217
 
    elif cmd == 'plan-merge':
1218
 
        # replaced by 'bzr weave-plan-merge'
1219
 
        w = readit()
1220
 
        for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
1221
 
            if line:
1222
 
                print '%14s | %s' % (state, line),
1223
 
    elif cmd == 'merge':
1224
 
        # replaced by 'bzr weave-merge-text'
1225
 
        w = readit()
1226
 
        p = w.plan_merge(int(argv[3]), int(argv[4]))
1227
 
        sys.stdout.writelines(w.weave_merge(p))
1228
 
    else:
1229
 
        raise ValueError('unknown command %r' % cmd)
1230
 
    
1231
 
 
1232
 
if __name__ == '__main__':
1233
 
    import sys
1234
 
    sys.exit(main(sys.argv))