/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: 2005-12-24 02:20:45 UTC
  • mto: (1185.50.57 bzr-jam-integration)
  • mto: This revision was merged to the branch mainline in revision 1550.
  • Revision ID: robertc@robertcollins.net-20051224022045-14efc8dfa0e1a4e9
Start tests for api usage.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
 
22
22
"""Weave - storage of related text file versions"""
23
23
 
24
 
# before intset (r923) 2000 versions in 41.5s
25
 
# with intset (r926) 2000 versions in 93s !!!
26
 
# better to just use plain sets.
27
 
 
28
 
# making _extract build and return a list, rather than being a generator
29
 
# takes 37.94s
30
 
 
31
 
# with python -O, r923 does 2000 versions in 36.87s
32
 
 
33
 
# with optimizations to avoid mutating lists - 35.75!  I guess copying
34
 
# all the elements every time costs more than the small manipulations.
35
 
# a surprisingly small change.
36
 
 
37
 
# r931, which avoids using a generator for extract, does 36.98s
38
 
 
39
 
# with memoized inclusions, takes 41.49s; not very good
40
 
 
41
 
# with slots, takes 37.35s; without takes 39.16, a bit surprising
42
 
 
43
 
# with the delta calculation mixed in with the add method, rather than
44
 
# separated, takes 36.78s
45
 
 
46
 
# with delta folded in and mutation of the list, 36.13s
47
 
 
48
 
# with all this and simplification of add code, 33s 
49
 
 
50
 
 
51
 
# TODO: Perhaps have copy method for Weave instances?
52
24
 
53
25
# XXX: If we do weaves this way, will a merge still behave the same
54
26
# way if it's done in a different order?  That's a pretty desirable
59
31
# binaries, perhaps by naively splitting on \n or perhaps using
60
32
# something like a rolling checksum.
61
33
 
62
 
# TODO: Track version names as well as indexes. 
63
 
 
64
34
# TODO: End marker for each version so we can stop reading?
65
35
 
66
36
# TODO: Check that no insertion occurs inside a deletion that was
73
43
 
74
44
# TODO: Parallel-extract that passes back each line along with a
75
45
# description of which revisions include it.  Nice for checking all
76
 
# shas in parallel.
77
 
 
78
 
 
79
 
 
80
 
 
81
 
class WeaveError(Exception):
82
 
    """Exception in processing weave"""
83
 
 
84
 
 
85
 
class WeaveFormatError(WeaveError):
86
 
    """Weave invariant violated"""
87
 
    
 
46
# shas or calculating stats in parallel.
 
47
 
 
48
# TODO: Using a single _extract routine and then processing the output
 
49
# is probably inefficient.  It's simple enough that we can afford to
 
50
# have slight specializations for different ways its used: annotate,
 
51
# basis for add, get, etc.
 
52
 
 
53
# TODO: Probably the API should work only in names to hide the integer
 
54
# indexes from the user.
 
55
 
 
56
# TODO: Is there any potential performance win by having an add()
 
57
# variant that is passed a pre-cooked version of the single basis
 
58
# version?
 
59
 
 
60
# TODO: Reweave can possibly be made faster by remembering diffs
 
61
# where the basis and destination are unchanged.
 
62
 
 
63
# 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 
 
66
# be done fairly efficiently because the sequence numbers constrain
 
67
# the possible relationships.
 
68
 
 
69
 
 
70
import sha
 
71
from difflib import SequenceMatcher
 
72
 
 
73
from bzrlib.trace import mutter
 
74
from bzrlib.errors import WeaveError, WeaveFormatError, WeaveParentMismatch, \
 
75
        WeaveRevisionNotPresent, WeaveRevisionAlreadyPresent
 
76
from bzrlib.tsort import topo_sort
 
77
 
88
78
 
89
79
class Weave(object):
90
80
    """weave - versioned text file storage.
118
108
    The instruction can be '{' or '}' for an insertion block, and '['
119
109
    and ']' for a deletion block respectively.  The version is the
120
110
    integer version index.  There is no replace operator, only deletes
121
 
    and inserts.
 
111
    and inserts.  For '}', the end of an insertion, there is no
 
112
    version parameter because it always closes the most recently
 
113
    opened insertion.
122
114
 
123
115
    Constraints/notes:
124
116
 
160
152
        each version; the parent's parents are implied.
161
153
 
162
154
    _sha1s
163
 
        List of hex SHA-1 of each version, or None if not recorded.
 
155
        List of hex SHA-1 of each version.
 
156
 
 
157
    _names
 
158
        List of symbolic names for each version.  Each should be unique.
 
159
 
 
160
    _name_map
 
161
        For each name, the version number.
 
162
 
 
163
    _weave_name
 
164
        Descriptive name of this weave; typically the filename if known.
 
165
        Set by read_weave.
164
166
    """
165
167
 
166
 
    __slots__ = ['_weave', '_parents', '_sha1s']
 
168
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
 
169
                 '_weave_name']
167
170
    
168
 
    def __init__(self):
 
171
    def __init__(self, weave_name=None):
169
172
        self._weave = []
170
173
        self._parents = []
171
174
        self._sha1s = []
172
 
 
 
175
        self._names = []
 
176
        self._name_map = {}
 
177
        self._weave_name = weave_name
 
178
 
 
179
    def __repr__(self):
 
180
        return "Weave(%r)" % self._weave_name
 
181
 
 
182
 
 
183
    def copy(self):
 
184
        """Return a deep copy of self.
 
185
        
 
186
        The copy can be modified without affecting the original weave."""
 
187
        other = Weave()
 
188
        other._weave = self._weave[:]
 
189
        other._parents = self._parents[:]
 
190
        other._sha1s = self._sha1s[:]
 
191
        other._names = self._names[:]
 
192
        other._name_map = self._name_map.copy()
 
193
        other._weave_name = self._weave_name
 
194
        return other
173
195
 
174
196
    def __eq__(self, other):
175
197
        if not isinstance(other, Weave):
176
198
            return False
177
199
        return self._parents == other._parents \
178
 
               and self._weave == other._weave
 
200
               and self._weave == other._weave \
 
201
               and self._sha1s == other._sha1s 
 
202
 
179
203
    
180
 
 
181
204
    def __ne__(self, other):
182
205
        return not self.__eq__(other)
183
206
 
184
 
        
185
 
    def add(self, parents, text):
 
207
    def __contains__(self, name):
 
208
        return self._name_map.has_key(name)
 
209
 
 
210
    def maybe_lookup(self, name_or_index):
 
211
        """Convert possible symbolic name to index, or pass through indexes."""
 
212
        if isinstance(name_or_index, (int, long)):
 
213
            return name_or_index
 
214
        else:
 
215
            return self.lookup(name_or_index)
 
216
 
 
217
        
 
218
    def lookup(self, name):
 
219
        """Convert symbolic version name to index."""
 
220
        try:
 
221
            return self._name_map[name]
 
222
        except KeyError:
 
223
            raise WeaveRevisionNotPresent(name, self)
 
224
 
 
225
    def names(self):
 
226
        return self._names[:]
 
227
 
 
228
    def iter_names(self):
 
229
        """Yield a list of all names in this weave."""
 
230
        return iter(self._names)
 
231
 
 
232
    def idx_to_name(self, version):
 
233
        return self._names[version]
 
234
 
 
235
    def _check_repeated_add(self, name, parents, text, sha1):
 
236
        """Check that a duplicated add is OK.
 
237
 
 
238
        If it is, return the (old) index; otherwise raise an exception.
 
239
        """
 
240
        idx = self.lookup(name)
 
241
        if sorted(self._parents[idx]) != sorted(parents) \
 
242
            or sha1 != self._sha1s[idx]:
 
243
            raise WeaveRevisionAlreadyPresent(name, self)
 
244
        return idx
 
245
        
 
246
    def add(self, name, parents, text, sha1=None):
186
247
        """Add a single text on top of the weave.
187
248
  
188
249
        Returns the index number of the newly added version.
189
250
 
 
251
        name
 
252
            Symbolic name for this version.
 
253
            (Typically the revision-id of the revision that added it.)
 
254
 
190
255
        parents
191
256
            List or set of direct parent version numbers.
192
257
            
193
258
        text
194
 
            Sequence of lines to be added in the new version."""
195
 
 
 
259
            Sequence of lines to be added in the new version.
 
260
 
 
261
        sha -- SHA-1 of the file, if known.  This is trusted to be
 
262
            correct if supplied.
 
263
        """
 
264
        from bzrlib.osutils import sha_strings
 
265
 
 
266
        assert isinstance(name, basestring)
 
267
        if sha1 is None:
 
268
            sha1 = sha_strings(text)
 
269
        if name in self._name_map:
 
270
            return self._check_repeated_add(name, parents, text, sha1)
 
271
 
 
272
        parents = map(self.maybe_lookup, parents)
196
273
        self._check_versions(parents)
197
274
        ## self._check_lines(text)
198
275
        new_version = len(self._parents)
199
276
 
200
 
        import sha
201
 
        s = sha.new()
202
 
        map(s.update, text)
203
 
        sha1 = s.hexdigest()
204
 
        del s
205
277
 
206
 
        # if we abort after here the weave will be corrupt
207
 
        self._parents.append(frozenset(parents))
 
278
        # if we abort after here the (in-memory) weave will be corrupt because only
 
279
        # some fields are updated
 
280
        self._parents.append(parents[:])
208
281
        self._sha1s.append(sha1)
 
282
        self._names.append(name)
 
283
        self._name_map[name] = new_version
209
284
 
210
285
            
211
286
        if not parents:
216
291
            if text:
217
292
                self._weave.append(('{', new_version))
218
293
                self._weave.extend(text)
219
 
                self._weave.append(('}', new_version))
 
294
                self._weave.append(('}', None))
220
295
        
221
296
            return new_version
222
297
 
238
313
            basis_lineno.append(lineno)
239
314
            basis_lines.append(line)
240
315
 
241
 
        # another small special case: a merge, producing the same text as auto-merge
 
316
        # another small special case: a merge, producing the same text
 
317
        # as auto-merge
242
318
        if text == basis_lines:
243
319
            return new_version            
244
320
 
252
328
        #print 'basis_lines:', basis_lines
253
329
        #print 'new_lines:  ', lines
254
330
 
255
 
        from difflib import SequenceMatcher
256
331
        s = SequenceMatcher(None, basis_lines, text)
257
332
 
258
333
        # offset gives the number of lines that have been inserted
287
362
                # we don't destroy ourselves
288
363
                i = i2 + offset
289
364
                self._weave[i:i] = ([('{', new_version)] 
290
 
                                + text[j1:j2] 
291
 
                                + [('}', new_version)])
 
365
                                    + text[j1:j2] 
 
366
                                    + [('}', None)])
292
367
                offset += 2 + (j2 - j1)
293
368
 
294
369
        return new_version
295
370
 
 
371
    def add_identical(self, old_rev_id, new_rev_id, parents):
 
372
        """Add an identical text to old_rev_id as new_rev_id."""
 
373
        old_lines = self.get(self.lookup(old_rev_id))
 
374
        self.add(new_rev_id, parents, old_lines)
296
375
 
297
376
    def inclusions(self, versions):
298
377
        """Return set of all ancestors of given version(s)."""
299
378
        i = set(versions)
300
 
        v = max(versions)
301
 
        try:
302
 
            while v >= 0:
303
 
                if v in i:
304
 
                    # include all its parents
305
 
                    i.update(self._parents[v])
306
 
                v -= 1
307
 
            return i
308
 
        except IndexError:
309
 
            raise ValueError("version %d not present in weave" % v)
 
379
        for v in xrange(max(versions), 0, -1):
 
380
            if v in i:
 
381
                # include all its parents
 
382
                i.update(self._parents[v])
 
383
        return i
 
384
        ## except IndexError:
 
385
        ##     raise ValueError("version %d not present in weave" % v)
 
386
 
 
387
 
 
388
    def parents(self, version):
 
389
        return self._parents[version]
 
390
 
 
391
 
 
392
    def parent_names(self, version):
 
393
        """Return version names for parents of a version."""
 
394
        return map(self.idx_to_name, self._parents[self.lookup(version)])
310
395
 
311
396
 
312
397
    def minimal_parents(self, version):
352
437
                raise IndexError("invalid version number %r" % i)
353
438
 
354
439
    
355
 
    def annotate(self, index):
356
 
        return list(self.annotate_iter(index))
357
 
 
358
 
 
359
 
    def annotate_iter(self, version):
 
440
    def annotate(self, name_or_index):
 
441
        return list(self.annotate_iter(name_or_index))
 
442
 
 
443
 
 
444
    def annotate_iter(self, name_or_index):
360
445
        """Yield list of (index-id, line) pairs for the specified version.
361
446
 
362
447
        The index indicates when the line originated in the weave."""
363
 
        for origin, lineno, text in self._extract([version]):
 
448
        incls = [self.maybe_lookup(name_or_index)]
 
449
        for origin, lineno, text in self._extract(incls):
364
450
            yield origin, text
365
451
 
366
 
 
367
452
    def _walk(self):
368
453
        """Walk the weave.
369
454
 
384
469
                if c == '{':
385
470
                    istack.append(v)
386
471
                elif c == '}':
387
 
                    oldv = istack.pop()
 
472
                    istack.pop()
388
473
                elif c == '[':
389
474
                    assert v not in dset
390
475
                    dset.add(v)
391
476
                elif c == ']':
392
477
                    dset.remove(v)
393
478
                else:
394
 
                    raise WeaveFormatError('unexpected instruction %r'
395
 
                                           % v)
 
479
                    raise WeaveFormatError('unexpected instruction %r' % v)
396
480
            else:
397
481
                assert isinstance(l, basestring)
398
482
                assert istack
410
494
 
411
495
        The set typically but not necessarily corresponds to a version.
412
496
        """
 
497
        for i in versions:
 
498
            if not isinstance(i, int):
 
499
                raise ValueError(i)
 
500
            
413
501
        included = self.inclusions(versions)
414
502
 
415
503
        istack = []
431
519
                    assert v not in istack
432
520
                    istack.append(v)
433
521
                elif c == '}':
434
 
                    oldv = istack.pop()
435
 
                    assert oldv == v
 
522
                    istack.pop()
436
523
                elif c == '[':
437
524
                    if v in included:
438
525
                        assert v not in dset
449
536
                if isactive:
450
537
                    result.append((istack[-1], lineno, l))
451
538
            lineno += 1
452
 
 
453
539
        if istack:
454
 
            raise WFE("unclosed insertion blocks at end of weave",
455
 
                                   istack)
 
540
            raise WeaveFormatError("unclosed insertion blocks "
 
541
                    "at end of weave: %s" % istack)
456
542
        if dset:
457
 
            raise WFE("unclosed deletion blocks at end of weave",
458
 
                                   dset)
459
 
 
 
543
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
 
544
                                   % dset)
460
545
        return result
461
 
    
462
 
 
463
 
 
464
 
    def get_iter(self, version):
 
546
 
 
547
 
 
548
    def get_iter(self, name_or_index):
465
549
        """Yield lines for the specified version."""
466
 
        for origin, lineno, line in self._extract([version]):
 
550
        incls = [self.maybe_lookup(name_or_index)]
 
551
        for origin, lineno, line in self._extract(incls):
467
552
            yield line
468
553
 
469
554
 
470
 
    def get(self, index):
471
 
        return list(self.get_iter(index))
 
555
    def get_text(self, name_or_index):
 
556
        return ''.join(self.get_iter(name_or_index))
 
557
        assert isinstance(version, int)
 
558
 
 
559
 
 
560
    def get_lines(self, name_or_index):
 
561
        return list(self.get_iter(name_or_index))
 
562
 
 
563
 
 
564
    get = get_lines
472
565
 
473
566
 
474
567
    def mash_iter(self, included):
475
568
        """Return composed version of multiple included versions."""
 
569
        included = map(self.maybe_lookup, included)
476
570
        for origin, lineno, text in self._extract(included):
477
571
            yield text
478
572
 
508
602
 
509
603
        # try extracting all versions; this is a bit slow and parallel
510
604
        # extraction could be used
511
 
        import sha
512
605
        nv = self.numversions()
513
606
        for version in range(nv):
514
607
            if progress_bar:
528
621
        # properly paired, etc.
529
622
 
530
623
 
531
 
 
532
 
    def merge(self, merge_versions):
533
 
        """Automerge and mark conflicts between versions.
534
 
 
535
 
        This returns a sequence, each entry describing alternatives
536
 
        for a chunk of the file.  Each of the alternatives is given as
537
 
        a list of lines.
538
 
 
539
 
        If there is a chunk of the file where there's no diagreement,
540
 
        only one alternative is given.
541
 
        """
542
 
 
543
 
        # approach: find the included versions common to all the
544
 
        # merged versions
545
 
        raise NotImplementedError()
546
 
 
547
 
 
548
 
 
549
624
    def _delta(self, included, lines):
550
625
        """Return changes from basis to new revision.
551
626
 
565
640
        If line1=line2, this is a pure insert; if newlines=[] this is a
566
641
        pure delete.  (Similar to difflib.)
567
642
        """
568
 
 
 
643
        raise NotImplementedError()
569
644
 
570
645
            
571
646
    def plan_merge(self, ver_a, ver_b):
620
695
        lines_a = []
621
696
        lines_b = []
622
697
        ch_a = ch_b = False
623
 
 
 
698
        # TODO: Return a structured form of the conflicts (e.g. 2-tuples for
 
699
        # conflicted regions), rather than just inserting the markers.
 
700
        # 
 
701
        # TODO: Show some version information (e.g. author, date) on 
 
702
        # conflicted regions.
624
703
        for state, line in plan:
625
704
            if state == 'unchanged' or state == 'killed-both':
626
705
                # resync and flush queued conflicts changes if any
634
713
                elif lines_a == lines_b:
635
714
                    for l in lines_a: yield l
636
715
                else:
637
 
                    yield '<<<<\n'
 
716
                    yield '<<<<<<<\n'
638
717
                    for l in lines_a: yield l
639
 
                    yield '====\n'
 
718
                    yield '=======\n'
640
719
                    for l in lines_b: yield l
641
 
                    yield '>>>>\n'
 
720
                    yield '>>>>>>>\n'
642
721
 
643
722
                del lines_a[:]
644
723
                del lines_b[:]
664
743
                                 'killed-both'), \
665
744
                       state
666
745
 
667
 
                
668
 
 
669
 
 
670
 
 
671
 
 
672
 
 
673
 
def weave_info(w):
674
 
    """Show some text information about the weave."""
675
 
    print '%6s %40s %20s' % ('ver', 'sha1', 'parents')
676
 
    for i in (6, 40, 20):
 
746
 
 
747
    def join(self, other):
 
748
        import sys, time
 
749
        """Integrate versions from other into this weave.
 
750
 
 
751
        The resulting weave contains all the history of both weaves; 
 
752
        any version you could retrieve from either self or other can be 
 
753
        retrieved from self after this call.
 
754
 
 
755
        It is illegal for the two weaves to contain different values 
 
756
        or different parents for any version.  See also reweave().
 
757
        """
 
758
        if other.numversions() == 0:
 
759
            return          # nothing to update, easy
 
760
        # two loops so that we do not change ourselves before verifying it
 
761
        # will be ok
 
762
        # work through in index order to make sure we get all dependencies
 
763
        for other_idx, name in enumerate(other._names):
 
764
            self._check_version_consistent(other, other_idx, name)
 
765
 
 
766
        merged = 0
 
767
        processed = 0
 
768
        time0 = time.time( )
 
769
        for other_idx, name in enumerate(other._names):
 
770
            # TODO: If all the parents of the other version are already
 
771
            # present then we can avoid some work by just taking the delta
 
772
            # and adjusting the offsets.
 
773
            new_parents = self._imported_parents(other, other_idx)
 
774
            sha1 = other._sha1s[other_idx]
 
775
 
 
776
            processed += 1
 
777
           
 
778
            if name in self._names:
 
779
                idx = self.lookup(name)
 
780
                n1 = map(other.idx_to_name, other._parents[other_idx] )
 
781
                n2 = map(self.idx_to_name, self._parents[other_idx] )
 
782
                if sha1 ==  self._sha1s[idx] and n1 == n2:
 
783
                        continue
 
784
 
 
785
            merged += 1
 
786
            lines = other.get_lines(other_idx)
 
787
            self.add(name, new_parents, lines, sha1)
 
788
 
 
789
        mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
 
790
                merged,processed,self._weave_name, time.time( )-time0))
 
791
 
 
792
 
 
793
 
 
794
 
 
795
    def _imported_parents(self, other, other_idx):
 
796
        """Return list of parents in self corresponding to indexes in other."""
 
797
        new_parents = []
 
798
        for parent_idx in other._parents[other_idx]:
 
799
            parent_name = other._names[parent_idx]
 
800
            if parent_name not in self._names:
 
801
                # should not be possible
 
802
                raise WeaveError("missing parent {%s} of {%s} in %r" 
 
803
                                 % (parent_name, other._name_map[other_idx], self))
 
804
            new_parents.append(self._name_map[parent_name])
 
805
        return new_parents
 
806
 
 
807
    def _check_version_consistent(self, other, other_idx, name):
 
808
        """Check if a version in consistent in this and other.
 
809
 
 
810
        To be consistent it must have:
 
811
 
 
812
         * the same text
 
813
         * the same direct parents (by name, not index, and disregarding
 
814
           order)
 
815
        
 
816
        If present & correct return True;
 
817
        if not present in self return False; 
 
818
        if inconsistent raise error."""
 
819
        this_idx = self._name_map.get(name, -1)
 
820
        if this_idx != -1:
 
821
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
 
822
                raise WeaveError("inconsistent texts for version {%s} "
 
823
                                 "when joining weaves"
 
824
                                 % (name))
 
825
            self_parents = self._parents[this_idx]
 
826
            other_parents = other._parents[other_idx]
 
827
            n1 = [self._names[i] for i in self_parents]
 
828
            n2 = [other._names[i] for i in other_parents]
 
829
            n1.sort()
 
830
            n2.sort()
 
831
            if n1 != n2:
 
832
                raise WeaveParentMismatch("inconsistent parents "
 
833
                    "for version {%s}: %s vs %s" % (name, n1, n2))
 
834
            else:
 
835
                return True         # ok!
 
836
        else:
 
837
            return False
 
838
 
 
839
    def reweave(self, other):
 
840
        """Reweave self with other."""
 
841
        new_weave = reweave(self, other)
 
842
        for attr in self.__slots__:
 
843
            setattr(self, attr, getattr(new_weave, attr))
 
844
 
 
845
 
 
846
def reweave(wa, wb):
 
847
    """Combine two weaves and return the result.
 
848
 
 
849
    This works even if a revision R has different parents in 
 
850
    wa and wb.  In the resulting weave all the parents are given.
 
851
 
 
852
    This is done by just building up a new weave, maintaining ordering 
 
853
    of the versions in the two inputs.  More efficient approaches
 
854
    might be possible but it should only be necessary to do 
 
855
    this operation rarely, when a new previously ghost version is 
 
856
    inserted.
 
857
    """
 
858
    wr = Weave()
 
859
    ia = ib = 0
 
860
    queue_a = range(wa.numversions())
 
861
    queue_b = range(wb.numversions())
 
862
    # first determine combined parents of all versions
 
863
    # map from version name -> all parent names
 
864
    combined_parents = _reweave_parent_graphs(wa, wb)
 
865
    mutter("combined parents: %r", combined_parents)
 
866
    order = topo_sort(combined_parents.iteritems())
 
867
    mutter("order to reweave: %r", order)
 
868
    for name in order:
 
869
        if name in wa._name_map:
 
870
            lines = wa.get_lines(name)
 
871
            if name in wb._name_map:
 
872
                assert lines == wb.get_lines(name)
 
873
        else:
 
874
            lines = wb.get_lines(name)
 
875
        wr.add(name, combined_parents[name], lines)
 
876
    return wr
 
877
 
 
878
 
 
879
def _reweave_parent_graphs(wa, wb):
 
880
    """Return combined parent ancestry for two weaves.
 
881
    
 
882
    Returned as a list of (version_name, set(parent_names))"""
 
883
    combined = {}
 
884
    for weave in [wa, wb]:
 
885
        for idx, name in enumerate(weave._names):
 
886
            p = combined.setdefault(name, set())
 
887
            p.update(map(weave.idx_to_name, weave._parents[idx]))
 
888
    return combined
 
889
 
 
890
 
 
891
def weave_toc(w):
 
892
    """Show the weave's table-of-contents"""
 
893
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
 
894
    for i in (6, 50, 10, 10):
677
895
        print '-' * i,
678
896
    print
679
897
    for i in range(w.numversions()):
680
898
        sha1 = w._sha1s[i]
681
 
        print '%6d %40s %s' % (i, sha1, ' '.join(map(str, w._parents[i])))
682
 
 
683
 
 
684
 
 
685
 
def weave_stats(weave_file):
686
 
    from bzrlib.progress import ProgressBar
 
899
        name = w._names[i]
 
900
        parent_str = ' '.join(map(str, w._parents[i]))
 
901
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
 
902
 
 
903
 
 
904
 
 
905
def weave_stats(weave_file, pb):
687
906
    from bzrlib.weavefile import read_weave
688
907
 
689
 
    pb = ProgressBar()
690
 
 
691
908
    wf = file(weave_file, 'rb')
692
909
    w = read_weave(wf)
693
910
    # FIXME: doesn't work on pipes
697
914
    vers = len(w)
698
915
    for i in range(vers):
699
916
        pb.update('checking sizes', i, vers)
700
 
        for line in w.get_iter(i):
 
917
        for origin, lineno, line in w._extract([i]):
701
918
            total += len(line)
702
919
 
703
920
    pb.clear()
706
923
    print 'weave file        %9d bytes' % weave_size
707
924
    print 'total contents    %9d bytes' % total
708
925
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
709
 
 
 
926
    if vers:
 
927
        avg = total/vers
 
928
        print 'average size      %9d bytes' % avg
 
929
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
710
930
 
711
931
 
712
932
def usage():
721
941
        Write out specified version.
722
942
    weave check WEAVEFILE
723
943
        Check consistency of all versions.
724
 
    weave info WEAVEFILE
 
944
    weave toc WEAVEFILE
725
945
        Display table of contents.
726
 
    weave add WEAVEFILE [BASE...] < NEWTEXT
 
946
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
727
947
        Add NEWTEXT, with specified parent versions.
728
948
    weave annotate WEAVEFILE VERSION
729
949
        Display origin of each line.
731
951
        Display composite of all selected versions.
732
952
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
733
953
        Auto-merge two versions and display conflicts.
 
954
    weave diff WEAVEFILE VERSION1 VERSION2 
 
955
        Show differences between two versions.
734
956
 
735
957
example:
736
958
 
737
959
    % weave init foo.weave
738
960
    % vi foo.txt
739
 
    % weave add foo.weave < foo.txt
 
961
    % weave add foo.weave ver0 < foo.txt
740
962
    added version 0
741
963
 
742
964
    (create updated version)
743
965
    % vi foo.txt
744
966
    % weave get foo.weave 0 | diff -u - foo.txt
745
 
    % weave add foo.weave 0 < foo.txt
 
967
    % weave add foo.weave ver1 0 < foo.txt
746
968
    added version 1
747
969
 
748
970
    % weave get foo.weave 0 > foo.txt       (create forked version)
749
971
    % vi foo.txt
750
 
    % weave add foo.weave 0 < foo.txt
 
972
    % weave add foo.weave ver2 0 < foo.txt
751
973
    added version 2
752
974
 
753
975
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
754
976
    % vi foo.txt                            (resolve conflicts)
755
 
    % weave add foo.weave 1 2 < foo.txt     (commit merged version)     
 
977
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
756
978
    
757
979
"""
758
980
    
761
983
def main(argv):
762
984
    import sys
763
985
    import os
764
 
    from weavefile import write_weave, read_weave
 
986
    try:
 
987
        import bzrlib
 
988
    except ImportError:
 
989
        # in case we're run directly from the subdirectory
 
990
        sys.path.append('..')
 
991
        import bzrlib
 
992
    from bzrlib.weavefile import write_weave, read_weave
765
993
    from bzrlib.progress import ProgressBar
766
994
 
767
 
    #import psyco
768
 
    #psyco.full()
 
995
    try:
 
996
        import psyco
 
997
        psyco.full()
 
998
    except ImportError:
 
999
        pass
 
1000
 
 
1001
    if len(argv) < 2:
 
1002
        usage()
 
1003
        return 0
769
1004
 
770
1005
    cmd = argv[1]
771
1006
 
777
1012
    elif cmd == 'add':
778
1013
        w = readit()
779
1014
        # at the moment, based on everything in the file
780
 
        parents = map(int, argv[3:])
 
1015
        name = argv[3]
 
1016
        parents = map(int, argv[4:])
781
1017
        lines = sys.stdin.readlines()
782
 
        ver = w.add(parents, lines)
 
1018
        ver = w.add(name, parents, lines)
783
1019
        write_weave(w, file(argv[2], 'wb'))
784
 
        print 'added version %d' % ver
 
1020
        print 'added version %r %d' % (name, ver)
785
1021
    elif cmd == 'init':
786
1022
        fn = argv[2]
787
1023
        if os.path.exists(fn):
796
1032
        w = readit()
797
1033
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
798
1034
 
 
1035
    elif cmd == 'diff':
 
1036
        from difflib import unified_diff
 
1037
        w = readit()
 
1038
        fn = argv[2]
 
1039
        v1, v2 = map(int, argv[3:5])
 
1040
        lines1 = w.get(v1)
 
1041
        lines2 = w.get(v2)
 
1042
        diff_gen = unified_diff(lines1, lines2,
 
1043
                                '%s version %d' % (fn, v1),
 
1044
                                '%s version %d' % (fn, v2))
 
1045
        sys.stdout.writelines(diff_gen)
 
1046
            
799
1047
    elif cmd == 'annotate':
800
1048
        w = readit()
801
1049
        # newline is added to all lines regardless; too hard to get
809
1057
                print '%5d | %s' % (origin, text)
810
1058
                lasto = origin
811
1059
                
812
 
    elif cmd == 'info':
813
 
        weave_info(readit())
 
1060
    elif cmd == 'toc':
 
1061
        weave_toc(readit())
814
1062
 
815
1063
    elif cmd == 'stats':
816
 
        weave_stats(argv[2])
 
1064
        weave_stats(argv[2], ProgressBar())
817
1065
        
818
1066
    elif cmd == 'check':
819
1067
        w = readit()
865
1113
        raise ValueError('unknown command %r' % cmd)
866
1114
    
867
1115
 
 
1116
 
 
1117
def profile_main(argv): 
 
1118
    import tempfile, hotshot, hotshot.stats
 
1119
 
 
1120
    prof_f = tempfile.NamedTemporaryFile()
 
1121
 
 
1122
    prof = hotshot.Profile(prof_f.name)
 
1123
 
 
1124
    ret = prof.runcall(main, argv)
 
1125
    prof.close()
 
1126
 
 
1127
    stats = hotshot.stats.load(prof_f.name)
 
1128
    #stats.strip_dirs()
 
1129
    stats.sort_stats('cumulative')
 
1130
    ## XXX: Might like to write to stderr or the trace file instead but
 
1131
    ## print_stats seems hardcoded to stdout
 
1132
    stats.print_stats(20)
 
1133
            
 
1134
    return ret
 
1135
 
 
1136
 
 
1137
def lsprofile_main(argv): 
 
1138
    from bzrlib.lsprof import profile
 
1139
    ret,stats = profile(main, argv)
 
1140
    stats.sort()
 
1141
    stats.pprint()
 
1142
    return ret
 
1143
 
 
1144
 
868
1145
if __name__ == '__main__':
869
1146
    import sys
870
 
    sys.exit(main(sys.argv))
 
1147
    if '--profile' in sys.argv:
 
1148
        args = sys.argv[:]
 
1149
        args.remove('--profile')
 
1150
        sys.exit(profile_main(args))
 
1151
    elif '--lsprof' in sys.argv:
 
1152
        args = sys.argv[:]
 
1153
        args.remove('--lsprof')
 
1154
        sys.exit(lsprofile_main(args))
 
1155
    else:
 
1156
        sys.exit(main(sys.argv))
 
1157