~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: Vincent Ladeuil
  • Date: 2010-03-02 10:21:39 UTC
  • mfrom: (4797.2.24 2.1)
  • mto: This revision was merged to the branch mainline in revision 5069.
  • Revision ID: v.ladeuil+lp@free.fr-20100302102139-b5cba7h6xu13mekg
Merge 2.1 into trunk including fixes for #331095, #507557, #185103, #524184 and #369501

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