~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: Alexander Belchenko
  • Date: 2007-10-26 21:49:15 UTC
  • mto: (2947.4.2 0.92)
  • mto: This revision was merged to the branch mainline in revision 2971.
  • Revision ID: bialix@ukr.net-20071026214915-5eacqh9k2ps6jagj
windows python-based installer: shortcut for uninstall action

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2009 Canonical Ltd
 
1
#! /usr/bin/python
 
2
 
 
3
# Copyright (C) 2005 Canonical Ltd
2
4
#
3
5
# This program is free software; you can redistribute it and/or modify
4
6
# it under the terms of the GNU General Public License as published by
12
14
#
13
15
# You should have received a copy of the GNU General Public License
14
16
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
18
 
17
19
# Author: Martin Pool <mbp@canonical.com>
18
20
 
59
61
# where the basis and destination are unchanged.
60
62
 
61
63
# FIXME: Sometimes we will be given a parents list for a revision
62
 
# that includes some redundant parents (i.e. already a parent of
63
 
# something in the list.)  We should eliminate them.  This can
 
64
# that includes some redundant parents (i.e. already a parent of 
 
65
# something in the list.)  We should eliminate them.  This can 
64
66
# be done fairly efficiently because the sequence numbers constrain
65
67
# the possible relationships.
66
68
 
69
71
from copy import copy
70
72
from cStringIO import StringIO
71
73
import os
 
74
import sha
72
75
import time
73
76
import warnings
74
77
 
75
 
from bzrlib.lazy_import import lazy_import
76
 
lazy_import(globals(), """
77
 
from bzrlib import tsort
78
 
""")
79
78
from bzrlib import (
80
 
    errors,
81
 
    osutils,
82
79
    progress,
83
80
    )
 
81
from bzrlib.trace import mutter
84
82
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
85
83
        RevisionAlreadyPresent,
86
84
        RevisionNotPresent,
87
 
        UnavailableRepresentation,
88
85
        WeaveRevisionAlreadyPresent,
89
86
        WeaveRevisionNotPresent,
90
87
        )
91
 
from bzrlib.osutils import dirname, sha, sha_strings, split_lines
 
88
import bzrlib.errors as errors
 
89
from bzrlib.osutils import sha_strings
92
90
import bzrlib.patiencediff
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
 
    )
 
91
from bzrlib.tsort import topo_sort
 
92
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
103
93
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
104
94
 
105
95
 
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
 
 
131
96
class Weave(VersionedFile):
132
97
    """weave - versioned text file storage.
133
 
 
 
98
    
134
99
    A Weave manages versions of line-based text files, keeping track
135
100
    of the originating version for each line.
136
101
 
182
147
 
183
148
    * It doesn't seem very useful to have an active insertion
184
149
      inside an inactive insertion, but it might happen.
185
 
 
 
150
      
186
151
    * Therefore, all instructions are always"considered"; that
187
152
      is passed onto and off the stack.  An outer inactive block
188
153
      doesn't disable an inner block.
218
183
    """
219
184
 
220
185
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
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__()
 
186
                 '_weave_name', '_matcher']
 
187
    
 
188
    def __init__(self, weave_name=None, access_mode='w', matcher=None):
 
189
        super(Weave, self).__init__(access_mode)
232
190
        self._weave = []
233
191
        self._parents = []
234
192
        self._sha1s = []
239
197
            self._matcher = bzrlib.patiencediff.PatienceSequenceMatcher
240
198
        else:
241
199
            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
248
200
 
249
201
    def __repr__(self):
250
202
        return "Weave(%r)" % self._weave_name
251
203
 
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
 
 
259
204
    def copy(self):
260
205
        """Return a deep copy of self.
261
 
 
 
206
        
262
207
        The copy can be modified without affecting the original weave."""
263
208
        other = Weave()
264
209
        other._weave = self._weave[:]
274
219
            return False
275
220
        return self._parents == other._parents \
276
221
               and self._weave == other._weave \
277
 
               and self._sha1s == other._sha1s
278
 
 
 
222
               and self._sha1s == other._sha1s 
 
223
    
279
224
    def __ne__(self, other):
280
225
        return not self.__eq__(other)
281
226
 
284
229
 
285
230
    def _lookup(self, name):
286
231
        """Convert symbolic version name to index."""
287
 
        if not self._allow_reserved:
288
 
            self.check_not_reserved_id(name)
 
232
        self.check_not_reserved_id(name)
289
233
        try:
290
234
            return self._name_map[name]
291
235
        except KeyError:
301
245
 
302
246
    __contains__ = has_version
303
247
 
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
 
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)])
384
251
 
385
252
    def _check_repeated_add(self, name, parents, text, sha1):
386
253
        """Check that a duplicated add is OK.
402
269
 
403
270
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
404
271
        """Add a single text on top of the weave.
405
 
 
 
272
  
406
273
        Returns the index number of the newly added version.
407
274
 
408
275
        version_id
409
276
            Symbolic name for this version.
410
277
            (Typically the revision-id of the revision that added it.)
411
 
            If None, a name will be allocated based on the hash. (sha1:SHAHASH)
412
278
 
413
279
        parents
414
280
            List or set of direct parent version numbers.
415
 
 
 
281
            
416
282
        lines
417
283
            Sequence of lines to be added in the new version.
418
284
 
419
285
        :param nostore_sha: See VersionedFile.add_lines.
420
286
        """
 
287
        assert isinstance(version_id, basestring)
421
288
        self._check_lines_not_unicode(lines)
422
289
        self._check_lines_are_lines(lines)
423
290
        if not sha1:
424
291
            sha1 = sha_strings(lines)
425
292
        if sha1 == nostore_sha:
426
293
            raise errors.ExistingContent
427
 
        if version_id is None:
428
 
            version_id = "sha1:" + sha1
429
294
        if version_id in self._name_map:
430
295
            return self._check_repeated_add(version_id, parents, lines, sha1)
431
296
 
442
307
        self._names.append(version_id)
443
308
        self._name_map[version_id] = new_version
444
309
 
445
 
 
 
310
            
446
311
        if not parents:
447
312
            # special case; adding with no parents revision; can do
448
313
            # this more quickly by just appending unconditionally.
459
324
            if sha1 == self._sha1s[pv]:
460
325
                # special case: same as the single parent
461
326
                return new_version
462
 
 
 
327
            
463
328
 
464
329
        ancestors = self._inclusions(parents)
465
330
 
500
365
            #print 'raw match', tag, i1, i2, j1, j2
501
366
            if tag == 'equal':
502
367
                continue
 
368
 
503
369
            i1 = basis_lineno[i1]
504
370
            i2 = basis_lineno[i2]
 
371
 
 
372
            assert 0 <= j1 <= j2 <= len(lines)
 
373
 
 
374
            #print tag, i1, i2, j1, j2
 
375
 
505
376
            # the deletion and insertion are handled separately.
506
377
            # first delete the region.
507
378
            if i1 != i2:
514
385
                # i2; we want to insert after this region to make sure
515
386
                # we don't destroy ourselves
516
387
                i = i2 + offset
517
 
                self._weave[i:i] = ([('{', new_version)]
518
 
                                    + lines[j1:j2]
 
388
                self._weave[i:i] = ([('{', new_version)] 
 
389
                                    + lines[j1:j2] 
519
390
                                    + [('}', None)])
520
391
                offset += 2 + (j2 - j1)
521
392
        return new_version
522
393
 
 
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
 
523
399
    def _inclusions(self, versions):
524
400
        """Return set of all ancestors of given version(s)."""
525
401
        if not len(versions):
548
424
            if not isinstance(l, basestring):
549
425
                raise ValueError("text line should be a string or unicode, not %s"
550
426
                                 % type(l))
551
 
 
 
427
        
552
428
 
553
429
 
554
430
    def _check_versions(self, indexes):
562
438
    def _compatible_parents(self, my_parents, other_parents):
563
439
        """During join check that other_parents are joinable with my_parents.
564
440
 
565
 
        Joinable is defined as 'is a subset of' - supersets may require
 
441
        Joinable is defined as 'is a subset of' - supersets may require 
566
442
        regeneration of diffs, but subsets do not.
567
443
        """
568
444
        return len(other_parents.difference(my_parents)) == 0
569
445
 
570
 
    def annotate(self, version_id):
571
 
        """Return a list of (version-id, line) tuples for version_id.
 
446
    def annotate_iter(self, version_id):
 
447
        """Yield list of (version-id, line) pairs for the specified version.
572
448
 
573
449
        The index indicates when the line originated in the weave."""
574
450
        incls = [self._lookup(version_id)]
575
 
        return [(self._idx_to_name(origin), text) for origin, lineno, text in
576
 
            self._extract(incls)]
 
451
        for origin, lineno, text in self._extract(incls):
 
452
            yield self._idx_to_name(origin), text
577
453
 
578
454
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
579
455
                                                pb=None):
582
458
            version_ids = self.versions()
583
459
        version_ids = set(version_ids)
584
460
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
585
 
            if inserted not in version_ids: continue
 
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
586
465
            if line[-1] != '\n':
587
 
                yield line + '\n', inserted
 
466
                yield line + '\n'
588
467
            else:
589
 
                yield line, inserted
 
468
                yield line
590
469
 
591
470
    def _walk_internal(self, version_ids=None):
592
471
        """Helper method for weave actions."""
593
 
 
 
472
        
594
473
        istack = []
595
474
        dset = set()
596
475
 
605
484
                elif c == '}':
606
485
                    istack.pop()
607
486
                elif c == '[':
 
487
                    assert self._names[v] not in dset
608
488
                    dset.add(self._names[v])
609
489
                elif c == ']':
610
490
                    dset.remove(self._names[v])
611
491
                else:
612
492
                    raise WeaveFormatError('unexpected instruction %r' % v)
613
493
            else:
 
494
                assert l.__class__ in (str, unicode)
 
495
                assert istack
614
496
                yield lineno, istack[-1], frozenset(dset), l
615
497
            lineno += 1
616
498
 
665
547
                # not in either revision
666
548
                yield 'irrelevant', line
667
549
 
 
550
        yield 'unchanged', ''           # terminator
 
551
 
668
552
    def _extract(self, versions):
669
553
        """Yield annotation of lines in included set.
670
554
 
677
561
        for i in versions:
678
562
            if not isinstance(i, int):
679
563
                raise ValueError(i)
680
 
 
 
564
            
681
565
        included = self._inclusions(versions)
682
566
 
683
567
        istack = []
692
576
 
693
577
        WFE = WeaveFormatError
694
578
 
695
 
        # wow.
 
579
        # wow. 
696
580
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
697
581
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
698
582
        # 1.6 seconds in 'isinstance'.
704
588
        # we're still spending ~1/4 of the method in isinstance though.
705
589
        # so lets hard code the acceptable string classes we expect:
706
590
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
707
 
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list'
 
591
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list' 
708
592
        #                                          objects>
709
593
        # yay, down to ~1/4 the initial extract time, and our inline time
710
594
        # has shrunk again, with isinstance no longer dominating.
711
595
        # tweaking the stack inclusion test to use a set gives:
712
596
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
713
 
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list'
 
597
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list' 
714
598
        #                                          objects>
715
599
        # - a 5% win, or possibly just noise. However with large istacks that
716
600
        # 'in' test could dominate, so I'm leaving this change in place -
717
601
        # when its fast enough to consider profiling big datasets we can review.
718
602
 
719
 
 
720
 
 
 
603
              
 
604
             
721
605
 
722
606
        for l in self._weave:
723
607
            if l.__class__ == tuple:
724
608
                c, v = l
725
609
                isactive = None
726
610
                if c == '{':
 
611
                    assert v not in iset
727
612
                    istack.append(v)
728
613
                    iset.add(v)
729
614
                elif c == '}':
730
615
                    iset.remove(istack.pop())
731
616
                elif c == '[':
732
617
                    if v in included:
 
618
                        assert v not in dset
733
619
                        dset.add(v)
734
 
                elif c == ']':
 
620
                else:
 
621
                    assert c == ']'
735
622
                    if v in included:
 
623
                        assert v in dset
736
624
                        dset.remove(v)
737
 
                else:
738
 
                    raise AssertionError()
739
625
            else:
 
626
                assert l.__class__ in (str, unicode)
740
627
                if isactive is None:
741
628
                    isactive = (not dset) and istack and (istack[-1] in included)
742
629
                if isactive:
752
639
 
753
640
    def _maybe_lookup(self, name_or_index):
754
641
        """Convert possible symbolic name to index, or pass through indexes.
755
 
 
 
642
        
756
643
        NOT FOR PUBLIC USE.
757
644
        """
758
645
        if isinstance(name_or_index, (int, long)):
768
655
        measured_sha1 = sha_strings(result)
769
656
        if measured_sha1 != expected_sha1:
770
657
            raise errors.WeaveInvalidChecksum(
771
 
                    'file %s, revision %s, expected: %s, measured %s'
 
658
                    'file %s, revision %s, expected: %s, measured %s' 
772
659
                    % (self._weave_name, version_id,
773
660
                       expected_sha1, measured_sha1))
774
661
        return result
775
662
 
 
663
    def get_sha1(self, version_id):
 
664
        """See VersionedFile.get_sha1()."""
 
665
        return self._sha1s[self._lookup(version_id)]
 
666
 
776
667
    def get_sha1s(self, version_ids):
777
668
        """See VersionedFile.get_sha1s()."""
778
 
        result = {}
779
 
        for v in version_ids:
780
 
            result[v] = self._sha1s[self._lookup(v)]
781
 
        return result
 
669
        return [self._sha1s[self._lookup(v)] for v in version_ids]
782
670
 
783
671
    def num_versions(self):
784
672
        """How many versions are in this weave?"""
785
673
        l = len(self._parents)
 
674
        assert l == len(self._sha1s)
786
675
        return l
787
676
 
788
677
    __len__ = num_versions
808
697
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
809
698
            # The problem is that set membership is much more expensive
810
699
            name = self._idx_to_name(i)
811
 
            sha1s[name] = sha()
 
700
            sha1s[name] = sha.new()
812
701
            texts[name] = []
813
702
            new_inc = set([name])
814
703
            for p in self._parents[i]:
815
704
                new_inc.update(inclusions[self._idx_to_name(p)])
816
705
 
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))))
 
706
            assert set(new_inc) == set(self.get_ancestry(name)), \
 
707
                'failed %s != %s' % (set(new_inc), set(self.get_ancestry(name)))
821
708
            inclusions[name] = new_inc
822
709
 
823
710
        nlines = len(self._weave)
853
740
        # no lines outside of insertion blocks, that deletions are
854
741
        # properly paired, etc.
855
742
 
 
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
 
856
794
    def _imported_parents(self, other, other_idx):
857
795
        """Return list of parents in self corresponding to indexes in other."""
858
796
        new_parents = []
860
798
            parent_name = other._names[parent_idx]
861
799
            if parent_name not in self._name_map:
862
800
                # should not be possible
863
 
                raise WeaveError("missing parent {%s} of {%s} in %r"
 
801
                raise WeaveError("missing parent {%s} of {%s} in %r" 
864
802
                                 % (parent_name, other._name_map[other_idx], self))
865
803
            new_parents.append(self._name_map[parent_name])
866
804
        return new_parents
873
811
         * the same text
874
812
         * the same direct parents (by name, not index, and disregarding
875
813
           order)
876
 
 
 
814
        
877
815
        If present & correct return True;
878
 
        if not present in self return False;
 
816
        if not present in self return False; 
879
817
        if inconsistent raise error."""
880
818
        this_idx = self._name_map.get(name, -1)
881
819
        if this_idx != -1:
914
852
    """A WeaveFile represents a Weave on disk and writes on change."""
915
853
 
916
854
    WEAVE_SUFFIX = '.weave'
917
 
 
918
 
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
 
855
    
 
856
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w'):
919
857
        """Create a WeaveFile.
920
 
 
 
858
        
921
859
        :param create: If not True, only open an existing knit.
922
860
        """
923
 
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
924
 
            allow_reserved=False)
 
861
        super(WeaveFile, self).__init__(name, access_mode)
925
862
        self._transport = transport
926
863
        self._filemode = filemode
927
864
        try:
942
879
        self._save()
943
880
        return result
944
881
 
 
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
 
945
887
    def copy_to(self, name, transport):
946
888
        """See VersionedFile.copy_to()."""
947
889
        # as we are all in memory always, just serialise to the new place.
950
892
        sio.seek(0)
951
893
        transport.put_file(name + WeaveFile.WEAVE_SUFFIX, sio, self._filemode)
952
894
 
 
895
    def create_empty(self, name, transport, filemode=None):
 
896
        return WeaveFile(name, transport, filemode, create=True)
 
897
 
953
898
    def _save(self):
954
899
        """Save the weave."""
955
900
        self._check_write_ok()
956
901
        sio = StringIO()
957
902
        write_weave_v5(self, sio)
958
903
        sio.seek(0)
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)
 
904
        self._transport.put_file(self._weave_name + WeaveFile.WEAVE_SUFFIX,
 
905
                                 sio,
 
906
                                 self._filemode)
966
907
 
967
908
    @staticmethod
968
909
    def get_suffixes():
969
910
        """See VersionedFile.get_suffixes()."""
970
911
        return [WeaveFile.WEAVE_SUFFIX]
971
912
 
972
 
    def insert_record_stream(self, stream):
973
 
        super(WeaveFile, self).insert_record_stream(stream)
 
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)
974
917
        self._save()
975
918
 
976
919
 
977
920
def _reweave(wa, wb, pb=None, msg=None):
978
921
    """Combine two weaves and return the result.
979
922
 
980
 
    This works even if a revision R has different parents in
 
923
    This works even if a revision R has different parents in 
981
924
    wa and wb.  In the resulting weave all the parents are given.
982
925
 
983
 
    This is done by just building up a new weave, maintaining ordering
 
926
    This is done by just building up a new weave, maintaining ordering 
984
927
    of the versions in the two inputs.  More efficient approaches
985
 
    might be possible but it should only be necessary to do
986
 
    this operation rarely, when a new previously ghost version is
 
928
    might be possible but it should only be necessary to do 
 
929
    this operation rarely, when a new previously ghost version is 
987
930
    inserted.
988
931
 
989
932
    :param pb: An optional progress bar, indicating how far done we are
997
940
    # map from version name -> all parent names
998
941
    combined_parents = _reweave_parent_graphs(wa, wb)
999
942
    mutter("combined parents: %r", combined_parents)
1000
 
    order = tsort.topo_sort(combined_parents.iteritems())
 
943
    order = topo_sort(combined_parents.iteritems())
1001
944
    mutter("order to reweave: %r", order)
1002
945
 
1003
946
    if pb and not msg:
1023
966
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
1024
967
    return wr
1025
968
 
1026
 
 
1027
969
def _reweave_parent_graphs(wa, wb):
1028
970
    """Return combined parent ancestry for two weaves.
1029
 
 
 
971
    
1030
972
    Returned as a list of (version_name, set(parent_names))"""
1031
973
    combined = {}
1032
974
    for weave in [wa, wb]:
1034
976
            p = combined.setdefault(name, set())
1035
977
            p.update(map(weave._idx_to_name, weave._parents[idx]))
1036
978
    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)