/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/bzr/weave.py

  • Committer: Jelmer Vernooij
  • Date: 2018-12-18 20:55:37 UTC
  • mfrom: (7223 work)
  • mto: This revision was merged to the branch mainline in revision 7231.
  • Revision ID: jelmer@jelmer.uk-20181218205537-td8qyejigxki0xmn
Merge trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
# Author: Martin Pool <mbp@canonical.com>
18
18
 
19
 
 
20
19
"""Weave - storage of related text file versions"""
21
20
 
 
21
from __future__ import absolute_import
22
22
 
23
23
# XXX: If we do weaves this way, will a merge still behave the same
24
24
# way if it's done in a different order?  That's a pretty desirable
67
67
# FIXME: the conflict markers should be *7* characters
68
68
 
69
69
from copy import copy
70
 
from cStringIO import StringIO
71
70
import os
72
71
 
73
 
from bzrlib.lazy_import import lazy_import
 
72
from ..lazy_import import lazy_import
74
73
lazy_import(globals(), """
75
 
from bzrlib import tsort
 
74
from breezy import tsort
76
75
""")
77
 
from bzrlib import (
 
76
from .. import (
78
77
    errors,
79
78
    osutils,
80
79
    )
81
 
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
82
 
        RevisionAlreadyPresent,
83
 
        RevisionNotPresent,
84
 
        UnavailableRepresentation,
85
 
        )
86
 
from bzrlib.osutils import dirname, sha, sha_strings, split_lines
87
 
import bzrlib.patiencediff
88
 
from bzrlib.revision import NULL_REVISION
89
 
from bzrlib.symbol_versioning import *
90
 
from bzrlib.trace import mutter
91
 
from bzrlib.versionedfile import (
 
80
from ..errors import (
 
81
    RevisionAlreadyPresent,
 
82
    RevisionNotPresent,
 
83
    UnavailableRepresentation,
 
84
    )
 
85
from ..osutils import dirname, sha, sha_strings, split_lines
 
86
from .. import patiencediff
 
87
from ..revision import NULL_REVISION
 
88
from ..sixish import (
 
89
    BytesIO,
 
90
    )
 
91
from ..trace import mutter
 
92
from .versionedfile import (
92
93
    AbsentContentFactory,
93
94
    adapter_registry,
94
95
    ContentFactory,
95
96
    sort_groupcompress,
96
97
    VersionedFile,
97
98
    )
98
 
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
 
99
from .weavefile import _read_weave_v5, write_weave_v5
 
100
 
 
101
 
 
102
class WeaveError(errors.BzrError):
 
103
 
 
104
    _fmt = "Error in processing weave: %(msg)s"
 
105
 
 
106
    def __init__(self, msg=None):
 
107
        errors.BzrError.__init__(self)
 
108
        self.msg = msg
 
109
 
 
110
 
 
111
class WeaveRevisionAlreadyPresent(WeaveError):
 
112
 
 
113
    _fmt = "Revision {%(revision_id)s} already present in %(weave)s"
 
114
 
 
115
    def __init__(self, revision_id, weave):
 
116
 
 
117
        WeaveError.__init__(self)
 
118
        self.revision_id = revision_id
 
119
        self.weave = weave
 
120
 
 
121
 
 
122
class WeaveRevisionNotPresent(WeaveError):
 
123
 
 
124
    _fmt = "Revision {%(revision_id)s} not present in %(weave)s"
 
125
 
 
126
    def __init__(self, revision_id, weave):
 
127
        WeaveError.__init__(self)
 
128
        self.revision_id = revision_id
 
129
        self.weave = weave
 
130
 
 
131
 
 
132
class WeaveFormatError(WeaveError):
 
133
 
 
134
    _fmt = "Weave invariant violated: %(what)s"
 
135
 
 
136
    def __init__(self, what):
 
137
        WeaveError.__init__(self)
 
138
        self.what = what
 
139
 
 
140
 
 
141
class WeaveParentMismatch(WeaveError):
 
142
 
 
143
    _fmt = "Parents are mismatched between two revisions. %(msg)s"
 
144
 
 
145
 
 
146
class WeaveInvalidChecksum(WeaveError):
 
147
 
 
148
    _fmt = "Text did not match its checksum: %(msg)s"
 
149
 
 
150
 
 
151
class WeaveTextDiffers(WeaveError):
 
152
 
 
153
    _fmt = ("Weaves differ on text content. Revision:"
 
154
            " {%(revision_id)s}, %(weave_a)s, %(weave_b)s")
 
155
 
 
156
    def __init__(self, revision_id, weave_a, weave_b):
 
157
        WeaveError.__init__(self)
 
158
        self.revision_id = revision_id
 
159
        self.weave_a = weave_a
 
160
        self.weave_b = weave_b
99
161
 
100
162
 
101
163
class WeaveContentFactory(ContentFactory):
231
293
        self._name_map = {}
232
294
        self._weave_name = weave_name
233
295
        if matcher is None:
234
 
            self._matcher = bzrlib.patiencediff.PatienceSequenceMatcher
 
296
            self._matcher = patiencediff.PatienceSequenceMatcher
235
297
        else:
236
298
            self._matcher = matcher
237
299
        if get_scope is None:
238
 
            get_scope = lambda:None
 
300
            def get_scope():
 
301
                return None
239
302
        self._get_scope = get_scope
240
303
        self._scope = get_scope()
241
304
        self._access_mode = access_mode
268
331
        if not isinstance(other, Weave):
269
332
            return False
270
333
        return self._parents == other._parents \
271
 
               and self._weave == other._weave \
272
 
               and self._sha1s == other._sha1s
 
334
            and self._weave == other._weave \
 
335
            and self._sha1s == other._sha1s
273
336
 
274
337
    def __ne__(self, other):
275
338
        return not self.__eq__(other)
359
422
                raise RevisionNotPresent([record.key[0]], self)
360
423
            # adapt to non-tuple interface
361
424
            parents = [parent[0] for parent in record.parents]
362
 
            if (record.storage_kind == 'fulltext'
363
 
                or record.storage_kind == 'chunked'):
364
 
                self.add_lines(record.key[0], parents,
 
425
            if (record.storage_kind == 'fulltext' or
 
426
                    record.storage_kind == 'chunked'):
 
427
                self.add_lines(
 
428
                    record.key[0], parents,
365
429
                    osutils.chunks_to_lines(record.get_bytes_as('chunked')))
366
430
            else:
367
431
                adapter_key = record.storage_kind, 'fulltext'
384
448
        """
385
449
        idx = self._lookup(name)
386
450
        if sorted(self._parents[idx]) != sorted(parents) \
387
 
            or sha1 != self._sha1s[idx]:
 
451
                or sha1 != self._sha1s[idx]:
388
452
            raise RevisionAlreadyPresent(name, self._weave_name)
389
453
        return idx
390
454
 
391
455
    def _add_lines(self, version_id, parents, lines, parent_texts,
392
 
       left_matching_blocks, nostore_sha, random_id, check_content):
 
456
                   left_matching_blocks, nostore_sha, random_id,
 
457
                   check_content):
393
458
        """See VersionedFile.add_lines."""
394
 
        idx = self._add(version_id, lines, map(self._lookup, parents),
395
 
            nostore_sha=nostore_sha)
 
459
        idx = self._add(version_id, lines, list(map(self._lookup, parents)),
 
460
                        nostore_sha=nostore_sha)
396
461
        return sha_strings(lines), sum(map(len, lines)), idx
397
462
 
398
463
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
420
485
        if sha1 == nostore_sha:
421
486
            raise errors.ExistingContent
422
487
        if version_id is None:
423
 
            version_id = "sha1:" + sha1
 
488
            version_id = b"sha1:" + sha1
424
489
        if version_id in self._name_map:
425
490
            return self._check_repeated_add(version_id, parents, lines, sha1)
426
491
 
427
492
        self._check_versions(parents)
428
 
        ## self._check_lines(lines)
429
493
        new_version = len(self._parents)
430
494
 
431
 
        # if we abort after here the (in-memory) weave will be corrupt because only
432
 
        # some fields are updated
 
495
        # if we abort after here the (in-memory) weave will be corrupt because
 
496
        # only some fields are updated
433
497
        # XXX: FIXME implement a succeed-or-fail of the rest of this routine.
434
498
        #      - Robert Collins 20060226
435
499
        self._parents.append(parents[:])
437
501
        self._names.append(version_id)
438
502
        self._name_map[version_id] = new_version
439
503
 
440
 
 
441
504
        if not parents:
442
505
            # special case; adding with no parents revision; can do
443
506
            # this more quickly by just appending unconditionally.
444
507
            # even more specially, if we're adding an empty text we
445
508
            # need do nothing at all.
446
509
            if lines:
447
 
                self._weave.append(('{', new_version))
 
510
                self._weave.append((b'{', new_version))
448
511
                self._weave.extend(lines)
449
 
                self._weave.append(('}', None))
 
512
                self._weave.append((b'}', None))
450
513
            return new_version
451
514
 
452
515
        if len(parents) == 1:
455
518
                # special case: same as the single parent
456
519
                return new_version
457
520
 
458
 
 
459
521
        ancestors = self._inclusions(parents)
460
522
 
461
523
        l = self._weave
479
541
        # matches the end of the file?  the current code says it's the
480
542
        # last line of the weave?
481
543
 
482
 
        #print 'basis_lines:', basis_lines
483
 
        #print 'new_lines:  ', lines
 
544
        # print 'basis_lines:', basis_lines
 
545
        # print 'new_lines:  ', lines
484
546
 
485
547
        s = self._matcher(None, basis_lines, lines)
486
548
 
487
549
        # offset gives the number of lines that have been inserted
488
 
        # into the weave up to the current point; if the original edit instruction
489
 
        # says to change line A then we actually change (A+offset)
 
550
        # into the weave up to the current point; if the original edit
 
551
        # instruction says to change line A then we actually change (A+offset)
490
552
        offset = 0
491
553
 
492
554
        for tag, i1, i2, j1, j2 in s.get_opcodes():
493
 
            # i1,i2 are given in offsets within basis_lines; we need to map them
494
 
            # back to offsets within the entire weave
495
 
            #print 'raw match', tag, i1, i2, j1, j2
 
555
            # i1,i2 are given in offsets within basis_lines; we need to map
 
556
            # them back to offsets within the entire weave print 'raw match',
 
557
            # tag, i1, i2, j1, j2
496
558
            if tag == 'equal':
497
559
                continue
498
560
            i1 = basis_lineno[i1]
500
562
            # the deletion and insertion are handled separately.
501
563
            # first delete the region.
502
564
            if i1 != i2:
503
 
                self._weave.insert(i1+offset, ('[', new_version))
504
 
                self._weave.insert(i2+offset+1, (']', new_version))
 
565
                self._weave.insert(i1 + offset, (b'[', new_version))
 
566
                self._weave.insert(i2 + offset + 1, (b']', new_version))
505
567
                offset += 2
506
568
 
507
569
            if j1 != j2:
509
571
                # i2; we want to insert after this region to make sure
510
572
                # we don't destroy ourselves
511
573
                i = i2 + offset
512
 
                self._weave[i:i] = ([('{', new_version)]
513
 
                                    + lines[j1:j2]
514
 
                                    + [('}', None)])
 
574
                self._weave[i:i] = ([(b'{', new_version)] +
 
575
                                    lines[j1:j2] +
 
576
                                    [(b'}', None)])
515
577
                offset += 2 + (j2 - j1)
516
578
        return new_version
517
579
 
520
582
        if not len(versions):
521
583
            return []
522
584
        i = set(versions)
523
 
        for v in xrange(max(versions), 0, -1):
 
585
        for v in range(max(versions), 0, -1):
524
586
            if v in i:
525
587
                # include all its parents
526
588
                i.update(self._parents[v])
527
589
        return i
528
 
        ## except IndexError:
529
 
        ##     raise ValueError("version %d not present in weave" % v)
530
590
 
531
591
    def get_ancestry(self, version_ids, topo_sorted=True):
532
592
        """See VersionedFile.get_ancestry."""
533
 
        if isinstance(version_ids, basestring):
 
593
        if isinstance(version_ids, bytes):
534
594
            version_ids = [version_ids]
535
595
        i = self._inclusions([self._lookup(v) for v in version_ids])
536
596
        return [self._idx_to_name(v) for v in i]
537
597
 
538
 
    def _check_lines(self, text):
539
 
        if not isinstance(text, list):
540
 
            raise ValueError("text should be a list, not %s" % type(text))
541
 
 
542
 
        for l in text:
543
 
            if not isinstance(l, basestring):
544
 
                raise ValueError("text line should be a string or unicode, not %s"
545
 
                                 % type(l))
546
 
 
547
 
 
548
 
 
549
598
    def _check_versions(self, indexes):
550
599
        """Check everything in the sequence of indexes is valid"""
551
600
        for i in indexes:
568
617
        The index indicates when the line originated in the weave."""
569
618
        incls = [self._lookup(version_id)]
570
619
        return [(self._idx_to_name(origin), text) for origin, lineno, text in
571
 
            self._extract(incls)]
 
620
                self._extract(incls)]
572
621
 
573
622
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
574
623
                                                pb=None):
576
625
        if version_ids is None:
577
626
            version_ids = self.versions()
578
627
        version_ids = set(version_ids)
579
 
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
580
 
            if inserted not in version_ids: continue
581
 
            if line[-1] != '\n':
582
 
                yield line + '\n', inserted
 
628
        for lineno, inserted, deletes, line in self._walk_internal(
 
629
                version_ids):
 
630
            if inserted not in version_ids:
 
631
                continue
 
632
            if not line.endswith(b'\n'):
 
633
                yield line + b'\n', inserted
583
634
            else:
584
635
                yield line, inserted
585
636
 
594
645
        for l in self._weave:
595
646
            if l.__class__ == tuple:
596
647
                c, v = l
597
 
                isactive = None
598
 
                if c == '{':
 
648
                if c == b'{':
599
649
                    istack.append(self._names[v])
600
 
                elif c == '}':
 
650
                elif c == b'}':
601
651
                    istack.pop()
602
 
                elif c == '[':
 
652
                elif c == b'[':
603
653
                    dset.add(self._names[v])
604
 
                elif c == ']':
 
654
                elif c == b']':
605
655
                    dset.remove(self._names[v])
606
656
                else:
607
657
                    raise WeaveFormatError('unexpected instruction %r' % v)
611
661
 
612
662
        if istack:
613
663
            raise WeaveFormatError("unclosed insertion blocks "
614
 
                    "at end of weave: %s" % istack)
 
664
                                   "at end of weave: %s" % istack)
615
665
        if dset:
616
 
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
617
 
                                   % dset)
 
666
            raise WeaveFormatError(
 
667
                "unclosed deletion blocks at end of weave: %s" % dset)
618
668
 
619
669
    def plan_merge(self, ver_a, ver_b):
620
670
        """Return pseudo-annotation indicating how the two versions merge.
628
678
        inc_b = set(self.get_ancestry([ver_b]))
629
679
        inc_c = inc_a & inc_b
630
680
 
631
 
        for lineno, insert, deleteset, line in self._walk_internal([ver_a, ver_b]):
 
681
        for lineno, insert, deleteset, line in self._walk_internal(
 
682
                [ver_a, ver_b]):
632
683
            if deleteset & inc_c:
633
684
                # killed in parent; can't be in either a or b
634
685
                # not relevant to our work
685
736
 
686
737
        result = []
687
738
 
688
 
        WFE = WeaveFormatError
689
 
 
690
739
        # wow.
691
 
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
 
740
        #  449       0   4474.6820   2356.5590   breezy.weave:556(_extract)
692
741
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
693
742
        # 1.6 seconds in 'isinstance'.
694
743
        # changing the first isinstance:
695
 
        #  449       0   2814.2660   1577.1760   bzrlib.weave:556(_extract)
 
744
        #  449       0   2814.2660   1577.1760   breezy.weave:556(_extract)
696
745
        #  +140414   0    762.8050    762.8050   +<isinstance>
697
746
        # note that the inline time actually dropped (less function calls)
698
747
        # and total processing time was halved.
699
748
        # we're still spending ~1/4 of the method in isinstance though.
700
749
        # so lets hard code the acceptable string classes we expect:
701
 
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
 
750
        #  449       0   1202.9420    786.2930   breezy.weave:556(_extract)
702
751
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list'
703
752
        #                                          objects>
704
753
        # yay, down to ~1/4 the initial extract time, and our inline time
705
754
        # has shrunk again, with isinstance no longer dominating.
706
755
        # tweaking the stack inclusion test to use a set gives:
707
 
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
 
756
        #  449       0   1122.8030    713.0080   breezy.weave:556(_extract)
708
757
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list'
709
758
        #                                          objects>
710
759
        # - a 5% win, or possibly just noise. However with large istacks that
711
 
        # 'in' test could dominate, so I'm leaving this change in place -
712
 
        # when its fast enough to consider profiling big datasets we can review.
713
 
 
714
 
 
715
 
 
 
760
        # 'in' test could dominate, so I'm leaving this change in place - when
 
761
        # its fast enough to consider profiling big datasets we can review.
716
762
 
717
763
        for l in self._weave:
718
764
            if l.__class__ == tuple:
719
765
                c, v = l
720
766
                isactive = None
721
 
                if c == '{':
 
767
                if c == b'{':
722
768
                    istack.append(v)
723
769
                    iset.add(v)
724
 
                elif c == '}':
 
770
                elif c == b'}':
725
771
                    iset.remove(istack.pop())
726
 
                elif c == '[':
 
772
                elif c == b'[':
727
773
                    if v in included:
728
774
                        dset.add(v)
729
 
                elif c == ']':
 
775
                elif c == b']':
730
776
                    if v in included:
731
777
                        dset.remove(v)
732
778
                else:
733
779
                    raise AssertionError()
734
780
            else:
735
781
                if isactive is None:
736
 
                    isactive = (not dset) and istack and (istack[-1] in included)
 
782
                    isactive = (not dset) and istack and (
 
783
                        istack[-1] in included)
737
784
                if isactive:
738
785
                    result.append((istack[-1], lineno, l))
739
786
            lineno += 1
740
787
        if istack:
741
788
            raise WeaveFormatError("unclosed insertion blocks "
742
 
                    "at end of weave: %s" % istack)
 
789
                                   "at end of weave: %s" % istack)
743
790
        if dset:
744
 
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
745
 
                                   % dset)
 
791
            raise WeaveFormatError(
 
792
                "unclosed deletion blocks at end of weave: %s" % dset)
746
793
        return result
747
794
 
748
795
    def _maybe_lookup(self, name_or_index):
750
797
 
751
798
        NOT FOR PUBLIC USE.
752
799
        """
753
 
        if isinstance(name_or_index, (int, long)):
 
800
        # GZ 2017-04-01: This used to check for long as well, but I don't think
 
801
        # there are python implementations with sys.maxsize > sys.maxint
 
802
        if isinstance(name_or_index, int):
754
803
            return name_or_index
755
804
        else:
756
805
            return self._lookup(name_or_index)
758
807
    def get_lines(self, version_id):
759
808
        """See VersionedFile.get_lines()."""
760
809
        int_index = self._maybe_lookup(version_id)
761
 
        result = [line for (origin, lineno, line) in self._extract([int_index])]
 
810
        result = [line for (origin, lineno, line)
 
811
                  in self._extract([int_index])]
762
812
        expected_sha1 = self._sha1s[int_index]
763
813
        measured_sha1 = sha_strings(result)
764
814
        if measured_sha1 != expected_sha1:
765
 
            raise errors.WeaveInvalidChecksum(
766
 
                    'file %s, revision %s, expected: %s, measured %s'
767
 
                    % (self._weave_name, version_id,
768
 
                       expected_sha1, measured_sha1))
 
815
            raise WeaveInvalidChecksum(
 
816
                'file %s, revision %s, expected: %s, measured %s'
 
817
                % (self._weave_name, version_id,
 
818
                   expected_sha1, measured_sha1))
769
819
        return result
770
820
 
771
821
    def get_sha1s(self, version_ids):
777
827
 
778
828
    def num_versions(self):
779
829
        """How many versions are in this weave?"""
780
 
        l = len(self._parents)
781
 
        return l
 
830
        return len(self._parents)
782
831
 
783
832
    __len__ = num_versions
784
833
 
791
840
            if inclusions:
792
841
                inclusions.sort()
793
842
                if inclusions[-1] >= version:
794
 
                    raise WeaveFormatError("invalid included version %d for index %d"
795
 
                                           % (inclusions[-1], version))
 
843
                    raise WeaveFormatError(
 
844
                        "invalid included version %d for index %d"
 
845
                        % (inclusions[-1], version))
796
846
 
797
847
        # try extracting all versions; parallel extraction is used
798
848
        nv = self.num_versions()
805
855
            name = self._idx_to_name(i)
806
856
            sha1s[name] = sha()
807
857
            texts[name] = []
808
 
            new_inc = set([name])
 
858
            new_inc = {name}
809
859
            for p in self._parents[i]:
810
860
                new_inc.update(inclusions[self._idx_to_name(p)])
811
861
 
831
881
                # The active inclusion must be an ancestor,
832
882
                # and no ancestors must have deleted this line,
833
883
                # because we don't support resurrection.
834
 
                if (insert in name_inclusions) and not (deleteset & name_inclusions):
 
884
                if ((insert in name_inclusions) and
 
885
                        not (deleteset & name_inclusions)):
835
886
                    sha1s[name].update(line)
836
887
 
837
888
        for i in range(nv):
838
889
            version = self._idx_to_name(i)
839
 
            hd = sha1s[version].hexdigest()
 
890
            hd = sha1s[version].hexdigest().encode()
840
891
            expected = self._sha1s[i]
841
892
            if hd != expected:
842
 
                raise errors.WeaveInvalidChecksum(
843
 
                        "mismatched sha1 for version %s: "
844
 
                        "got %s, expected %s"
845
 
                        % (version, hd, expected))
 
893
                raise WeaveInvalidChecksum(
 
894
                    "mismatched sha1 for version %s: "
 
895
                    "got %s, expected %s"
 
896
                    % (version, hd, expected))
846
897
 
847
898
        # TODO: check insertions are properly nested, that there are
848
899
        # no lines outside of insertion blocks, that deletions are
875
926
        this_idx = self._name_map.get(name, -1)
876
927
        if this_idx != -1:
877
928
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
878
 
                raise errors.WeaveTextDiffers(name, self, other)
 
929
                raise WeaveTextDiffers(name, self, other)
879
930
            self_parents = self._parents[this_idx]
880
931
            other_parents = other._parents[other_idx]
881
 
            n1 = set([self._names[i] for i in self_parents])
882
 
            n2 = set([other._names[i] for i in other_parents])
 
932
            n1 = {self._names[i] for i in self_parents}
 
933
            n2 = {other._names[i] for i in other_parents}
883
934
            if not self._compatible_parents(n1, n2):
884
 
                raise WeaveParentMismatch("inconsistent parents "
 
935
                raise WeaveParentMismatch(
 
936
                    "inconsistent parents "
885
937
                    "for version {%s}: %s vs %s" % (name, n1, n2))
886
938
            else:
887
939
                return True         # ok!
910
962
 
911
963
    WEAVE_SUFFIX = '.weave'
912
964
 
913
 
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
 
965
    def __init__(self, name, transport, filemode=None, create=False,
 
966
                 access_mode='w', get_scope=None):
914
967
        """Create a WeaveFile.
915
968
 
916
969
        :param create: If not True, only open an existing knit.
917
970
        """
918
971
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
919
 
            allow_reserved=False)
 
972
                                        allow_reserved=False)
920
973
        self._transport = transport
921
974
        self._filemode = filemode
922
975
        try:
923
 
            _read_weave_v5(self._transport.get(name + WeaveFile.WEAVE_SUFFIX), self)
 
976
            f = self._transport.get(name + WeaveFile.WEAVE_SUFFIX)
 
977
            _read_weave_v5(BytesIO(f.read()), self)
924
978
        except errors.NoSuchFile:
925
979
            if not create:
926
980
                raise
928
982
            self._save()
929
983
 
930
984
    def _add_lines(self, version_id, parents, lines, parent_texts,
931
 
        left_matching_blocks, nostore_sha, random_id, check_content):
 
985
                   left_matching_blocks, nostore_sha, random_id,
 
986
                   check_content):
932
987
        """Add a version and save the weave."""
933
988
        self.check_not_reserved_id(version_id)
934
 
        result = super(WeaveFile, self)._add_lines(version_id, parents, lines,
935
 
            parent_texts, left_matching_blocks, nostore_sha, random_id,
936
 
            check_content)
 
989
        result = super(WeaveFile, self)._add_lines(
 
990
            version_id, parents, lines, parent_texts, left_matching_blocks,
 
991
            nostore_sha, random_id, check_content)
937
992
        self._save()
938
993
        return result
939
994
 
940
995
    def copy_to(self, name, transport):
941
996
        """See VersionedFile.copy_to()."""
942
997
        # as we are all in memory always, just serialise to the new place.
943
 
        sio = StringIO()
 
998
        sio = BytesIO()
944
999
        write_weave_v5(self, sio)
945
1000
        sio.seek(0)
946
1001
        transport.put_file(name + WeaveFile.WEAVE_SUFFIX, sio, self._filemode)
948
1003
    def _save(self):
949
1004
        """Save the weave."""
950
1005
        self._check_write_ok()
951
 
        sio = StringIO()
 
1006
        sio = BytesIO()
952
1007
        write_weave_v5(self, sio)
953
1008
        sio.seek(0)
954
1009
        bytes = sio.getvalue()
985
1040
    :param msg: An optional message for the progress
986
1041
    """
987
1042
    wr = Weave()
988
 
    ia = ib = 0
989
 
    queue_a = range(wa.num_versions())
990
 
    queue_b = range(wb.num_versions())
991
1043
    # first determine combined parents of all versions
992
1044
    # map from version name -> all parent names
993
1045
    combined_parents = _reweave_parent_graphs(wa, wb)
994
1046
    mutter("combined parents: %r", combined_parents)
995
 
    order = tsort.topo_sort(combined_parents.iteritems())
 
1047
    order = tsort.topo_sort(combined_parents.items())
996
1048
    mutter("order to reweave: %r", order)
997
1049
 
998
1050
    if pb and not msg:
1010
1062
                    mutter('weaves: %s, %s', wa._weave_name, wb._weave_name)
1011
1063
                    import difflib
1012
1064
                    lines = list(difflib.unified_diff(lines, lines_b,
1013
 
                            wa._weave_name, wb._weave_name))
 
1065
                                                      wa._weave_name, wb._weave_name))
1014
1066
                    mutter('lines:\n%s', ''.join(lines))
1015
 
                    raise errors.WeaveTextDiffers(name, wa, wb)
 
1067
                    raise WeaveTextDiffers(name, wa, wb)
1016
1068
        else:
1017
1069
            lines = wb.get_lines(name)
1018
1070
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])