~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: John Arbash Meinel
  • Date: 2008-05-19 21:35:52 UTC
  • mto: This revision was merged to the branch mainline in revision 3441.
  • Revision ID: john@arbash-meinel.com-20080519213552-8jc1yc4w8rqhgzri
switch find_unmerged to use the new function

The api is very compatible, so we don't really need to expose a new function.
So make it hidden, and leave find_unmerged to take out the write lock and call it.

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 sha_strings, split_lines
87
90
import bzrlib.patiencediff
88
 
from bzrlib.revision import NULL_REVISION
89
91
from bzrlib.symbol_versioning import *
90
92
from bzrlib.trace import mutter
 
93
from bzrlib.tsort import topo_sort
91
94
from bzrlib.versionedfile import (
92
95
    AbsentContentFactory,
93
96
    adapter_registry,
94
97
    ContentFactory,
95
 
    sort_groupcompress,
 
98
    InterVersionedFile,
96
99
    VersionedFile,
97
100
    )
98
101
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
107
110
    def __init__(self, version, weave):
108
111
        """Create a WeaveContentFactory for version from weave."""
109
112
        ContentFactory.__init__(self)
110
 
        self.sha1 = weave.get_sha1s([version])[version]
 
113
        self.sha1 = weave.get_sha1s([version])[0]
111
114
        self.key = (version,)
112
115
        parents = weave.get_parent_map([version])[version]
113
116
        self.parents = tuple((parent,) for parent in parents)
116
119
 
117
120
    def get_bytes_as(self, storage_kind):
118
121
        if storage_kind == 'fulltext':
119
 
            return self._weave.get_text(self.key[-1])
120
 
        elif storage_kind == 'chunked':
121
 
            return self._weave.get_lines(self.key[-1])
 
122
            return self._weave.get_text(self.key[0])
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:
309
307
        :return: An iterator of ContentFactory objects, each of which is only
310
308
            valid until the iterator is advanced.
311
309
        """
312
 
        versions = [version[-1] for version in versions]
313
310
        if ordering == 'topological':
314
311
            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)
 
312
            new_versions = topo_sort(parents)
321
313
            new_versions.extend(set(versions).difference(set(parents)))
322
314
            versions = new_versions
323
315
        for version in versions:
330
322
        """See VersionedFile.get_parent_map."""
331
323
        result = {}
332
324
        for version_id in version_ids:
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
 
325
            try:
 
326
                result[version_id] = tuple(
 
327
                    map(self._idx_to_name, self._parents[self._lookup(version_id)]))
 
328
            except RevisionNotPresent:
 
329
                pass
343
330
        return result
344
331
 
345
332
    def get_parents_with_ghosts(self, version_id):
348
335
    def insert_record_stream(self, stream):
349
336
        """Insert a record stream into this versioned file.
350
337
 
351
 
        :param stream: A stream of records to insert.
 
338
        :param stream: A stream of records to insert. 
352
339
        :return: None
353
340
        :seealso VersionedFile.get_record_stream:
354
341
        """
359
346
                raise RevisionNotPresent([record.key[0]], self)
360
347
            # adapt to non-tuple interface
361
348
            parents = [parent[0] for parent in record.parents]
362
 
            if (record.storage_kind == 'fulltext'
363
 
                or record.storage_kind == 'chunked'):
 
349
            if record.storage_kind == 'fulltext':
364
350
                self.add_lines(record.key[0], parents,
365
 
                    osutils.chunks_to_lines(record.get_bytes_as('chunked')))
 
351
                    split_lines(record.get_bytes_as('fulltext')))
366
352
            else:
367
353
                adapter_key = record.storage_kind, 'fulltext'
368
354
                try:
371
357
                    adapter_factory = adapter_registry.get(adapter_key)
372
358
                    adapter = adapter_factory(self)
373
359
                    adapters[adapter_key] = adapter
374
 
                lines = split_lines(adapter.get_bytes(record))
 
360
                lines = split_lines(adapter.get_bytes(
 
361
                    record, record.get_bytes_as(record.storage_kind)))
375
362
                try:
376
363
                    self.add_lines(record.key[0], parents, lines)
377
364
                except RevisionAlreadyPresent:
397
384
 
398
385
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
399
386
        """Add a single text on top of the weave.
400
 
 
 
387
  
401
388
        Returns the index number of the newly added version.
402
389
 
403
390
        version_id
404
391
            Symbolic name for this version.
405
392
            (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
393
 
408
394
        parents
409
395
            List or set of direct parent version numbers.
410
 
 
 
396
            
411
397
        lines
412
398
            Sequence of lines to be added in the new version.
413
399
 
419
405
            sha1 = sha_strings(lines)
420
406
        if sha1 == nostore_sha:
421
407
            raise errors.ExistingContent
422
 
        if version_id is None:
423
 
            version_id = "sha1:" + sha1
424
408
        if version_id in self._name_map:
425
409
            return self._check_repeated_add(version_id, parents, lines, sha1)
426
410
 
437
421
        self._names.append(version_id)
438
422
        self._name_map[version_id] = new_version
439
423
 
440
 
 
 
424
            
441
425
        if not parents:
442
426
            # special case; adding with no parents revision; can do
443
427
            # this more quickly by just appending unconditionally.
454
438
            if sha1 == self._sha1s[pv]:
455
439
                # special case: same as the single parent
456
440
                return new_version
457
 
 
 
441
            
458
442
 
459
443
        ancestors = self._inclusions(parents)
460
444
 
509
493
                # i2; we want to insert after this region to make sure
510
494
                # we don't destroy ourselves
511
495
                i = i2 + offset
512
 
                self._weave[i:i] = ([('{', new_version)]
513
 
                                    + lines[j1:j2]
 
496
                self._weave[i:i] = ([('{', new_version)] 
 
497
                                    + lines[j1:j2] 
514
498
                                    + [('}', None)])
515
499
                offset += 2 + (j2 - j1)
516
500
        return new_version
543
527
            if not isinstance(l, basestring):
544
528
                raise ValueError("text line should be a string or unicode, not %s"
545
529
                                 % type(l))
546
 
 
 
530
        
547
531
 
548
532
 
549
533
    def _check_versions(self, indexes):
557
541
    def _compatible_parents(self, my_parents, other_parents):
558
542
        """During join check that other_parents are joinable with my_parents.
559
543
 
560
 
        Joinable is defined as 'is a subset of' - supersets may require
 
544
        Joinable is defined as 'is a subset of' - supersets may require 
561
545
        regeneration of diffs, but subsets do not.
562
546
        """
563
547
        return len(other_parents.difference(my_parents)) == 0
577
561
            version_ids = self.versions()
578
562
        version_ids = set(version_ids)
579
563
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
580
 
            if inserted not in version_ids: continue
 
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
581
568
            if line[-1] != '\n':
582
569
                yield line + '\n', inserted
583
570
            else:
585
572
 
586
573
    def _walk_internal(self, version_ids=None):
587
574
        """Helper method for weave actions."""
588
 
 
 
575
        
589
576
        istack = []
590
577
        dset = set()
591
578
 
660
647
                # not in either revision
661
648
                yield 'irrelevant', line
662
649
 
 
650
        yield 'unchanged', ''           # terminator
 
651
 
663
652
    def _extract(self, versions):
664
653
        """Yield annotation of lines in included set.
665
654
 
672
661
        for i in versions:
673
662
            if not isinstance(i, int):
674
663
                raise ValueError(i)
675
 
 
 
664
            
676
665
        included = self._inclusions(versions)
677
666
 
678
667
        istack = []
687
676
 
688
677
        WFE = WeaveFormatError
689
678
 
690
 
        # wow.
 
679
        # wow. 
691
680
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
692
681
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
693
682
        # 1.6 seconds in 'isinstance'.
699
688
        # we're still spending ~1/4 of the method in isinstance though.
700
689
        # so lets hard code the acceptable string classes we expect:
701
690
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
702
 
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list'
 
691
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list' 
703
692
        #                                          objects>
704
693
        # yay, down to ~1/4 the initial extract time, and our inline time
705
694
        # has shrunk again, with isinstance no longer dominating.
706
695
        # tweaking the stack inclusion test to use a set gives:
707
696
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
708
 
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list'
 
697
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list' 
709
698
        #                                          objects>
710
699
        # - a 5% win, or possibly just noise. However with large istacks that
711
700
        # 'in' test could dominate, so I'm leaving this change in place -
712
701
        # when its fast enough to consider profiling big datasets we can review.
713
702
 
714
 
 
715
 
 
 
703
              
 
704
             
716
705
 
717
706
        for l in self._weave:
718
707
            if l.__class__ == tuple:
747
736
 
748
737
    def _maybe_lookup(self, name_or_index):
749
738
        """Convert possible symbolic name to index, or pass through indexes.
750
 
 
 
739
        
751
740
        NOT FOR PUBLIC USE.
752
741
        """
753
742
        if isinstance(name_or_index, (int, long)):
763
752
        measured_sha1 = sha_strings(result)
764
753
        if measured_sha1 != expected_sha1:
765
754
            raise errors.WeaveInvalidChecksum(
766
 
                    'file %s, revision %s, expected: %s, measured %s'
 
755
                    'file %s, revision %s, expected: %s, measured %s' 
767
756
                    % (self._weave_name, version_id,
768
757
                       expected_sha1, measured_sha1))
769
758
        return result
770
759
 
771
760
    def get_sha1s(self, version_ids):
772
761
        """See VersionedFile.get_sha1s()."""
773
 
        result = {}
774
 
        for v in version_ids:
775
 
            result[v] = self._sha1s[self._lookup(v)]
776
 
        return result
 
762
        return [self._sha1s[self._lookup(v)] for v in version_ids]
777
763
 
778
764
    def num_versions(self):
779
765
        """How many versions are in this weave?"""
803
789
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
804
790
            # The problem is that set membership is much more expensive
805
791
            name = self._idx_to_name(i)
806
 
            sha1s[name] = sha()
 
792
            sha1s[name] = sha.new()
807
793
            texts[name] = []
808
794
            new_inc = set([name])
809
795
            for p in self._parents[i]:
811
797
 
812
798
            if set(new_inc) != set(self.get_ancestry(name)):
813
799
                raise AssertionError(
814
 
                    'failed %s != %s'
 
800
                    'failed %s != %s' 
815
801
                    % (set(new_inc), set(self.get_ancestry(name))))
816
802
            inclusions[name] = new_inc
817
803
 
848
834
        # no lines outside of insertion blocks, that deletions are
849
835
        # properly paired, etc.
850
836
 
 
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
 
851
890
    def _imported_parents(self, other, other_idx):
852
891
        """Return list of parents in self corresponding to indexes in other."""
853
892
        new_parents = []
855
894
            parent_name = other._names[parent_idx]
856
895
            if parent_name not in self._name_map:
857
896
                # should not be possible
858
 
                raise WeaveError("missing parent {%s} of {%s} in %r"
 
897
                raise WeaveError("missing parent {%s} of {%s} in %r" 
859
898
                                 % (parent_name, other._name_map[other_idx], self))
860
899
            new_parents.append(self._name_map[parent_name])
861
900
        return new_parents
868
907
         * the same text
869
908
         * the same direct parents (by name, not index, and disregarding
870
909
           order)
871
 
 
 
910
        
872
911
        If present & correct return True;
873
 
        if not present in self return False;
 
912
        if not present in self return False; 
874
913
        if inconsistent raise error."""
875
914
        this_idx = self._name_map.get(name, -1)
876
915
        if this_idx != -1:
909
948
    """A WeaveFile represents a Weave on disk and writes on change."""
910
949
 
911
950
    WEAVE_SUFFIX = '.weave'
912
 
 
 
951
    
913
952
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
914
953
        """Create a WeaveFile.
915
 
 
 
954
        
916
955
        :param create: If not True, only open an existing knit.
917
956
        """
918
 
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
919
 
            allow_reserved=False)
 
957
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope)
920
958
        self._transport = transport
921
959
        self._filemode = filemode
922
960
        try:
923
 
            f = self._transport.get(name + WeaveFile.WEAVE_SUFFIX)
924
 
            _read_weave_v5(StringIO(f.read()), self)
 
961
            _read_weave_v5(self._transport.get(name + WeaveFile.WEAVE_SUFFIX), self)
925
962
        except errors.NoSuchFile:
926
963
            if not create:
927
964
                raise
952
989
        sio = StringIO()
953
990
        write_weave_v5(self, sio)
954
991
        sio.seek(0)
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)
 
992
        self._transport.put_file(self._weave_name + WeaveFile.WEAVE_SUFFIX,
 
993
                                 sio,
 
994
                                 self._filemode)
962
995
 
963
996
    @staticmethod
964
997
    def get_suffixes():
969
1002
        super(WeaveFile, self).insert_record_stream(stream)
970
1003
        self._save()
971
1004
 
 
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
 
972
1012
 
973
1013
def _reweave(wa, wb, pb=None, msg=None):
974
1014
    """Combine two weaves and return the result.
975
1015
 
976
 
    This works even if a revision R has different parents in
 
1016
    This works even if a revision R has different parents in 
977
1017
    wa and wb.  In the resulting weave all the parents are given.
978
1018
 
979
 
    This is done by just building up a new weave, maintaining ordering
 
1019
    This is done by just building up a new weave, maintaining ordering 
980
1020
    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
 
1021
    might be possible but it should only be necessary to do 
 
1022
    this operation rarely, when a new previously ghost version is 
983
1023
    inserted.
984
1024
 
985
1025
    :param pb: An optional progress bar, indicating how far done we are
993
1033
    # map from version name -> all parent names
994
1034
    combined_parents = _reweave_parent_graphs(wa, wb)
995
1035
    mutter("combined parents: %r", combined_parents)
996
 
    order = tsort.topo_sort(combined_parents.iteritems())
 
1036
    order = topo_sort(combined_parents.iteritems())
997
1037
    mutter("order to reweave: %r", order)
998
1038
 
999
1039
    if pb and not msg:
1019
1059
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
1020
1060
    return wr
1021
1061
 
1022
 
 
1023
1062
def _reweave_parent_graphs(wa, wb):
1024
1063
    """Return combined parent ancestry for two weaves.
1025
 
 
 
1064
    
1026
1065
    Returned as a list of (version_name, set(parent_names))"""
1027
1066
    combined = {}
1028
1067
    for weave in [wa, wb]:
1030
1069
            p = combined.setdefault(name, set())
1031
1070
            p.update(map(weave._idx_to_name, weave._parents[idx]))
1032
1071
    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)