~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: Martin Pool
  • Date: 2008-07-14 07:39:30 UTC
  • mto: This revision was merged to the branch mainline in revision 3537.
  • Revision ID: mbp@sourcefrog.net-20080714073930-z8nl2c44jal0eozs
Update test for knit.check() to expect it to recurse into fallback vfs

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
 
 
21
 
19
22
"""Weave - storage of related text file versions"""
20
23
 
21
 
from __future__ import absolute_import
22
24
 
23
25
# XXX: If we do weaves this way, will a merge still behave the same
24
26
# way if it's done in a different order?  That's a pretty desirable
59
61
# where the basis and destination are unchanged.
60
62
 
61
63
# FIXME: Sometimes we will be given a parents list for a revision
62
 
# that includes some redundant parents (i.e. already a parent of
63
 
# something in the list.)  We should eliminate them.  This can
 
64
# that includes some redundant parents (i.e. already a parent of 
 
65
# something in the list.)  We should eliminate them.  This can 
64
66
# be done fairly efficiently because the sequence numbers constrain
65
67
# the possible relationships.
66
68
 
69
71
from copy import copy
70
72
from cStringIO import StringIO
71
73
import os
 
74
import sha
 
75
import time
 
76
import warnings
72
77
 
73
 
from bzrlib.lazy_import import lazy_import
74
 
lazy_import(globals(), """
75
 
from bzrlib import tsort
76
 
""")
77
78
from bzrlib import (
78
 
    errors,
79
 
    osutils,
 
79
    progress,
80
80
    )
81
81
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
82
82
        RevisionAlreadyPresent,
83
83
        RevisionNotPresent,
84
84
        UnavailableRepresentation,
 
85
        WeaveRevisionAlreadyPresent,
 
86
        WeaveRevisionNotPresent,
85
87
        )
86
 
from bzrlib.osutils import dirname, sha, sha_strings, split_lines
 
88
import bzrlib.errors as errors
 
89
from bzrlib.osutils import dirname, sha_strings, split_lines
87
90
import bzrlib.patiencediff
88
91
from bzrlib.revision import NULL_REVISION
89
92
from bzrlib.symbol_versioning import *
90
93
from bzrlib.trace import mutter
 
94
from bzrlib.tsort import topo_sort
91
95
from bzrlib.versionedfile import (
92
96
    AbsentContentFactory,
93
97
    adapter_registry,
94
98
    ContentFactory,
95
 
    sort_groupcompress,
96
99
    VersionedFile,
97
100
    )
98
101
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
117
120
    def get_bytes_as(self, storage_kind):
118
121
        if storage_kind == 'fulltext':
119
122
            return self._weave.get_text(self.key[-1])
120
 
        elif storage_kind == 'chunked':
121
 
            return self._weave.get_lines(self.key[-1])
122
123
        else:
123
124
            raise UnavailableRepresentation(self.key, storage_kind, 'fulltext')
124
125
 
125
126
 
126
127
class Weave(VersionedFile):
127
128
    """weave - versioned text file storage.
128
 
 
 
129
    
129
130
    A Weave manages versions of line-based text files, keeping track
130
131
    of the originating version for each line.
131
132
 
177
178
 
178
179
    * It doesn't seem very useful to have an active insertion
179
180
      inside an inactive insertion, but it might happen.
180
 
 
 
181
      
181
182
    * Therefore, all instructions are always"considered"; that
182
183
      is passed onto and off the stack.  An outer inactive block
183
184
      doesn't disable an inner block.
213
214
    """
214
215
 
215
216
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
216
 
                 '_weave_name', '_matcher', '_allow_reserved']
217
 
 
218
 
    def __init__(self, weave_name=None, access_mode='w', matcher=None,
219
 
                 get_scope=None, allow_reserved=False):
 
217
                 '_weave_name', '_matcher']
 
218
    
 
219
    def __init__(self, weave_name=None, access_mode='w', matcher=None, get_scope=None):
220
220
        """Create a weave.
221
221
 
222
222
        :param get_scope: A callable that returns an opaque object to be used
223
223
            for detecting when this weave goes out of scope (should stop
224
224
            answering requests or allowing mutation).
225
225
        """
226
 
        super(Weave, self).__init__()
 
226
        super(Weave, self).__init__(access_mode)
227
227
        self._weave = []
228
228
        self._parents = []
229
229
        self._sha1s = []
239
239
        self._get_scope = get_scope
240
240
        self._scope = get_scope()
241
241
        self._access_mode = access_mode
242
 
        self._allow_reserved = allow_reserved
243
242
 
244
243
    def __repr__(self):
245
244
        return "Weave(%r)" % self._weave_name
253
252
 
254
253
    def copy(self):
255
254
        """Return a deep copy of self.
256
 
 
 
255
        
257
256
        The copy can be modified without affecting the original weave."""
258
257
        other = Weave()
259
258
        other._weave = self._weave[:]
269
268
            return False
270
269
        return self._parents == other._parents \
271
270
               and self._weave == other._weave \
272
 
               and self._sha1s == other._sha1s
273
 
 
 
271
               and self._sha1s == other._sha1s 
 
272
    
274
273
    def __ne__(self, other):
275
274
        return not self.__eq__(other)
276
275
 
279
278
 
280
279
    def _lookup(self, name):
281
280
        """Convert symbolic version name to index."""
282
 
        if not self._allow_reserved:
283
 
            self.check_not_reserved_id(name)
 
281
        self.check_not_reserved_id(name)
284
282
        try:
285
283
            return self._name_map[name]
286
284
        except KeyError:
312
310
        versions = [version[-1] for version in versions]
313
311
        if ordering == 'topological':
314
312
            parents = self.get_parent_map(versions)
315
 
            new_versions = tsort.topo_sort(parents)
316
 
            new_versions.extend(set(versions).difference(set(parents)))
317
 
            versions = new_versions
318
 
        elif ordering == 'groupcompress':
319
 
            parents = self.get_parent_map(versions)
320
 
            new_versions = sort_groupcompress(parents)
 
313
            new_versions = topo_sort(parents)
321
314
            new_versions.extend(set(versions).difference(set(parents)))
322
315
            versions = new_versions
323
316
        for version in versions:
348
341
    def insert_record_stream(self, stream):
349
342
        """Insert a record stream into this versioned file.
350
343
 
351
 
        :param stream: A stream of records to insert.
 
344
        :param stream: A stream of records to insert. 
352
345
        :return: None
353
346
        :seealso VersionedFile.get_record_stream:
354
347
        """
359
352
                raise RevisionNotPresent([record.key[0]], self)
360
353
            # adapt to non-tuple interface
361
354
            parents = [parent[0] for parent in record.parents]
362
 
            if (record.storage_kind == 'fulltext'
363
 
                or record.storage_kind == 'chunked'):
 
355
            if record.storage_kind == 'fulltext':
364
356
                self.add_lines(record.key[0], parents,
365
 
                    osutils.chunks_to_lines(record.get_bytes_as('chunked')))
 
357
                    split_lines(record.get_bytes_as('fulltext')))
366
358
            else:
367
359
                adapter_key = record.storage_kind, 'fulltext'
368
360
                try:
371
363
                    adapter_factory = adapter_registry.get(adapter_key)
372
364
                    adapter = adapter_factory(self)
373
365
                    adapters[adapter_key] = adapter
374
 
                lines = split_lines(adapter.get_bytes(record))
 
366
                lines = split_lines(adapter.get_bytes(
 
367
                    record, record.get_bytes_as(record.storage_kind)))
375
368
                try:
376
369
                    self.add_lines(record.key[0], parents, lines)
377
370
                except RevisionAlreadyPresent:
397
390
 
398
391
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
399
392
        """Add a single text on top of the weave.
400
 
 
 
393
  
401
394
        Returns the index number of the newly added version.
402
395
 
403
396
        version_id
404
397
            Symbolic name for this version.
405
398
            (Typically the revision-id of the revision that added it.)
406
 
            If None, a name will be allocated based on the hash. (sha1:SHAHASH)
407
399
 
408
400
        parents
409
401
            List or set of direct parent version numbers.
410
 
 
 
402
            
411
403
        lines
412
404
            Sequence of lines to be added in the new version.
413
405
 
419
411
            sha1 = sha_strings(lines)
420
412
        if sha1 == nostore_sha:
421
413
            raise errors.ExistingContent
422
 
        if version_id is None:
423
 
            version_id = "sha1:" + sha1
424
414
        if version_id in self._name_map:
425
415
            return self._check_repeated_add(version_id, parents, lines, sha1)
426
416
 
437
427
        self._names.append(version_id)
438
428
        self._name_map[version_id] = new_version
439
429
 
440
 
 
 
430
            
441
431
        if not parents:
442
432
            # special case; adding with no parents revision; can do
443
433
            # this more quickly by just appending unconditionally.
454
444
            if sha1 == self._sha1s[pv]:
455
445
                # special case: same as the single parent
456
446
                return new_version
457
 
 
 
447
            
458
448
 
459
449
        ancestors = self._inclusions(parents)
460
450
 
509
499
                # i2; we want to insert after this region to make sure
510
500
                # we don't destroy ourselves
511
501
                i = i2 + offset
512
 
                self._weave[i:i] = ([('{', new_version)]
513
 
                                    + lines[j1:j2]
 
502
                self._weave[i:i] = ([('{', new_version)] 
 
503
                                    + lines[j1:j2] 
514
504
                                    + [('}', None)])
515
505
                offset += 2 + (j2 - j1)
516
506
        return new_version
543
533
            if not isinstance(l, basestring):
544
534
                raise ValueError("text line should be a string or unicode, not %s"
545
535
                                 % type(l))
546
 
 
 
536
        
547
537
 
548
538
 
549
539
    def _check_versions(self, indexes):
557
547
    def _compatible_parents(self, my_parents, other_parents):
558
548
        """During join check that other_parents are joinable with my_parents.
559
549
 
560
 
        Joinable is defined as 'is a subset of' - supersets may require
 
550
        Joinable is defined as 'is a subset of' - supersets may require 
561
551
        regeneration of diffs, but subsets do not.
562
552
        """
563
553
        return len(other_parents.difference(my_parents)) == 0
577
567
            version_ids = self.versions()
578
568
        version_ids = set(version_ids)
579
569
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
580
 
            if inserted not in version_ids: continue
 
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
581
574
            if line[-1] != '\n':
582
575
                yield line + '\n', inserted
583
576
            else:
585
578
 
586
579
    def _walk_internal(self, version_ids=None):
587
580
        """Helper method for weave actions."""
588
 
 
 
581
        
589
582
        istack = []
590
583
        dset = set()
591
584
 
660
653
                # not in either revision
661
654
                yield 'irrelevant', line
662
655
 
 
656
        yield 'unchanged', ''           # terminator
 
657
 
663
658
    def _extract(self, versions):
664
659
        """Yield annotation of lines in included set.
665
660
 
672
667
        for i in versions:
673
668
            if not isinstance(i, int):
674
669
                raise ValueError(i)
675
 
 
 
670
            
676
671
        included = self._inclusions(versions)
677
672
 
678
673
        istack = []
687
682
 
688
683
        WFE = WeaveFormatError
689
684
 
690
 
        # wow.
 
685
        # wow. 
691
686
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
692
687
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
693
688
        # 1.6 seconds in 'isinstance'.
699
694
        # we're still spending ~1/4 of the method in isinstance though.
700
695
        # so lets hard code the acceptable string classes we expect:
701
696
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
702
 
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list'
 
697
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list' 
703
698
        #                                          objects>
704
699
        # yay, down to ~1/4 the initial extract time, and our inline time
705
700
        # has shrunk again, with isinstance no longer dominating.
706
701
        # tweaking the stack inclusion test to use a set gives:
707
702
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
708
 
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list'
 
703
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list' 
709
704
        #                                          objects>
710
705
        # - a 5% win, or possibly just noise. However with large istacks that
711
706
        # 'in' test could dominate, so I'm leaving this change in place -
712
707
        # when its fast enough to consider profiling big datasets we can review.
713
708
 
714
 
 
715
 
 
 
709
              
 
710
             
716
711
 
717
712
        for l in self._weave:
718
713
            if l.__class__ == tuple:
747
742
 
748
743
    def _maybe_lookup(self, name_or_index):
749
744
        """Convert possible symbolic name to index, or pass through indexes.
750
 
 
 
745
        
751
746
        NOT FOR PUBLIC USE.
752
747
        """
753
748
        if isinstance(name_or_index, (int, long)):
763
758
        measured_sha1 = sha_strings(result)
764
759
        if measured_sha1 != expected_sha1:
765
760
            raise errors.WeaveInvalidChecksum(
766
 
                    'file %s, revision %s, expected: %s, measured %s'
 
761
                    'file %s, revision %s, expected: %s, measured %s' 
767
762
                    % (self._weave_name, version_id,
768
763
                       expected_sha1, measured_sha1))
769
764
        return result
803
798
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
804
799
            # The problem is that set membership is much more expensive
805
800
            name = self._idx_to_name(i)
806
 
            sha1s[name] = sha()
 
801
            sha1s[name] = sha.new()
807
802
            texts[name] = []
808
803
            new_inc = set([name])
809
804
            for p in self._parents[i]:
811
806
 
812
807
            if set(new_inc) != set(self.get_ancestry(name)):
813
808
                raise AssertionError(
814
 
                    'failed %s != %s'
 
809
                    'failed %s != %s' 
815
810
                    % (set(new_inc), set(self.get_ancestry(name))))
816
811
            inclusions[name] = new_inc
817
812
 
855
850
            parent_name = other._names[parent_idx]
856
851
            if parent_name not in self._name_map:
857
852
                # should not be possible
858
 
                raise WeaveError("missing parent {%s} of {%s} in %r"
 
853
                raise WeaveError("missing parent {%s} of {%s} in %r" 
859
854
                                 % (parent_name, other._name_map[other_idx], self))
860
855
            new_parents.append(self._name_map[parent_name])
861
856
        return new_parents
868
863
         * the same text
869
864
         * the same direct parents (by name, not index, and disregarding
870
865
           order)
871
 
 
 
866
        
872
867
        If present & correct return True;
873
 
        if not present in self return False;
 
868
        if not present in self return False; 
874
869
        if inconsistent raise error."""
875
870
        this_idx = self._name_map.get(name, -1)
876
871
        if this_idx != -1:
909
904
    """A WeaveFile represents a Weave on disk and writes on change."""
910
905
 
911
906
    WEAVE_SUFFIX = '.weave'
912
 
 
 
907
    
913
908
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
914
909
        """Create a WeaveFile.
915
 
 
 
910
        
916
911
        :param create: If not True, only open an existing knit.
917
912
        """
918
 
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
919
 
            allow_reserved=False)
 
913
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope)
920
914
        self._transport = transport
921
915
        self._filemode = filemode
922
916
        try:
923
 
            f = self._transport.get(name + WeaveFile.WEAVE_SUFFIX)
924
 
            _read_weave_v5(StringIO(f.read()), self)
 
917
            _read_weave_v5(self._transport.get(name + WeaveFile.WEAVE_SUFFIX), self)
925
918
        except errors.NoSuchFile:
926
919
            if not create:
927
920
                raise
969
962
        super(WeaveFile, self).insert_record_stream(stream)
970
963
        self._save()
971
964
 
 
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
972
 
973
973
def _reweave(wa, wb, pb=None, msg=None):
974
974
    """Combine two weaves and return the result.
975
975
 
976
 
    This works even if a revision R has different parents in
 
976
    This works even if a revision R has different parents in 
977
977
    wa and wb.  In the resulting weave all the parents are given.
978
978
 
979
 
    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 
980
980
    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
 
981
    might be possible but it should only be necessary to do 
 
982
    this operation rarely, when a new previously ghost version is 
983
983
    inserted.
984
984
 
985
985
    :param pb: An optional progress bar, indicating how far done we are
993
993
    # map from version name -> all parent names
994
994
    combined_parents = _reweave_parent_graphs(wa, wb)
995
995
    mutter("combined parents: %r", combined_parents)
996
 
    order = tsort.topo_sort(combined_parents.iteritems())
 
996
    order = topo_sort(combined_parents.iteritems())
997
997
    mutter("order to reweave: %r", order)
998
998
 
999
999
    if pb and not msg:
1019
1019
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
1020
1020
    return wr
1021
1021
 
1022
 
 
1023
1022
def _reweave_parent_graphs(wa, wb):
1024
1023
    """Return combined parent ancestry for two weaves.
1025
 
 
 
1024
    
1026
1025
    Returned as a list of (version_name, set(parent_names))"""
1027
1026
    combined = {}
1028
1027
    for weave in [wa, wb]:
1030
1029
            p = combined.setdefault(name, set())
1031
1030
            p.update(map(weave._idx_to_name, weave._parents[idx]))
1032
1031
    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))