/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 bzrlib/weave.py

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/python
2
 
 
3
 
# Copyright (C) 2005 Canonical Ltd
 
1
# Copyright (C) 2005, 2009 Canonical Ltd
4
2
#
5
3
# This program is free software; you can redistribute it and/or modify
6
4
# it under the terms of the GNU General Public License as published by
14
12
#
15
13
# You should have received a copy of the GNU General Public License
16
14
# along with this program; if not, write to the Free Software
17
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
16
 
19
17
# Author: Martin Pool <mbp@canonical.com>
20
18
 
61
59
# where the basis and destination are unchanged.
62
60
 
63
61
# FIXME: Sometimes we will be given a parents list for a revision
64
 
# that includes some redundant parents (i.e. already a parent of 
65
 
# something in the list.)  We should eliminate them.  This can 
 
62
# that includes some redundant parents (i.e. already a parent of
 
63
# something in the list.)  We should eliminate them.  This can
66
64
# be done fairly efficiently because the sequence numbers constrain
67
65
# the possible relationships.
68
66
 
71
69
from copy import copy
72
70
from cStringIO import StringIO
73
71
import os
74
 
import sha
75
 
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
 
from bzrlib.trace import mutter
82
81
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
83
82
        RevisionAlreadyPresent,
84
83
        RevisionNotPresent,
85
 
        WeaveRevisionAlreadyPresent,
86
 
        WeaveRevisionNotPresent,
 
84
        UnavailableRepresentation,
87
85
        )
88
 
import bzrlib.errors as errors
89
 
from bzrlib.osutils import sha_strings
 
86
from bzrlib.osutils import dirname, sha, sha_strings, split_lines
90
87
import bzrlib.patiencediff
91
 
from bzrlib.tsort import topo_sort
92
 
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
 
88
from bzrlib.revision import NULL_REVISION
 
89
from bzrlib.symbol_versioning import *
 
90
from bzrlib.trace import mutter
 
91
from bzrlib.versionedfile import (
 
92
    AbsentContentFactory,
 
93
    adapter_registry,
 
94
    ContentFactory,
 
95
    sort_groupcompress,
 
96
    VersionedFile,
 
97
    )
93
98
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
94
99
 
95
100
 
 
101
class WeaveContentFactory(ContentFactory):
 
102
    """Content factory for streaming from weaves.
 
103
 
 
104
    :seealso ContentFactory:
 
105
    """
 
106
 
 
107
    def __init__(self, version, weave):
 
108
        """Create a WeaveContentFactory for version from weave."""
 
109
        ContentFactory.__init__(self)
 
110
        self.sha1 = weave.get_sha1s([version])[version]
 
111
        self.key = (version,)
 
112
        parents = weave.get_parent_map([version])[version]
 
113
        self.parents = tuple((parent,) for parent in parents)
 
114
        self.storage_kind = 'fulltext'
 
115
        self._weave = weave
 
116
 
 
117
    def get_bytes_as(self, storage_kind):
 
118
        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
        else:
 
123
            raise UnavailableRepresentation(self.key, storage_kind, 'fulltext')
 
124
 
 
125
 
96
126
class Weave(VersionedFile):
97
127
    """weave - versioned text file storage.
98
 
    
 
128
 
99
129
    A Weave manages versions of line-based text files, keeping track
100
130
    of the originating version for each line.
101
131
 
147
177
 
148
178
    * It doesn't seem very useful to have an active insertion
149
179
      inside an inactive insertion, but it might happen.
150
 
      
 
180
 
151
181
    * Therefore, all instructions are always"considered"; that
152
182
      is passed onto and off the stack.  An outer inactive block
153
183
      doesn't disable an inner block.
183
213
    """
184
214
 
185
215
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
186
 
                 '_weave_name', '_matcher']
187
 
    
188
 
    def __init__(self, weave_name=None, access_mode='w', matcher=None):
189
 
        super(Weave, self).__init__(access_mode)
 
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
        """Create a weave.
 
221
 
 
222
        :param get_scope: A callable that returns an opaque object to be used
 
223
            for detecting when this weave goes out of scope (should stop
 
224
            answering requests or allowing mutation).
 
225
        """
 
226
        super(Weave, self).__init__()
190
227
        self._weave = []
191
228
        self._parents = []
192
229
        self._sha1s = []
197
234
            self._matcher = bzrlib.patiencediff.PatienceSequenceMatcher
198
235
        else:
199
236
            self._matcher = matcher
 
237
        if get_scope is None:
 
238
            get_scope = lambda:None
 
239
        self._get_scope = get_scope
 
240
        self._scope = get_scope()
 
241
        self._access_mode = access_mode
 
242
        self._allow_reserved = allow_reserved
200
243
 
201
244
    def __repr__(self):
202
245
        return "Weave(%r)" % self._weave_name
203
246
 
 
247
    def _check_write_ok(self):
 
248
        """Is the versioned file marked as 'finished' ? Raise if it is."""
 
249
        if self._get_scope() != self._scope:
 
250
            raise errors.OutSideTransaction()
 
251
        if self._access_mode != 'w':
 
252
            raise errors.ReadOnlyObjectDirtiedError(self)
 
253
 
204
254
    def copy(self):
205
255
        """Return a deep copy of self.
206
 
        
 
256
 
207
257
        The copy can be modified without affecting the original weave."""
208
258
        other = Weave()
209
259
        other._weave = self._weave[:]
219
269
            return False
220
270
        return self._parents == other._parents \
221
271
               and self._weave == other._weave \
222
 
               and self._sha1s == other._sha1s 
223
 
    
 
272
               and self._sha1s == other._sha1s
 
273
 
224
274
    def __ne__(self, other):
225
275
        return not self.__eq__(other)
226
276
 
229
279
 
230
280
    def _lookup(self, name):
231
281
        """Convert symbolic version name to index."""
232
 
        self.check_not_reserved_id(name)
 
282
        if not self._allow_reserved:
 
283
            self.check_not_reserved_id(name)
233
284
        try:
234
285
            return self._name_map[name]
235
286
        except KeyError:
245
296
 
246
297
    __contains__ = has_version
247
298
 
 
299
    def get_record_stream(self, versions, ordering, include_delta_closure):
 
300
        """Get a stream of records for versions.
 
301
 
 
302
        :param versions: The versions to include. Each version is a tuple
 
303
            (version,).
 
304
        :param ordering: Either 'unordered' or 'topological'. A topologically
 
305
            sorted stream has compression parents strictly before their
 
306
            children.
 
307
        :param include_delta_closure: If True then the closure across any
 
308
            compression parents will be included (in the opaque data).
 
309
        :return: An iterator of ContentFactory objects, each of which is only
 
310
            valid until the iterator is advanced.
 
311
        """
 
312
        versions = [version[-1] for version in versions]
 
313
        if ordering == 'topological':
 
314
            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)
 
321
            new_versions.extend(set(versions).difference(set(parents)))
 
322
            versions = new_versions
 
323
        for version in versions:
 
324
            if version in self:
 
325
                yield WeaveContentFactory(version, self)
 
326
            else:
 
327
                yield AbsentContentFactory((version,))
 
328
 
248
329
    def get_parent_map(self, version_ids):
249
330
        """See VersionedFile.get_parent_map."""
250
331
        result = {}
251
332
        for version_id in version_ids:
252
 
            try:
253
 
                result[version_id] = tuple(
254
 
                    map(self._idx_to_name, self._parents[self._lookup(version_id)]))
255
 
            except RevisionNotPresent:
256
 
                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
257
343
        return result
258
344
 
259
345
    def get_parents_with_ghosts(self, version_id):
260
346
        raise NotImplementedError(self.get_parents_with_ghosts)
261
347
 
 
348
    def insert_record_stream(self, stream):
 
349
        """Insert a record stream into this versioned file.
 
350
 
 
351
        :param stream: A stream of records to insert.
 
352
        :return: None
 
353
        :seealso VersionedFile.get_record_stream:
 
354
        """
 
355
        adapters = {}
 
356
        for record in stream:
 
357
            # Raise an error when a record is missing.
 
358
            if record.storage_kind == 'absent':
 
359
                raise RevisionNotPresent([record.key[0]], self)
 
360
            # adapt to non-tuple interface
 
361
            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,
 
365
                    osutils.chunks_to_lines(record.get_bytes_as('chunked')))
 
366
            else:
 
367
                adapter_key = record.storage_kind, 'fulltext'
 
368
                try:
 
369
                    adapter = adapters[adapter_key]
 
370
                except KeyError:
 
371
                    adapter_factory = adapter_registry.get(adapter_key)
 
372
                    adapter = adapter_factory(self)
 
373
                    adapters[adapter_key] = adapter
 
374
                lines = split_lines(adapter.get_bytes(record))
 
375
                try:
 
376
                    self.add_lines(record.key[0], parents, lines)
 
377
                except RevisionAlreadyPresent:
 
378
                    pass
 
379
 
262
380
    def _check_repeated_add(self, name, parents, text, sha1):
263
381
        """Check that a duplicated add is OK.
264
382
 
279
397
 
280
398
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
281
399
        """Add a single text on top of the weave.
282
 
  
 
400
 
283
401
        Returns the index number of the newly added version.
284
402
 
285
403
        version_id
286
404
            Symbolic name for this version.
287
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)
288
407
 
289
408
        parents
290
409
            List or set of direct parent version numbers.
291
 
            
 
410
 
292
411
        lines
293
412
            Sequence of lines to be added in the new version.
294
413
 
295
414
        :param nostore_sha: See VersionedFile.add_lines.
296
415
        """
297
 
        assert isinstance(version_id, basestring)
298
416
        self._check_lines_not_unicode(lines)
299
417
        self._check_lines_are_lines(lines)
300
418
        if not sha1:
301
419
            sha1 = sha_strings(lines)
302
420
        if sha1 == nostore_sha:
303
421
            raise errors.ExistingContent
 
422
        if version_id is None:
 
423
            version_id = "sha1:" + sha1
304
424
        if version_id in self._name_map:
305
425
            return self._check_repeated_add(version_id, parents, lines, sha1)
306
426
 
317
437
        self._names.append(version_id)
318
438
        self._name_map[version_id] = new_version
319
439
 
320
 
            
 
440
 
321
441
        if not parents:
322
442
            # special case; adding with no parents revision; can do
323
443
            # this more quickly by just appending unconditionally.
334
454
            if sha1 == self._sha1s[pv]:
335
455
                # special case: same as the single parent
336
456
                return new_version
337
 
            
 
457
 
338
458
 
339
459
        ancestors = self._inclusions(parents)
340
460
 
375
495
            #print 'raw match', tag, i1, i2, j1, j2
376
496
            if tag == 'equal':
377
497
                continue
378
 
 
379
498
            i1 = basis_lineno[i1]
380
499
            i2 = basis_lineno[i2]
381
 
 
382
 
            assert 0 <= j1 <= j2 <= len(lines)
383
 
 
384
 
            #print tag, i1, i2, j1, j2
385
 
 
386
500
            # the deletion and insertion are handled separately.
387
501
            # first delete the region.
388
502
            if i1 != i2:
395
509
                # i2; we want to insert after this region to make sure
396
510
                # we don't destroy ourselves
397
511
                i = i2 + offset
398
 
                self._weave[i:i] = ([('{', new_version)] 
399
 
                                    + lines[j1:j2] 
 
512
                self._weave[i:i] = ([('{', new_version)]
 
513
                                    + lines[j1:j2]
400
514
                                    + [('}', None)])
401
515
                offset += 2 + (j2 - j1)
402
516
        return new_version
403
517
 
404
 
    def _clone_text(self, new_version_id, old_version_id, parents):
405
 
        """See VersionedFile.clone_text."""
406
 
        old_lines = self.get_text(old_version_id)
407
 
        self.add_lines(new_version_id, parents, old_lines)
408
 
 
409
518
    def _inclusions(self, versions):
410
519
        """Return set of all ancestors of given version(s)."""
411
520
        if not len(versions):
434
543
            if not isinstance(l, basestring):
435
544
                raise ValueError("text line should be a string or unicode, not %s"
436
545
                                 % type(l))
437
 
        
 
546
 
438
547
 
439
548
 
440
549
    def _check_versions(self, indexes):
448
557
    def _compatible_parents(self, my_parents, other_parents):
449
558
        """During join check that other_parents are joinable with my_parents.
450
559
 
451
 
        Joinable is defined as 'is a subset of' - supersets may require 
 
560
        Joinable is defined as 'is a subset of' - supersets may require
452
561
        regeneration of diffs, but subsets do not.
453
562
        """
454
563
        return len(other_parents.difference(my_parents)) == 0
455
564
 
456
 
    def annotate_iter(self, version_id):
457
 
        """Yield list of (version-id, line) pairs for the specified version.
 
565
    def annotate(self, version_id):
 
566
        """Return a list of (version-id, line) tuples for version_id.
458
567
 
459
568
        The index indicates when the line originated in the weave."""
460
569
        incls = [self._lookup(version_id)]
461
 
        for origin, lineno, text in self._extract(incls):
462
 
            yield self._idx_to_name(origin), text
 
570
        return [(self._idx_to_name(origin), text) for origin, lineno, text in
 
571
            self._extract(incls)]
463
572
 
464
573
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
465
574
                                                pb=None):
468
577
            version_ids = self.versions()
469
578
        version_ids = set(version_ids)
470
579
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
471
 
            # if inserted not in version_ids then it was inserted before the
472
 
            # versions we care about, but because weaves cannot represent ghosts
473
 
            # properly, we do not filter down to that
474
 
            # if inserted not in version_ids: continue
 
580
            if inserted not in version_ids: continue
475
581
            if line[-1] != '\n':
476
582
                yield line + '\n', inserted
477
583
            else:
479
585
 
480
586
    def _walk_internal(self, version_ids=None):
481
587
        """Helper method for weave actions."""
482
 
        
 
588
 
483
589
        istack = []
484
590
        dset = set()
485
591
 
494
600
                elif c == '}':
495
601
                    istack.pop()
496
602
                elif c == '[':
497
 
                    assert self._names[v] not in dset
498
603
                    dset.add(self._names[v])
499
604
                elif c == ']':
500
605
                    dset.remove(self._names[v])
501
606
                else:
502
607
                    raise WeaveFormatError('unexpected instruction %r' % v)
503
608
            else:
504
 
                assert l.__class__ in (str, unicode)
505
 
                assert istack
506
609
                yield lineno, istack[-1], frozenset(dset), l
507
610
            lineno += 1
508
611
 
557
660
                # not in either revision
558
661
                yield 'irrelevant', line
559
662
 
560
 
        yield 'unchanged', ''           # terminator
561
 
 
562
663
    def _extract(self, versions):
563
664
        """Yield annotation of lines in included set.
564
665
 
571
672
        for i in versions:
572
673
            if not isinstance(i, int):
573
674
                raise ValueError(i)
574
 
            
 
675
 
575
676
        included = self._inclusions(versions)
576
677
 
577
678
        istack = []
586
687
 
587
688
        WFE = WeaveFormatError
588
689
 
589
 
        # wow. 
 
690
        # wow.
590
691
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
591
692
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
592
693
        # 1.6 seconds in 'isinstance'.
598
699
        # we're still spending ~1/4 of the method in isinstance though.
599
700
        # so lets hard code the acceptable string classes we expect:
600
701
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
601
 
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list' 
 
702
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list'
602
703
        #                                          objects>
603
704
        # yay, down to ~1/4 the initial extract time, and our inline time
604
705
        # has shrunk again, with isinstance no longer dominating.
605
706
        # tweaking the stack inclusion test to use a set gives:
606
707
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
607
 
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list' 
 
708
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list'
608
709
        #                                          objects>
609
710
        # - a 5% win, or possibly just noise. However with large istacks that
610
711
        # 'in' test could dominate, so I'm leaving this change in place -
611
712
        # when its fast enough to consider profiling big datasets we can review.
612
713
 
613
 
              
614
 
             
 
714
 
 
715
 
615
716
 
616
717
        for l in self._weave:
617
718
            if l.__class__ == tuple:
618
719
                c, v = l
619
720
                isactive = None
620
721
                if c == '{':
621
 
                    assert v not in iset
622
722
                    istack.append(v)
623
723
                    iset.add(v)
624
724
                elif c == '}':
625
725
                    iset.remove(istack.pop())
626
726
                elif c == '[':
627
727
                    if v in included:
628
 
                        assert v not in dset
629
728
                        dset.add(v)
630
 
                else:
631
 
                    assert c == ']'
 
729
                elif c == ']':
632
730
                    if v in included:
633
 
                        assert v in dset
634
731
                        dset.remove(v)
 
732
                else:
 
733
                    raise AssertionError()
635
734
            else:
636
 
                assert l.__class__ in (str, unicode)
637
735
                if isactive is None:
638
736
                    isactive = (not dset) and istack and (istack[-1] in included)
639
737
                if isactive:
649
747
 
650
748
    def _maybe_lookup(self, name_or_index):
651
749
        """Convert possible symbolic name to index, or pass through indexes.
652
 
        
 
750
 
653
751
        NOT FOR PUBLIC USE.
654
752
        """
655
753
        if isinstance(name_or_index, (int, long)):
665
763
        measured_sha1 = sha_strings(result)
666
764
        if measured_sha1 != expected_sha1:
667
765
            raise errors.WeaveInvalidChecksum(
668
 
                    'file %s, revision %s, expected: %s, measured %s' 
 
766
                    'file %s, revision %s, expected: %s, measured %s'
669
767
                    % (self._weave_name, version_id,
670
768
                       expected_sha1, measured_sha1))
671
769
        return result
672
770
 
673
 
    def get_sha1(self, version_id):
674
 
        """See VersionedFile.get_sha1()."""
675
 
        return self._sha1s[self._lookup(version_id)]
676
 
 
677
771
    def get_sha1s(self, version_ids):
678
772
        """See VersionedFile.get_sha1s()."""
679
 
        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
680
777
 
681
778
    def num_versions(self):
682
779
        """How many versions are in this weave?"""
683
780
        l = len(self._parents)
684
 
        assert l == len(self._sha1s)
685
781
        return l
686
782
 
687
783
    __len__ = num_versions
707
803
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
708
804
            # The problem is that set membership is much more expensive
709
805
            name = self._idx_to_name(i)
710
 
            sha1s[name] = sha.new()
 
806
            sha1s[name] = sha()
711
807
            texts[name] = []
712
808
            new_inc = set([name])
713
809
            for p in self._parents[i]:
714
810
                new_inc.update(inclusions[self._idx_to_name(p)])
715
811
 
716
 
            assert set(new_inc) == set(self.get_ancestry(name)), \
717
 
                'failed %s != %s' % (set(new_inc), set(self.get_ancestry(name)))
 
812
            if set(new_inc) != set(self.get_ancestry(name)):
 
813
                raise AssertionError(
 
814
                    'failed %s != %s'
 
815
                    % (set(new_inc), set(self.get_ancestry(name))))
718
816
            inclusions[name] = new_inc
719
817
 
720
818
        nlines = len(self._weave)
750
848
        # no lines outside of insertion blocks, that deletions are
751
849
        # properly paired, etc.
752
850
 
753
 
    def _join(self, other, pb, msg, version_ids, ignore_missing):
754
 
        """Worker routine for join()."""
755
 
        if not other.versions():
756
 
            return          # nothing to update, easy
757
 
 
758
 
        if not version_ids:
759
 
            # versions is never none, InterWeave checks this.
760
 
            return 0
761
 
 
762
 
        # two loops so that we do not change ourselves before verifying it
763
 
        # will be ok
764
 
        # work through in index order to make sure we get all dependencies
765
 
        names_to_join = []
766
 
        processed = 0
767
 
        # get the selected versions only that are in other.versions.
768
 
        version_ids = set(other.versions()).intersection(set(version_ids))
769
 
        # pull in the referenced graph.
770
 
        version_ids = other.get_ancestry(version_ids)
771
 
        pending_parents = other.get_parent_map(version_ids)
772
 
        pending_graph = pending_parents.items()
773
 
        if len(pending_graph) != len(version_ids):
774
 
            raise RevisionNotPresent(
775
 
                set(version_ids) - set(pending_parents.keys()), self)
776
 
        for name in topo_sort(pending_graph):
777
 
            other_idx = other._name_map[name]
778
 
            # returns True if we have it, False if we need it.
779
 
            if not self._check_version_consistent(other, other_idx, name):
780
 
                names_to_join.append((other_idx, name))
781
 
            processed += 1
782
 
 
783
 
        if pb and not msg:
784
 
            msg = 'weave join'
785
 
 
786
 
        merged = 0
787
 
        time0 = time.time()
788
 
        for other_idx, name in names_to_join:
789
 
            # TODO: If all the parents of the other version are already
790
 
            # present then we can avoid some work by just taking the delta
791
 
            # and adjusting the offsets.
792
 
            new_parents = self._imported_parents(other, other_idx)
793
 
            sha1 = other._sha1s[other_idx]
794
 
 
795
 
            merged += 1
796
 
 
797
 
            if pb:
798
 
                pb.update(msg, merged, len(names_to_join))
799
 
           
800
 
            lines = other.get_lines(other_idx)
801
 
            self._add(name, lines, new_parents, sha1)
802
 
 
803
 
        mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
804
 
                merged, processed, self._weave_name, time.time()-time0))
805
 
 
806
851
    def _imported_parents(self, other, other_idx):
807
852
        """Return list of parents in self corresponding to indexes in other."""
808
853
        new_parents = []
810
855
            parent_name = other._names[parent_idx]
811
856
            if parent_name not in self._name_map:
812
857
                # should not be possible
813
 
                raise WeaveError("missing parent {%s} of {%s} in %r" 
 
858
                raise WeaveError("missing parent {%s} of {%s} in %r"
814
859
                                 % (parent_name, other._name_map[other_idx], self))
815
860
            new_parents.append(self._name_map[parent_name])
816
861
        return new_parents
823
868
         * the same text
824
869
         * the same direct parents (by name, not index, and disregarding
825
870
           order)
826
 
        
 
871
 
827
872
        If present & correct return True;
828
 
        if not present in self return False; 
 
873
        if not present in self return False;
829
874
        if inconsistent raise error."""
830
875
        this_idx = self._name_map.get(name, -1)
831
876
        if this_idx != -1:
864
909
    """A WeaveFile represents a Weave on disk and writes on change."""
865
910
 
866
911
    WEAVE_SUFFIX = '.weave'
867
 
    
868
 
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w'):
 
912
 
 
913
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
869
914
        """Create a WeaveFile.
870
 
        
 
915
 
871
916
        :param create: If not True, only open an existing knit.
872
917
        """
873
 
        super(WeaveFile, self).__init__(name, access_mode)
 
918
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
 
919
            allow_reserved=False)
874
920
        self._transport = transport
875
921
        self._filemode = filemode
876
922
        try:
891
937
        self._save()
892
938
        return result
893
939
 
894
 
    def _clone_text(self, new_version_id, old_version_id, parents):
895
 
        """See VersionedFile.clone_text."""
896
 
        super(WeaveFile, self)._clone_text(new_version_id, old_version_id, parents)
897
 
        self._save
898
 
 
899
940
    def copy_to(self, name, transport):
900
941
        """See VersionedFile.copy_to()."""
901
942
        # as we are all in memory always, just serialise to the new place.
910
951
        sio = StringIO()
911
952
        write_weave_v5(self, sio)
912
953
        sio.seek(0)
913
 
        self._transport.put_file(self._weave_name + WeaveFile.WEAVE_SUFFIX,
914
 
                                 sio,
915
 
                                 self._filemode)
 
954
        bytes = sio.getvalue()
 
955
        path = self._weave_name + WeaveFile.WEAVE_SUFFIX
 
956
        try:
 
957
            self._transport.put_bytes(path, bytes, self._filemode)
 
958
        except errors.NoSuchFile:
 
959
            self._transport.mkdir(dirname(path))
 
960
            self._transport.put_bytes(path, bytes, self._filemode)
916
961
 
917
962
    @staticmethod
918
963
    def get_suffixes():
919
964
        """See VersionedFile.get_suffixes()."""
920
965
        return [WeaveFile.WEAVE_SUFFIX]
921
966
 
922
 
    def join(self, other, pb=None, msg=None, version_ids=None,
923
 
             ignore_missing=False):
924
 
        """Join other into self and save."""
925
 
        super(WeaveFile, self).join(other, pb, msg, version_ids, ignore_missing)
 
967
    def insert_record_stream(self, stream):
 
968
        super(WeaveFile, self).insert_record_stream(stream)
926
969
        self._save()
927
970
 
928
971
 
929
972
def _reweave(wa, wb, pb=None, msg=None):
930
973
    """Combine two weaves and return the result.
931
974
 
932
 
    This works even if a revision R has different parents in 
 
975
    This works even if a revision R has different parents in
933
976
    wa and wb.  In the resulting weave all the parents are given.
934
977
 
935
 
    This is done by just building up a new weave, maintaining ordering 
 
978
    This is done by just building up a new weave, maintaining ordering
936
979
    of the versions in the two inputs.  More efficient approaches
937
 
    might be possible but it should only be necessary to do 
938
 
    this operation rarely, when a new previously ghost version is 
 
980
    might be possible but it should only be necessary to do
 
981
    this operation rarely, when a new previously ghost version is
939
982
    inserted.
940
983
 
941
984
    :param pb: An optional progress bar, indicating how far done we are
949
992
    # map from version name -> all parent names
950
993
    combined_parents = _reweave_parent_graphs(wa, wb)
951
994
    mutter("combined parents: %r", combined_parents)
952
 
    order = topo_sort(combined_parents.iteritems())
 
995
    order = tsort.topo_sort(combined_parents.iteritems())
953
996
    mutter("order to reweave: %r", order)
954
997
 
955
998
    if pb and not msg:
975
1018
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
976
1019
    return wr
977
1020
 
 
1021
 
978
1022
def _reweave_parent_graphs(wa, wb):
979
1023
    """Return combined parent ancestry for two weaves.
980
 
    
 
1024
 
981
1025
    Returned as a list of (version_name, set(parent_names))"""
982
1026
    combined = {}
983
1027
    for weave in [wa, wb]:
985
1029
            p = combined.setdefault(name, set())
986
1030
            p.update(map(weave._idx_to_name, weave._parents[idx]))
987
1031
    return combined
988
 
 
989
 
 
990
 
def weave_toc(w):
991
 
    """Show the weave's table-of-contents"""
992
 
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
993
 
    for i in (6, 50, 10, 10):
994
 
        print '-' * i,
995
 
    print
996
 
    for i in range(w.num_versions()):
997
 
        sha1 = w._sha1s[i]
998
 
        name = w._names[i]
999
 
        parent_str = ' '.join(map(str, w._parents[i]))
1000
 
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
1001
 
 
1002
 
 
1003
 
 
1004
 
def weave_stats(weave_file, pb):
1005
 
    from bzrlib.weavefile import read_weave
1006
 
 
1007
 
    wf = file(weave_file, 'rb')
1008
 
    w = read_weave(wf)
1009
 
    # FIXME: doesn't work on pipes
1010
 
    weave_size = wf.tell()
1011
 
 
1012
 
    total = 0
1013
 
    vers = len(w)
1014
 
    for i in range(vers):
1015
 
        pb.update('checking sizes', i, vers)
1016
 
        for origin, lineno, line in w._extract([i]):
1017
 
            total += len(line)
1018
 
 
1019
 
    pb.clear()
1020
 
 
1021
 
    print 'versions          %9d' % vers
1022
 
    print 'weave file        %9d bytes' % weave_size
1023
 
    print 'total contents    %9d bytes' % total
1024
 
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
1025
 
    if vers:
1026
 
        avg = total/vers
1027
 
        print 'average size      %9d bytes' % avg
1028
 
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
1029
 
 
1030
 
 
1031
 
def usage():
1032
 
    print """bzr weave tool
1033
 
 
1034
 
Experimental tool for weave algorithm.
1035
 
 
1036
 
usage:
1037
 
    weave init WEAVEFILE
1038
 
        Create an empty weave file
1039
 
    weave get WEAVEFILE VERSION
1040
 
        Write out specified version.
1041
 
    weave check WEAVEFILE
1042
 
        Check consistency of all versions.
1043
 
    weave toc WEAVEFILE
1044
 
        Display table of contents.
1045
 
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
1046
 
        Add NEWTEXT, with specified parent versions.
1047
 
    weave annotate WEAVEFILE VERSION
1048
 
        Display origin of each line.
1049
 
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
1050
 
        Auto-merge two versions and display conflicts.
1051
 
    weave diff WEAVEFILE VERSION1 VERSION2 
1052
 
        Show differences between two versions.
1053
 
 
1054
 
example:
1055
 
 
1056
 
    % weave init foo.weave
1057
 
    % vi foo.txt
1058
 
    % weave add foo.weave ver0 < foo.txt
1059
 
    added version 0
1060
 
 
1061
 
    (create updated version)
1062
 
    % vi foo.txt
1063
 
    % weave get foo.weave 0 | diff -u - foo.txt
1064
 
    % weave add foo.weave ver1 0 < foo.txt
1065
 
    added version 1
1066
 
 
1067
 
    % weave get foo.weave 0 > foo.txt       (create forked version)
1068
 
    % vi foo.txt
1069
 
    % weave add foo.weave ver2 0 < foo.txt
1070
 
    added version 2
1071
 
 
1072
 
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
1073
 
    % vi foo.txt                            (resolve conflicts)
1074
 
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
1075
 
    
1076
 
"""
1077
 
    
1078
 
 
1079
 
 
1080
 
def main(argv):
1081
 
    import sys
1082
 
    import os
1083
 
    try:
1084
 
        import bzrlib
1085
 
    except ImportError:
1086
 
        # in case we're run directly from the subdirectory
1087
 
        sys.path.append('..')
1088
 
        import bzrlib
1089
 
    from bzrlib.weavefile import write_weave, read_weave
1090
 
    from bzrlib.progress import ProgressBar
1091
 
 
1092
 
    try:
1093
 
        import psyco
1094
 
        psyco.full()
1095
 
    except ImportError:
1096
 
        pass
1097
 
 
1098
 
    if len(argv) < 2:
1099
 
        usage()
1100
 
        return 0
1101
 
 
1102
 
    cmd = argv[1]
1103
 
 
1104
 
    def readit():
1105
 
        return read_weave(file(argv[2], 'rb'))
1106
 
    
1107
 
    if cmd == 'help':
1108
 
        usage()
1109
 
    elif cmd == 'add':
1110
 
        w = readit()
1111
 
        # at the moment, based on everything in the file
1112
 
        name = argv[3]
1113
 
        parents = map(int, argv[4:])
1114
 
        lines = sys.stdin.readlines()
1115
 
        ver = w.add(name, parents, lines)
1116
 
        write_weave(w, file(argv[2], 'wb'))
1117
 
        print 'added version %r %d' % (name, ver)
1118
 
    elif cmd == 'init':
1119
 
        fn = argv[2]
1120
 
        if os.path.exists(fn):
1121
 
            raise IOError("file exists")
1122
 
        w = Weave()
1123
 
        write_weave(w, file(fn, 'wb'))
1124
 
    elif cmd == 'get': # get one version
1125
 
        w = readit()
1126
 
        sys.stdout.writelines(w.get_iter(int(argv[3])))
1127
 
        
1128
 
    elif cmd == 'diff':
1129
 
        w = readit()
1130
 
        fn = argv[2]
1131
 
        v1, v2 = map(int, argv[3:5])
1132
 
        lines1 = w.get(v1)
1133
 
        lines2 = w.get(v2)
1134
 
        diff_gen = bzrlib.patiencediff.unified_diff(lines1, lines2,
1135
 
                                '%s version %d' % (fn, v1),
1136
 
                                '%s version %d' % (fn, v2))
1137
 
        sys.stdout.writelines(diff_gen)
1138
 
            
1139
 
    elif cmd == 'annotate':
1140
 
        w = readit()
1141
 
        # newline is added to all lines regardless; too hard to get
1142
 
        # reasonable formatting otherwise
1143
 
        lasto = None
1144
 
        for origin, text in w.annotate(int(argv[3])):
1145
 
            text = text.rstrip('\r\n')
1146
 
            if origin == lasto:
1147
 
                print '      | %s' % (text)
1148
 
            else:
1149
 
                print '%5d | %s' % (origin, text)
1150
 
                lasto = origin
1151
 
                
1152
 
    elif cmd == 'toc':
1153
 
        weave_toc(readit())
1154
 
 
1155
 
    elif cmd == 'stats':
1156
 
        weave_stats(argv[2], ProgressBar())
1157
 
        
1158
 
    elif cmd == 'check':
1159
 
        w = readit()
1160
 
        pb = ProgressBar()
1161
 
        w.check(pb)
1162
 
        pb.clear()
1163
 
        print '%d versions ok' % w.num_versions()
1164
 
 
1165
 
    elif cmd == 'inclusions':
1166
 
        w = readit()
1167
 
        print ' '.join(map(str, w.inclusions([int(argv[3])])))
1168
 
 
1169
 
    elif cmd == 'parents':
1170
 
        w = readit()
1171
 
        print ' '.join(map(str, w._parents[int(argv[3])]))
1172
 
 
1173
 
    elif cmd == 'plan-merge':
1174
 
        # replaced by 'bzr weave-plan-merge'
1175
 
        w = readit()
1176
 
        for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
1177
 
            if line:
1178
 
                print '%14s | %s' % (state, line),
1179
 
    elif cmd == 'merge':
1180
 
        # replaced by 'bzr weave-merge-text'
1181
 
        w = readit()
1182
 
        p = w.plan_merge(int(argv[3]), int(argv[4]))
1183
 
        sys.stdout.writelines(w.weave_merge(p))
1184
 
    else:
1185
 
        raise ValueError('unknown command %r' % cmd)
1186
 
    
1187
 
 
1188
 
if __name__ == '__main__':
1189
 
    import sys
1190
 
    sys.exit(main(sys.argv))
1191
 
 
1192
 
 
1193
 
class InterWeave(InterVersionedFile):
1194
 
    """Optimised code paths for weave to weave operations."""
1195
 
    
1196
 
    _matching_file_from_factory = staticmethod(WeaveFile)
1197
 
    _matching_file_to_factory = staticmethod(WeaveFile)
1198
 
    
1199
 
    @staticmethod
1200
 
    def is_compatible(source, target):
1201
 
        """Be compatible with weaves."""
1202
 
        try:
1203
 
            return (isinstance(source, Weave) and
1204
 
                    isinstance(target, Weave))
1205
 
        except AttributeError:
1206
 
            return False
1207
 
 
1208
 
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1209
 
        """See InterVersionedFile.join."""
1210
 
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1211
 
        if self.target.versions() == [] and version_ids is None:
1212
 
            self.target._copy_weave_content(self.source)
1213
 
            return
1214
 
        self.target._join(self.source, pb, msg, version_ids, ignore_missing)
1215
 
 
1216
 
 
1217
 
InterVersionedFile.register_optimiser(InterWeave)