~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: Jelmer Vernooij
  • Date: 2012-01-27 19:05:43 UTC
  • mto: This revision was merged to the branch mainline in revision 6450.
  • Revision ID: jelmer@samba.org-20120127190543-vk350mv4a0c7aug2
Fix weave test.

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 sha
75
 
import time
76
 
import warnings
77
72
 
 
73
from bzrlib.lazy_import import lazy_import
 
74
lazy_import(globals(), """
 
75
from bzrlib import tsort
 
76
""")
78
77
from bzrlib import (
79
 
    progress,
 
78
    errors,
 
79
    osutils,
80
80
    )
81
81
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
82
82
        RevisionAlreadyPresent,
83
83
        RevisionNotPresent,
84
84
        UnavailableRepresentation,
85
 
        WeaveRevisionAlreadyPresent,
86
 
        WeaveRevisionNotPresent,
87
85
        )
88
 
import bzrlib.errors as errors
89
 
from bzrlib.osutils import sha_strings, split_lines
 
86
from bzrlib.osutils import dirname, sha, sha_strings, split_lines
90
87
import bzrlib.patiencediff
 
88
from bzrlib.revision import NULL_REVISION
91
89
from bzrlib.symbol_versioning import *
92
90
from bzrlib.trace import mutter
93
 
from bzrlib.tsort import topo_sort
94
91
from bzrlib.versionedfile import (
95
92
    AbsentContentFactory,
96
93
    adapter_registry,
97
94
    ContentFactory,
98
 
    InterVersionedFile,
 
95
    sort_groupcompress,
99
96
    VersionedFile,
100
97
    )
101
98
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
110
107
    def __init__(self, version, weave):
111
108
        """Create a WeaveContentFactory for version from weave."""
112
109
        ContentFactory.__init__(self)
113
 
        self.sha1 = weave.get_sha1s([version])[0]
 
110
        self.sha1 = weave.get_sha1s([version])[version]
114
111
        self.key = (version,)
115
112
        parents = weave.get_parent_map([version])[version]
116
113
        self.parents = tuple((parent,) for parent in parents)
119
116
 
120
117
    def get_bytes_as(self, storage_kind):
121
118
        if storage_kind == 'fulltext':
122
 
            return self._weave.get_text(self.key[0])
 
119
            return self._weave.get_text(self.key[-1])
 
120
        elif storage_kind == 'chunked':
 
121
            return self._weave.get_lines(self.key[-1])
123
122
        else:
124
123
            raise UnavailableRepresentation(self.key, storage_kind, 'fulltext')
125
124
 
126
125
 
127
126
class Weave(VersionedFile):
128
127
    """weave - versioned text file storage.
129
 
    
 
128
 
130
129
    A Weave manages versions of line-based text files, keeping track
131
130
    of the originating version for each line.
132
131
 
178
177
 
179
178
    * It doesn't seem very useful to have an active insertion
180
179
      inside an inactive insertion, but it might happen.
181
 
      
 
180
 
182
181
    * Therefore, all instructions are always"considered"; that
183
182
      is passed onto and off the stack.  An outer inactive block
184
183
      doesn't disable an inner block.
214
213
    """
215
214
 
216
215
    __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):
 
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):
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__(access_mode)
 
226
        super(Weave, self).__init__()
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
242
243
 
243
244
    def __repr__(self):
244
245
        return "Weave(%r)" % self._weave_name
252
253
 
253
254
    def copy(self):
254
255
        """Return a deep copy of self.
255
 
        
 
256
 
256
257
        The copy can be modified without affecting the original weave."""
257
258
        other = Weave()
258
259
        other._weave = self._weave[:]
268
269
            return False
269
270
        return self._parents == other._parents \
270
271
               and self._weave == other._weave \
271
 
               and self._sha1s == other._sha1s 
272
 
    
 
272
               and self._sha1s == other._sha1s
 
273
 
273
274
    def __ne__(self, other):
274
275
        return not self.__eq__(other)
275
276
 
278
279
 
279
280
    def _lookup(self, name):
280
281
        """Convert symbolic version name to index."""
281
 
        self.check_not_reserved_id(name)
 
282
        if not self._allow_reserved:
 
283
            self.check_not_reserved_id(name)
282
284
        try:
283
285
            return self._name_map[name]
284
286
        except KeyError:
307
309
        :return: An iterator of ContentFactory objects, each of which is only
308
310
            valid until the iterator is advanced.
309
311
        """
 
312
        versions = [version[-1] for version in versions]
310
313
        if ordering == 'topological':
311
314
            parents = self.get_parent_map(versions)
312
 
            new_versions = topo_sort(parents)
 
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
321
            new_versions.extend(set(versions).difference(set(parents)))
314
322
            versions = new_versions
315
323
        for version in versions:
322
330
        """See VersionedFile.get_parent_map."""
323
331
        result = {}
324
332
        for version_id in version_ids:
325
 
            try:
326
 
                result[version_id] = tuple(
327
 
                    map(self._idx_to_name, self._parents[self._lookup(version_id)]))
328
 
            except RevisionNotPresent:
329
 
                pass
 
333
            if version_id == NULL_REVISION:
 
334
                parents = ()
 
335
            else:
 
336
                try:
 
337
                    parents = tuple(
 
338
                        map(self._idx_to_name,
 
339
                            self._parents[self._lookup(version_id)]))
 
340
                except RevisionNotPresent:
 
341
                    continue
 
342
            result[version_id] = parents
330
343
        return result
331
344
 
332
345
    def get_parents_with_ghosts(self, version_id):
335
348
    def insert_record_stream(self, stream):
336
349
        """Insert a record stream into this versioned file.
337
350
 
338
 
        :param stream: A stream of records to insert. 
 
351
        :param stream: A stream of records to insert.
339
352
        :return: None
340
353
        :seealso VersionedFile.get_record_stream:
341
354
        """
346
359
                raise RevisionNotPresent([record.key[0]], self)
347
360
            # adapt to non-tuple interface
348
361
            parents = [parent[0] for parent in record.parents]
349
 
            if record.storage_kind == 'fulltext':
 
362
            if (record.storage_kind == 'fulltext'
 
363
                or record.storage_kind == 'chunked'):
350
364
                self.add_lines(record.key[0], parents,
351
 
                    split_lines(record.get_bytes_as('fulltext')))
 
365
                    osutils.chunks_to_lines(record.get_bytes_as('chunked')))
352
366
            else:
353
367
                adapter_key = record.storage_kind, 'fulltext'
354
368
                try:
357
371
                    adapter_factory = adapter_registry.get(adapter_key)
358
372
                    adapter = adapter_factory(self)
359
373
                    adapters[adapter_key] = adapter
360
 
                lines = split_lines(adapter.get_bytes(
361
 
                    record, record.get_bytes_as(record.storage_kind)))
 
374
                lines = split_lines(adapter.get_bytes(record))
362
375
                try:
363
376
                    self.add_lines(record.key[0], parents, lines)
364
377
                except RevisionAlreadyPresent:
384
397
 
385
398
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
386
399
        """Add a single text on top of the weave.
387
 
  
 
400
 
388
401
        Returns the index number of the newly added version.
389
402
 
390
403
        version_id
391
404
            Symbolic name for this version.
392
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)
393
407
 
394
408
        parents
395
409
            List or set of direct parent version numbers.
396
 
            
 
410
 
397
411
        lines
398
412
            Sequence of lines to be added in the new version.
399
413
 
405
419
            sha1 = sha_strings(lines)
406
420
        if sha1 == nostore_sha:
407
421
            raise errors.ExistingContent
 
422
        if version_id is None:
 
423
            version_id = "sha1:" + sha1
408
424
        if version_id in self._name_map:
409
425
            return self._check_repeated_add(version_id, parents, lines, sha1)
410
426
 
421
437
        self._names.append(version_id)
422
438
        self._name_map[version_id] = new_version
423
439
 
424
 
            
 
440
 
425
441
        if not parents:
426
442
            # special case; adding with no parents revision; can do
427
443
            # this more quickly by just appending unconditionally.
438
454
            if sha1 == self._sha1s[pv]:
439
455
                # special case: same as the single parent
440
456
                return new_version
441
 
            
 
457
 
442
458
 
443
459
        ancestors = self._inclusions(parents)
444
460
 
493
509
                # i2; we want to insert after this region to make sure
494
510
                # we don't destroy ourselves
495
511
                i = i2 + offset
496
 
                self._weave[i:i] = ([('{', new_version)] 
497
 
                                    + lines[j1:j2] 
 
512
                self._weave[i:i] = ([('{', new_version)]
 
513
                                    + lines[j1:j2]
498
514
                                    + [('}', None)])
499
515
                offset += 2 + (j2 - j1)
500
516
        return new_version
527
543
            if not isinstance(l, basestring):
528
544
                raise ValueError("text line should be a string or unicode, not %s"
529
545
                                 % type(l))
530
 
        
 
546
 
531
547
 
532
548
 
533
549
    def _check_versions(self, indexes):
541
557
    def _compatible_parents(self, my_parents, other_parents):
542
558
        """During join check that other_parents are joinable with my_parents.
543
559
 
544
 
        Joinable is defined as 'is a subset of' - supersets may require 
 
560
        Joinable is defined as 'is a subset of' - supersets may require
545
561
        regeneration of diffs, but subsets do not.
546
562
        """
547
563
        return len(other_parents.difference(my_parents)) == 0
561
577
            version_ids = self.versions()
562
578
        version_ids = set(version_ids)
563
579
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
564
 
            # if inserted not in version_ids then it was inserted before the
565
 
            # versions we care about, but because weaves cannot represent ghosts
566
 
            # properly, we do not filter down to that
567
 
            # if inserted not in version_ids: continue
 
580
            if inserted not in version_ids: continue
568
581
            if line[-1] != '\n':
569
582
                yield line + '\n', inserted
570
583
            else:
572
585
 
573
586
    def _walk_internal(self, version_ids=None):
574
587
        """Helper method for weave actions."""
575
 
        
 
588
 
576
589
        istack = []
577
590
        dset = set()
578
591
 
647
660
                # not in either revision
648
661
                yield 'irrelevant', line
649
662
 
650
 
        yield 'unchanged', ''           # terminator
651
 
 
652
663
    def _extract(self, versions):
653
664
        """Yield annotation of lines in included set.
654
665
 
661
672
        for i in versions:
662
673
            if not isinstance(i, int):
663
674
                raise ValueError(i)
664
 
            
 
675
 
665
676
        included = self._inclusions(versions)
666
677
 
667
678
        istack = []
676
687
 
677
688
        WFE = WeaveFormatError
678
689
 
679
 
        # wow. 
 
690
        # wow.
680
691
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
681
692
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
682
693
        # 1.6 seconds in 'isinstance'.
688
699
        # we're still spending ~1/4 of the method in isinstance though.
689
700
        # so lets hard code the acceptable string classes we expect:
690
701
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
691
 
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list' 
 
702
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list'
692
703
        #                                          objects>
693
704
        # yay, down to ~1/4 the initial extract time, and our inline time
694
705
        # has shrunk again, with isinstance no longer dominating.
695
706
        # tweaking the stack inclusion test to use a set gives:
696
707
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
697
 
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list' 
 
708
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list'
698
709
        #                                          objects>
699
710
        # - a 5% win, or possibly just noise. However with large istacks that
700
711
        # 'in' test could dominate, so I'm leaving this change in place -
701
712
        # when its fast enough to consider profiling big datasets we can review.
702
713
 
703
 
              
704
 
             
 
714
 
 
715
 
705
716
 
706
717
        for l in self._weave:
707
718
            if l.__class__ == tuple:
736
747
 
737
748
    def _maybe_lookup(self, name_or_index):
738
749
        """Convert possible symbolic name to index, or pass through indexes.
739
 
        
 
750
 
740
751
        NOT FOR PUBLIC USE.
741
752
        """
742
753
        if isinstance(name_or_index, (int, long)):
752
763
        measured_sha1 = sha_strings(result)
753
764
        if measured_sha1 != expected_sha1:
754
765
            raise errors.WeaveInvalidChecksum(
755
 
                    'file %s, revision %s, expected: %s, measured %s' 
 
766
                    'file %s, revision %s, expected: %s, measured %s'
756
767
                    % (self._weave_name, version_id,
757
768
                       expected_sha1, measured_sha1))
758
769
        return result
759
770
 
760
771
    def get_sha1s(self, version_ids):
761
772
        """See VersionedFile.get_sha1s()."""
762
 
        return [self._sha1s[self._lookup(v)] for v in version_ids]
 
773
        result = {}
 
774
        for v in version_ids:
 
775
            result[v] = self._sha1s[self._lookup(v)]
 
776
        return result
763
777
 
764
778
    def num_versions(self):
765
779
        """How many versions are in this weave?"""
789
803
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
790
804
            # The problem is that set membership is much more expensive
791
805
            name = self._idx_to_name(i)
792
 
            sha1s[name] = sha.new()
 
806
            sha1s[name] = sha()
793
807
            texts[name] = []
794
808
            new_inc = set([name])
795
809
            for p in self._parents[i]:
797
811
 
798
812
            if set(new_inc) != set(self.get_ancestry(name)):
799
813
                raise AssertionError(
800
 
                    'failed %s != %s' 
 
814
                    'failed %s != %s'
801
815
                    % (set(new_inc), set(self.get_ancestry(name))))
802
816
            inclusions[name] = new_inc
803
817
 
834
848
        # no lines outside of insertion blocks, that deletions are
835
849
        # properly paired, etc.
836
850
 
837
 
    def _join(self, other, pb, msg, version_ids, ignore_missing):
838
 
        """Worker routine for join()."""
839
 
        if not other.versions():
840
 
            return          # nothing to update, easy
841
 
 
842
 
        if not version_ids:
843
 
            # versions is never none, InterWeave checks this.
844
 
            return 0
845
 
 
846
 
        # two loops so that we do not change ourselves before verifying it
847
 
        # will be ok
848
 
        # work through in index order to make sure we get all dependencies
849
 
        names_to_join = []
850
 
        processed = 0
851
 
        # get the selected versions only that are in other.versions.
852
 
        version_ids = set(other.versions()).intersection(set(version_ids))
853
 
        # pull in the referenced graph.
854
 
        version_ids = other.get_ancestry(version_ids)
855
 
        pending_parents = other.get_parent_map(version_ids)
856
 
        pending_graph = pending_parents.items()
857
 
        if len(pending_graph) != len(version_ids):
858
 
            raise RevisionNotPresent(
859
 
                set(version_ids) - set(pending_parents.keys()), self)
860
 
        for name in topo_sort(pending_graph):
861
 
            other_idx = other._name_map[name]
862
 
            # returns True if we have it, False if we need it.
863
 
            if not self._check_version_consistent(other, other_idx, name):
864
 
                names_to_join.append((other_idx, name))
865
 
            processed += 1
866
 
 
867
 
        if pb and not msg:
868
 
            msg = 'weave join'
869
 
 
870
 
        merged = 0
871
 
        time0 = time.time()
872
 
        for other_idx, name in names_to_join:
873
 
            # TODO: If all the parents of the other version are already
874
 
            # present then we can avoid some work by just taking the delta
875
 
            # and adjusting the offsets.
876
 
            new_parents = self._imported_parents(other, other_idx)
877
 
            sha1 = other._sha1s[other_idx]
878
 
 
879
 
            merged += 1
880
 
 
881
 
            if pb:
882
 
                pb.update(msg, merged, len(names_to_join))
883
 
           
884
 
            lines = other.get_lines(other_idx)
885
 
            self._add(name, lines, new_parents, sha1)
886
 
 
887
 
        mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
888
 
                merged, processed, self._weave_name, time.time()-time0))
889
 
 
890
851
    def _imported_parents(self, other, other_idx):
891
852
        """Return list of parents in self corresponding to indexes in other."""
892
853
        new_parents = []
894
855
            parent_name = other._names[parent_idx]
895
856
            if parent_name not in self._name_map:
896
857
                # should not be possible
897
 
                raise WeaveError("missing parent {%s} of {%s} in %r" 
 
858
                raise WeaveError("missing parent {%s} of {%s} in %r"
898
859
                                 % (parent_name, other._name_map[other_idx], self))
899
860
            new_parents.append(self._name_map[parent_name])
900
861
        return new_parents
907
868
         * the same text
908
869
         * the same direct parents (by name, not index, and disregarding
909
870
           order)
910
 
        
 
871
 
911
872
        If present & correct return True;
912
 
        if not present in self return False; 
 
873
        if not present in self return False;
913
874
        if inconsistent raise error."""
914
875
        this_idx = self._name_map.get(name, -1)
915
876
        if this_idx != -1:
948
909
    """A WeaveFile represents a Weave on disk and writes on change."""
949
910
 
950
911
    WEAVE_SUFFIX = '.weave'
951
 
    
 
912
 
952
913
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
953
914
        """Create a WeaveFile.
954
 
        
 
915
 
955
916
        :param create: If not True, only open an existing knit.
956
917
        """
957
 
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope)
 
918
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
 
919
            allow_reserved=False)
958
920
        self._transport = transport
959
921
        self._filemode = filemode
960
922
        try:
961
 
            _read_weave_v5(self._transport.get(name + WeaveFile.WEAVE_SUFFIX), self)
 
923
            f = self._transport.get(name + WeaveFile.WEAVE_SUFFIX)
 
924
            _read_weave_v5(f, self)
962
925
        except errors.NoSuchFile:
963
926
            if not create:
964
927
                raise
989
952
        sio = StringIO()
990
953
        write_weave_v5(self, sio)
991
954
        sio.seek(0)
992
 
        self._transport.put_file(self._weave_name + WeaveFile.WEAVE_SUFFIX,
993
 
                                 sio,
994
 
                                 self._filemode)
 
955
        bytes = sio.getvalue()
 
956
        path = self._weave_name + WeaveFile.WEAVE_SUFFIX
 
957
        try:
 
958
            self._transport.put_bytes(path, bytes, self._filemode)
 
959
        except errors.NoSuchFile:
 
960
            self._transport.mkdir(dirname(path))
 
961
            self._transport.put_bytes(path, bytes, self._filemode)
995
962
 
996
963
    @staticmethod
997
964
    def get_suffixes():
1002
969
        super(WeaveFile, self).insert_record_stream(stream)
1003
970
        self._save()
1004
971
 
1005
 
    @deprecated_method(one_five)
1006
 
    def join(self, other, pb=None, msg=None, version_ids=None,
1007
 
             ignore_missing=False):
1008
 
        """Join other into self and save."""
1009
 
        super(WeaveFile, self).join(other, pb, msg, version_ids, ignore_missing)
1010
 
        self._save()
1011
 
 
1012
972
 
1013
973
def _reweave(wa, wb, pb=None, msg=None):
1014
974
    """Combine two weaves and return the result.
1015
975
 
1016
 
    This works even if a revision R has different parents in 
 
976
    This works even if a revision R has different parents in
1017
977
    wa and wb.  In the resulting weave all the parents are given.
1018
978
 
1019
 
    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
1020
980
    of the versions in the two inputs.  More efficient approaches
1021
 
    might be possible but it should only be necessary to do 
1022
 
    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
1023
983
    inserted.
1024
984
 
1025
985
    :param pb: An optional progress bar, indicating how far done we are
1033
993
    # map from version name -> all parent names
1034
994
    combined_parents = _reweave_parent_graphs(wa, wb)
1035
995
    mutter("combined parents: %r", combined_parents)
1036
 
    order = topo_sort(combined_parents.iteritems())
 
996
    order = tsort.topo_sort(combined_parents.iteritems())
1037
997
    mutter("order to reweave: %r", order)
1038
998
 
1039
999
    if pb and not msg:
1059
1019
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
1060
1020
    return wr
1061
1021
 
 
1022
 
1062
1023
def _reweave_parent_graphs(wa, wb):
1063
1024
    """Return combined parent ancestry for two weaves.
1064
 
    
 
1025
 
1065
1026
    Returned as a list of (version_name, set(parent_names))"""
1066
1027
    combined = {}
1067
1028
    for weave in [wa, wb]:
1069
1030
            p = combined.setdefault(name, set())
1070
1031
            p.update(map(weave._idx_to_name, weave._parents[idx]))
1071
1032
    return combined
1072
 
 
1073
 
 
1074
 
def weave_toc(w):
1075
 
    """Show the weave's table-of-contents"""
1076
 
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
1077
 
    for i in (6, 50, 10, 10):
1078
 
        print '-' * i,
1079
 
    print
1080
 
    for i in range(w.num_versions()):
1081
 
        sha1 = w._sha1s[i]
1082
 
        name = w._names[i]
1083
 
        parent_str = ' '.join(map(str, w._parents[i]))
1084
 
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
1085
 
 
1086
 
 
1087
 
 
1088
 
def weave_stats(weave_file, pb):
1089
 
    from bzrlib.weavefile import read_weave
1090
 
 
1091
 
    wf = file(weave_file, 'rb')
1092
 
    w = read_weave(wf)
1093
 
    # FIXME: doesn't work on pipes
1094
 
    weave_size = wf.tell()
1095
 
 
1096
 
    total = 0
1097
 
    vers = len(w)
1098
 
    for i in range(vers):
1099
 
        pb.update('checking sizes', i, vers)
1100
 
        for origin, lineno, line in w._extract([i]):
1101
 
            total += len(line)
1102
 
 
1103
 
    pb.clear()
1104
 
 
1105
 
    print 'versions          %9d' % vers
1106
 
    print 'weave file        %9d bytes' % weave_size
1107
 
    print 'total contents    %9d bytes' % total
1108
 
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
1109
 
    if vers:
1110
 
        avg = total/vers
1111
 
        print 'average size      %9d bytes' % avg
1112
 
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
1113
 
 
1114
 
 
1115
 
def usage():
1116
 
    print """bzr weave tool
1117
 
 
1118
 
Experimental tool for weave algorithm.
1119
 
 
1120
 
usage:
1121
 
    weave init WEAVEFILE
1122
 
        Create an empty weave file
1123
 
    weave get WEAVEFILE VERSION
1124
 
        Write out specified version.
1125
 
    weave check WEAVEFILE
1126
 
        Check consistency of all versions.
1127
 
    weave toc WEAVEFILE
1128
 
        Display table of contents.
1129
 
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
1130
 
        Add NEWTEXT, with specified parent versions.
1131
 
    weave annotate WEAVEFILE VERSION
1132
 
        Display origin of each line.
1133
 
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
1134
 
        Auto-merge two versions and display conflicts.
1135
 
    weave diff WEAVEFILE VERSION1 VERSION2 
1136
 
        Show differences between two versions.
1137
 
 
1138
 
example:
1139
 
 
1140
 
    % weave init foo.weave
1141
 
    % vi foo.txt
1142
 
    % weave add foo.weave ver0 < foo.txt
1143
 
    added version 0
1144
 
 
1145
 
    (create updated version)
1146
 
    % vi foo.txt
1147
 
    % weave get foo.weave 0 | diff -u - foo.txt
1148
 
    % weave add foo.weave ver1 0 < foo.txt
1149
 
    added version 1
1150
 
 
1151
 
    % weave get foo.weave 0 > foo.txt       (create forked version)
1152
 
    % vi foo.txt
1153
 
    % weave add foo.weave ver2 0 < foo.txt
1154
 
    added version 2
1155
 
 
1156
 
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
1157
 
    % vi foo.txt                            (resolve conflicts)
1158
 
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
1159
 
    
1160
 
"""
1161
 
    
1162
 
 
1163
 
 
1164
 
def main(argv):
1165
 
    import sys
1166
 
    import os
1167
 
    try:
1168
 
        import bzrlib
1169
 
    except ImportError:
1170
 
        # in case we're run directly from the subdirectory
1171
 
        sys.path.append('..')
1172
 
        import bzrlib
1173
 
    from bzrlib.weavefile import write_weave, read_weave
1174
 
    from bzrlib.progress import ProgressBar
1175
 
 
1176
 
    try:
1177
 
        import psyco
1178
 
        psyco.full()
1179
 
    except ImportError:
1180
 
        pass
1181
 
 
1182
 
    if len(argv) < 2:
1183
 
        usage()
1184
 
        return 0
1185
 
 
1186
 
    cmd = argv[1]
1187
 
 
1188
 
    def readit():
1189
 
        return read_weave(file(argv[2], 'rb'))
1190
 
    
1191
 
    if cmd == 'help':
1192
 
        usage()
1193
 
    elif cmd == 'add':
1194
 
        w = readit()
1195
 
        # at the moment, based on everything in the file
1196
 
        name = argv[3]
1197
 
        parents = map(int, argv[4:])
1198
 
        lines = sys.stdin.readlines()
1199
 
        ver = w.add(name, parents, lines)
1200
 
        write_weave(w, file(argv[2], 'wb'))
1201
 
        print 'added version %r %d' % (name, ver)
1202
 
    elif cmd == 'init':
1203
 
        fn = argv[2]
1204
 
        if os.path.exists(fn):
1205
 
            raise IOError("file exists")
1206
 
        w = Weave()
1207
 
        write_weave(w, file(fn, 'wb'))
1208
 
    elif cmd == 'get': # get one version
1209
 
        w = readit()
1210
 
        sys.stdout.writelines(w.get_iter(int(argv[3])))
1211
 
        
1212
 
    elif cmd == 'diff':
1213
 
        w = readit()
1214
 
        fn = argv[2]
1215
 
        v1, v2 = map(int, argv[3:5])
1216
 
        lines1 = w.get(v1)
1217
 
        lines2 = w.get(v2)
1218
 
        diff_gen = bzrlib.patiencediff.unified_diff(lines1, lines2,
1219
 
                                '%s version %d' % (fn, v1),
1220
 
                                '%s version %d' % (fn, v2))
1221
 
        sys.stdout.writelines(diff_gen)
1222
 
            
1223
 
    elif cmd == 'annotate':
1224
 
        w = readit()
1225
 
        # newline is added to all lines regardless; too hard to get
1226
 
        # reasonable formatting otherwise
1227
 
        lasto = None
1228
 
        for origin, text in w.annotate(int(argv[3])):
1229
 
            text = text.rstrip('\r\n')
1230
 
            if origin == lasto:
1231
 
                print '      | %s' % (text)
1232
 
            else:
1233
 
                print '%5d | %s' % (origin, text)
1234
 
                lasto = origin
1235
 
                
1236
 
    elif cmd == 'toc':
1237
 
        weave_toc(readit())
1238
 
 
1239
 
    elif cmd == 'stats':
1240
 
        weave_stats(argv[2], ProgressBar())
1241
 
        
1242
 
    elif cmd == 'check':
1243
 
        w = readit()
1244
 
        pb = ProgressBar()
1245
 
        w.check(pb)
1246
 
        pb.clear()
1247
 
        print '%d versions ok' % w.num_versions()
1248
 
 
1249
 
    elif cmd == 'inclusions':
1250
 
        w = readit()
1251
 
        print ' '.join(map(str, w.inclusions([int(argv[3])])))
1252
 
 
1253
 
    elif cmd == 'parents':
1254
 
        w = readit()
1255
 
        print ' '.join(map(str, w._parents[int(argv[3])]))
1256
 
 
1257
 
    elif cmd == 'plan-merge':
1258
 
        # replaced by 'bzr weave-plan-merge'
1259
 
        w = readit()
1260
 
        for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
1261
 
            if line:
1262
 
                print '%14s | %s' % (state, line),
1263
 
    elif cmd == 'merge':
1264
 
        # replaced by 'bzr weave-merge-text'
1265
 
        w = readit()
1266
 
        p = w.plan_merge(int(argv[3]), int(argv[4]))
1267
 
        sys.stdout.writelines(w.weave_merge(p))
1268
 
    else:
1269
 
        raise ValueError('unknown command %r' % cmd)
1270
 
    
1271
 
 
1272
 
if __name__ == '__main__':
1273
 
    import sys
1274
 
    sys.exit(main(sys.argv))
1275
 
 
1276
 
 
1277
 
class InterWeave(InterVersionedFile):
1278
 
    """Optimised code paths for weave to weave operations."""
1279
 
    
1280
 
    _matching_file_from_factory = staticmethod(WeaveFile)
1281
 
    _matching_file_to_factory = staticmethod(WeaveFile)
1282
 
    
1283
 
    @staticmethod
1284
 
    def is_compatible(source, target):
1285
 
        """Be compatible with weaves."""
1286
 
        try:
1287
 
            return (isinstance(source, Weave) and
1288
 
                    isinstance(target, Weave))
1289
 
        except AttributeError:
1290
 
            return False
1291
 
 
1292
 
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1293
 
        """See InterVersionedFile.join."""
1294
 
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1295
 
        if self.target.versions() == [] and version_ids is None:
1296
 
            self.target._copy_weave_content(self.source)
1297
 
            return
1298
 
        self.target._join(self.source, pb, msg, version_ids, ignore_missing)
1299
 
 
1300
 
 
1301
 
InterVersionedFile.register_optimiser(InterWeave)