/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: 2008-04-07 04:54:52 UTC
  • mfrom: (3340 +trunk)
  • mto: This revision was merged to the branch mainline in revision 3350.
  • Revision ID: robertc@robertcollins.net-20080407045452-8r6asf9hs0cl5jvy
MergeĀ .dev.

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