/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: Jelmer Vernooij
  • Date: 2005-11-21 20:10:56 UTC
  • mto: (1185.33.40 bzr.dev)
  • mto: This revision was merged to the branch mainline in revision 1512.
  • Revision ID: jelmer@samba.org-20051121201056-b5b364b20cb58115
Don't clear Revision.parent_ids after it has been set from the arguments

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
 
 
180
    def copy(self):
 
181
        """Return a deep copy of self.
 
182
        
 
183
        The copy can be modified without affecting the original weave."""
 
184
        other = Weave()
 
185
        other._weave = self._weave[:]
 
186
        other._parents = self._parents[:]
 
187
        other._sha1s = self._sha1s[:]
 
188
        other._names = self._names[:]
 
189
        other._name_map = self._name_map.copy()
 
190
        other._weave_name = self._weave_name
 
191
        return other
173
192
 
174
193
    def __eq__(self, other):
175
194
        if not isinstance(other, Weave):
176
195
            return False
177
196
        return self._parents == other._parents \
178
 
               and self._weave == other._weave
 
197
               and self._weave == other._weave \
 
198
               and self._sha1s == other._sha1s 
 
199
 
179
200
    
180
 
 
181
201
    def __ne__(self, other):
182
202
        return not self.__eq__(other)
183
203
 
184
 
        
185
 
    def add(self, parents, text):
 
204
    def __contains__(self, name):
 
205
        return self._name_map.has_key(name)
 
206
 
 
207
    def maybe_lookup(self, name_or_index):
 
208
        """Convert possible symbolic name to index, or pass through indexes."""
 
209
        if isinstance(name_or_index, (int, long)):
 
210
            return name_or_index
 
211
        else:
 
212
            return self.lookup(name_or_index)
 
213
 
 
214
        
 
215
    def lookup(self, name):
 
216
        """Convert symbolic version name to index."""
 
217
        try:
 
218
            return self._name_map[name]
 
219
        except KeyError:
 
220
            raise WeaveRevisionNotPresent(name, self)
 
221
 
 
222
    def names(self):
 
223
        return self._names[:]
 
224
 
 
225
    def iter_names(self):
 
226
        """Yield a list of all names in this weave."""
 
227
        return iter(self._names)
 
228
 
 
229
    def idx_to_name(self, version):
 
230
        return self._names[version]
 
231
 
 
232
    def _check_repeated_add(self, name, parents, text, sha1):
 
233
        """Check that a duplicated add is OK.
 
234
 
 
235
        If it is, return the (old) index; otherwise raise an exception.
 
236
        """
 
237
        idx = self.lookup(name)
 
238
        if sorted(self._parents[idx]) != sorted(parents) \
 
239
            or sha1 != self._sha1s[idx]:
 
240
            raise WeaveRevisionAlreadyPresent(name, self)
 
241
        return idx
 
242
        
 
243
    def add(self, name, parents, text, sha1=None):
186
244
        """Add a single text on top of the weave.
187
245
  
188
246
        Returns the index number of the newly added version.
189
247
 
 
248
        name
 
249
            Symbolic name for this version.
 
250
            (Typically the revision-id of the revision that added it.)
 
251
 
190
252
        parents
191
253
            List or set of direct parent version numbers.
192
254
            
193
255
        text
194
 
            Sequence of lines to be added in the new version."""
195
 
 
 
256
            Sequence of lines to be added in the new version.
 
257
 
 
258
        sha -- SHA-1 of the file, if known.  This is trusted to be
 
259
            correct if supplied.
 
260
        """
 
261
        from bzrlib.osutils import sha_strings
 
262
 
 
263
        assert isinstance(name, basestring)
 
264
        if sha1 is None:
 
265
            sha1 = sha_strings(text)
 
266
        if name in self._name_map:
 
267
            return self._check_repeated_add(name, parents, text, sha1)
 
268
 
 
269
        parents = map(self.maybe_lookup, parents)
196
270
        self._check_versions(parents)
197
271
        ## self._check_lines(text)
198
272
        new_version = len(self._parents)
199
273
 
200
 
        import sha
201
 
        s = sha.new()
202
 
        map(s.update, text)
203
 
        sha1 = s.hexdigest()
204
 
        del s
205
274
 
206
 
        # if we abort after here the weave will be corrupt
207
 
        self._parents.append(frozenset(parents))
 
275
        # if we abort after here the (in-memory) weave will be corrupt because only
 
276
        # some fields are updated
 
277
        self._parents.append(parents[:])
208
278
        self._sha1s.append(sha1)
 
279
        self._names.append(name)
 
280
        self._name_map[name] = new_version
209
281
 
210
282
            
211
283
        if not parents:
216
288
            if text:
217
289
                self._weave.append(('{', new_version))
218
290
                self._weave.extend(text)
219
 
                self._weave.append(('}', new_version))
 
291
                self._weave.append(('}', None))
220
292
        
221
293
            return new_version
222
294
 
238
310
            basis_lineno.append(lineno)
239
311
            basis_lines.append(line)
240
312
 
241
 
        # another small special case: a merge, producing the same text as auto-merge
 
313
        # another small special case: a merge, producing the same text
 
314
        # as auto-merge
242
315
        if text == basis_lines:
243
316
            return new_version            
244
317
 
252
325
        #print 'basis_lines:', basis_lines
253
326
        #print 'new_lines:  ', lines
254
327
 
255
 
        from difflib import SequenceMatcher
256
328
        s = SequenceMatcher(None, basis_lines, text)
257
329
 
258
330
        # offset gives the number of lines that have been inserted
287
359
                # we don't destroy ourselves
288
360
                i = i2 + offset
289
361
                self._weave[i:i] = ([('{', new_version)] 
290
 
                                + text[j1:j2] 
291
 
                                + [('}', new_version)])
 
362
                                    + text[j1:j2] 
 
363
                                    + [('}', None)])
292
364
                offset += 2 + (j2 - j1)
293
365
 
294
366
        return new_version
295
367
 
 
368
    def add_identical(self, old_rev_id, new_rev_id, parents):
 
369
        """Add an identical text to old_rev_id as new_rev_id."""
 
370
        old_lines = self.get(self.lookup(old_rev_id))
 
371
        self.add(new_rev_id, parents, old_lines)
296
372
 
297
373
    def inclusions(self, versions):
298
374
        """Return set of all ancestors of given version(s)."""
299
375
        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)
 
376
        for v in xrange(max(versions), 0, -1):
 
377
            if v in i:
 
378
                # include all its parents
 
379
                i.update(self._parents[v])
 
380
        return i
 
381
        ## except IndexError:
 
382
        ##     raise ValueError("version %d not present in weave" % v)
 
383
 
 
384
 
 
385
    def parents(self, version):
 
386
        return self._parents[version]
 
387
 
 
388
 
 
389
    def parent_names(self, version):
 
390
        """Return version names for parents of a version."""
 
391
        return map(self.idx_to_name, self._parents[self.lookup(version)])
310
392
 
311
393
 
312
394
    def minimal_parents(self, version):
352
434
                raise IndexError("invalid version number %r" % i)
353
435
 
354
436
    
355
 
    def annotate(self, index):
356
 
        return list(self.annotate_iter(index))
357
 
 
358
 
 
359
 
    def annotate_iter(self, version):
 
437
    def annotate(self, name_or_index):
 
438
        return list(self.annotate_iter(name_or_index))
 
439
 
 
440
 
 
441
    def annotate_iter(self, name_or_index):
360
442
        """Yield list of (index-id, line) pairs for the specified version.
361
443
 
362
444
        The index indicates when the line originated in the weave."""
363
 
        for origin, lineno, text in self._extract([version]):
 
445
        incls = [self.maybe_lookup(name_or_index)]
 
446
        for origin, lineno, text in self._extract(incls):
364
447
            yield origin, text
365
448
 
366
 
 
367
449
    def _walk(self):
368
450
        """Walk the weave.
369
451
 
384
466
                if c == '{':
385
467
                    istack.append(v)
386
468
                elif c == '}':
387
 
                    oldv = istack.pop()
 
469
                    istack.pop()
388
470
                elif c == '[':
389
471
                    assert v not in dset
390
472
                    dset.add(v)
391
473
                elif c == ']':
392
474
                    dset.remove(v)
393
475
                else:
394
 
                    raise WeaveFormatError('unexpected instruction %r'
395
 
                                           % v)
 
476
                    raise WeaveFormatError('unexpected instruction %r' % v)
396
477
            else:
397
478
                assert isinstance(l, basestring)
398
479
                assert istack
410
491
 
411
492
        The set typically but not necessarily corresponds to a version.
412
493
        """
 
494
        for i in versions:
 
495
            if not isinstance(i, int):
 
496
                raise ValueError(i)
 
497
            
413
498
        included = self.inclusions(versions)
414
499
 
415
500
        istack = []
431
516
                    assert v not in istack
432
517
                    istack.append(v)
433
518
                elif c == '}':
434
 
                    oldv = istack.pop()
435
 
                    assert oldv == v
 
519
                    istack.pop()
436
520
                elif c == '[':
437
521
                    if v in included:
438
522
                        assert v not in dset
449
533
                if isactive:
450
534
                    result.append((istack[-1], lineno, l))
451
535
            lineno += 1
452
 
 
453
536
        if istack:
454
 
            raise WFE("unclosed insertion blocks at end of weave",
455
 
                                   istack)
 
537
            raise WeaveFormatError("unclosed insertion blocks "
 
538
                    "at end of weave: %s" % istack)
456
539
        if dset:
457
 
            raise WFE("unclosed deletion blocks at end of weave",
458
 
                                   dset)
459
 
 
 
540
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
 
541
                                   % dset)
460
542
        return result
461
 
    
462
 
 
463
 
 
464
 
    def get_iter(self, version):
 
543
 
 
544
 
 
545
    def get_iter(self, name_or_index):
465
546
        """Yield lines for the specified version."""
466
 
        for origin, lineno, line in self._extract([version]):
 
547
        incls = [self.maybe_lookup(name_or_index)]
 
548
        for origin, lineno, line in self._extract(incls):
467
549
            yield line
468
550
 
469
551
 
470
 
    def get(self, index):
471
 
        return list(self.get_iter(index))
 
552
    def get_text(self, name_or_index):
 
553
        return ''.join(self.get_iter(name_or_index))
 
554
        assert isinstance(version, int)
 
555
 
 
556
 
 
557
    def get_lines(self, name_or_index):
 
558
        return list(self.get_iter(name_or_index))
 
559
 
 
560
 
 
561
    get = get_lines
472
562
 
473
563
 
474
564
    def mash_iter(self, included):
475
565
        """Return composed version of multiple included versions."""
 
566
        included = map(self.maybe_lookup, included)
476
567
        for origin, lineno, text in self._extract(included):
477
568
            yield text
478
569
 
508
599
 
509
600
        # try extracting all versions; this is a bit slow and parallel
510
601
        # extraction could be used
511
 
        import sha
512
602
        nv = self.numversions()
513
603
        for version in range(nv):
514
604
            if progress_bar:
539
629
        If there is a chunk of the file where there's no diagreement,
540
630
        only one alternative is given.
541
631
        """
542
 
 
543
632
        # approach: find the included versions common to all the
544
633
        # merged versions
545
634
        raise NotImplementedError()
565
654
        If line1=line2, this is a pure insert; if newlines=[] this is a
566
655
        pure delete.  (Similar to difflib.)
567
656
        """
568
 
 
 
657
        raise NotImplementedError()
569
658
 
570
659
            
571
660
    def plan_merge(self, ver_a, ver_b):
634
723
                elif lines_a == lines_b:
635
724
                    for l in lines_a: yield l
636
725
                else:
637
 
                    yield '<<<<\n'
 
726
                    yield '<<<<<<<\n'
638
727
                    for l in lines_a: yield l
639
 
                    yield '====\n'
 
728
                    yield '=======\n'
640
729
                    for l in lines_b: yield l
641
 
                    yield '>>>>\n'
 
730
                    yield '>>>>>>>\n'
642
731
 
643
732
                del lines_a[:]
644
733
                del lines_b[:]
665
754
                       state
666
755
 
667
756
                
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):
 
757
    def join(self, other):
 
758
        """Integrate versions from other into this weave.
 
759
 
 
760
        The resulting weave contains all the history of both weaves; 
 
761
        any version you could retrieve from either self or other can be 
 
762
        retrieved from self after this call.
 
763
 
 
764
        It is illegal for the two weaves to contain different values 
 
765
        or different parents for any version.  See also reweave().
 
766
        """
 
767
        if other.numversions() == 0:
 
768
            return          # nothing to update, easy
 
769
        # two loops so that we do not change ourselves before verifying it
 
770
        # will be ok
 
771
        # work through in index order to make sure we get all dependencies
 
772
        for other_idx, name in enumerate(other._names):
 
773
            if self._check_version_consistent(other, other_idx, name):
 
774
                continue
 
775
        for other_idx, name in enumerate(other._names):
 
776
            # TODO: If all the parents of the other version are already 
 
777
            # present then we can avoid some work by just taking the delta
 
778
            # and adjusting the offsets.
 
779
            new_parents = self._imported_parents(other, other_idx)
 
780
            lines = other.get_lines(other_idx)
 
781
            sha1 = other._sha1s[other_idx]
 
782
            self.add(name, new_parents, lines, sha1)
 
783
 
 
784
 
 
785
    def _imported_parents(self, other, other_idx):
 
786
        """Return list of parents in self corresponding to indexes in other."""
 
787
        new_parents = []
 
788
        for parent_idx in other._parents[other_idx]:
 
789
            parent_name = other._names[parent_idx]
 
790
            if parent_name not in self._names:
 
791
                # should not be possible
 
792
                raise WeaveError("missing parent {%s} of {%s} in %r" 
 
793
                                 % (parent_name, other._name_map[other_idx], self))
 
794
            new_parents.append(self._name_map[parent_name])
 
795
        return new_parents
 
796
 
 
797
    def _check_version_consistent(self, other, other_idx, name):
 
798
        """Check if a version in consistent in this and other.
 
799
 
 
800
        To be consistent it must have:
 
801
 
 
802
         * the same text
 
803
         * the same direct parents (by name, not index, and disregarding
 
804
           order)
 
805
        
 
806
        If present & correct return True;
 
807
        if not present in self return False; 
 
808
        if inconsistent raise error."""
 
809
        this_idx = self._name_map.get(name, -1)
 
810
        if this_idx != -1:
 
811
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
 
812
                raise WeaveError("inconsistent texts for version {%s} "
 
813
                                 "when joining weaves"
 
814
                                 % (name))
 
815
            self_parents = self._parents[this_idx]
 
816
            other_parents = other._parents[other_idx]
 
817
            n1 = [self._names[i] for i in self_parents]
 
818
            n2 = [other._names[i] for i in other_parents]
 
819
            n1.sort()
 
820
            n2.sort()
 
821
            if n1 != n2:
 
822
                raise WeaveParentMismatch("inconsistent parents "
 
823
                    "for version {%s}: %s vs %s" % (name, n1, n2))
 
824
            else:
 
825
                return True         # ok!
 
826
        else:
 
827
            return False
 
828
 
 
829
    def reweave(self, other):
 
830
        """Reweave self with other."""
 
831
        new_weave = reweave(self, other)
 
832
        for attr in self.__slots__:
 
833
            setattr(self, attr, getattr(new_weave, attr))
 
834
 
 
835
 
 
836
def reweave(wa, wb):
 
837
    """Combine two weaves and return the result.
 
838
 
 
839
    This works even if a revision R has different parents in 
 
840
    wa and wb.  In the resulting weave all the parents are given.
 
841
 
 
842
    This is done by just building up a new weave, maintaining ordering 
 
843
    of the versions in the two inputs.  More efficient approaches
 
844
    might be possible but it should only be necessary to do 
 
845
    this operation rarely, when a new previously ghost version is 
 
846
    inserted.
 
847
    """
 
848
    wr = Weave()
 
849
    ia = ib = 0
 
850
    queue_a = range(wa.numversions())
 
851
    queue_b = range(wb.numversions())
 
852
    # first determine combined parents of all versions
 
853
    # map from version name -> all parent names
 
854
    combined_parents = _reweave_parent_graphs(wa, wb)
 
855
    mutter("combined parents: %r", combined_parents)
 
856
    order = topo_sort(combined_parents.iteritems())
 
857
    mutter("order to reweave: %r", order)
 
858
    for name in order:
 
859
        if name in wa._name_map:
 
860
            lines = wa.get_lines(name)
 
861
            if name in wb._name_map:
 
862
                assert lines == wb.get_lines(name)
 
863
        else:
 
864
            lines = wb.get_lines(name)
 
865
        wr.add(name, combined_parents[name], lines)
 
866
    return wr
 
867
 
 
868
 
 
869
def _reweave_parent_graphs(wa, wb):
 
870
    """Return combined parent ancestry for two weaves.
 
871
    
 
872
    Returned as a list of (version_name, set(parent_names))"""
 
873
    combined = {}
 
874
    for weave in [wa, wb]:
 
875
        for idx, name in enumerate(weave._names):
 
876
            p = combined.setdefault(name, set())
 
877
            p.update(map(weave.idx_to_name, weave._parents[idx]))
 
878
    return combined
 
879
 
 
880
 
 
881
def weave_toc(w):
 
882
    """Show the weave's table-of-contents"""
 
883
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
 
884
    for i in (6, 50, 10, 10):
677
885
        print '-' * i,
678
886
    print
679
887
    for i in range(w.numversions()):
680
888
        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
 
889
        name = w._names[i]
 
890
        parent_str = ' '.join(map(str, w._parents[i]))
 
891
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
 
892
 
 
893
 
 
894
 
 
895
def weave_stats(weave_file, pb):
687
896
    from bzrlib.weavefile import read_weave
688
897
 
689
 
    pb = ProgressBar()
690
 
 
691
898
    wf = file(weave_file, 'rb')
692
899
    w = read_weave(wf)
693
900
    # FIXME: doesn't work on pipes
697
904
    vers = len(w)
698
905
    for i in range(vers):
699
906
        pb.update('checking sizes', i, vers)
700
 
        for line in w.get_iter(i):
 
907
        for origin, lineno, line in w._extract([i]):
701
908
            total += len(line)
702
909
 
703
910
    pb.clear()
706
913
    print 'weave file        %9d bytes' % weave_size
707
914
    print 'total contents    %9d bytes' % total
708
915
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
709
 
 
 
916
    if vers:
 
917
        avg = total/vers
 
918
        print 'average size      %9d bytes' % avg
 
919
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
710
920
 
711
921
 
712
922
def usage():
721
931
        Write out specified version.
722
932
    weave check WEAVEFILE
723
933
        Check consistency of all versions.
724
 
    weave info WEAVEFILE
 
934
    weave toc WEAVEFILE
725
935
        Display table of contents.
726
 
    weave add WEAVEFILE [BASE...] < NEWTEXT
 
936
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
727
937
        Add NEWTEXT, with specified parent versions.
728
938
    weave annotate WEAVEFILE VERSION
729
939
        Display origin of each line.
731
941
        Display composite of all selected versions.
732
942
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
733
943
        Auto-merge two versions and display conflicts.
 
944
    weave diff WEAVEFILE VERSION1 VERSION2 
 
945
        Show differences between two versions.
734
946
 
735
947
example:
736
948
 
737
949
    % weave init foo.weave
738
950
    % vi foo.txt
739
 
    % weave add foo.weave < foo.txt
 
951
    % weave add foo.weave ver0 < foo.txt
740
952
    added version 0
741
953
 
742
954
    (create updated version)
743
955
    % vi foo.txt
744
956
    % weave get foo.weave 0 | diff -u - foo.txt
745
 
    % weave add foo.weave 0 < foo.txt
 
957
    % weave add foo.weave ver1 0 < foo.txt
746
958
    added version 1
747
959
 
748
960
    % weave get foo.weave 0 > foo.txt       (create forked version)
749
961
    % vi foo.txt
750
 
    % weave add foo.weave 0 < foo.txt
 
962
    % weave add foo.weave ver2 0 < foo.txt
751
963
    added version 2
752
964
 
753
965
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
754
966
    % vi foo.txt                            (resolve conflicts)
755
 
    % weave add foo.weave 1 2 < foo.txt     (commit merged version)     
 
967
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
756
968
    
757
969
"""
758
970
    
761
973
def main(argv):
762
974
    import sys
763
975
    import os
764
 
    from weavefile import write_weave, read_weave
 
976
    try:
 
977
        import bzrlib
 
978
    except ImportError:
 
979
        # in case we're run directly from the subdirectory
 
980
        sys.path.append('..')
 
981
        import bzrlib
 
982
    from bzrlib.weavefile import write_weave, read_weave
765
983
    from bzrlib.progress import ProgressBar
766
984
 
767
 
    #import psyco
768
 
    #psyco.full()
 
985
    try:
 
986
        import psyco
 
987
        psyco.full()
 
988
    except ImportError:
 
989
        pass
 
990
 
 
991
    if len(argv) < 2:
 
992
        usage()
 
993
        return 0
769
994
 
770
995
    cmd = argv[1]
771
996
 
777
1002
    elif cmd == 'add':
778
1003
        w = readit()
779
1004
        # at the moment, based on everything in the file
780
 
        parents = map(int, argv[3:])
 
1005
        name = argv[3]
 
1006
        parents = map(int, argv[4:])
781
1007
        lines = sys.stdin.readlines()
782
 
        ver = w.add(parents, lines)
 
1008
        ver = w.add(name, parents, lines)
783
1009
        write_weave(w, file(argv[2], 'wb'))
784
 
        print 'added version %d' % ver
 
1010
        print 'added version %r %d' % (name, ver)
785
1011
    elif cmd == 'init':
786
1012
        fn = argv[2]
787
1013
        if os.path.exists(fn):
796
1022
        w = readit()
797
1023
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
798
1024
 
 
1025
    elif cmd == 'diff':
 
1026
        from difflib import unified_diff
 
1027
        w = readit()
 
1028
        fn = argv[2]
 
1029
        v1, v2 = map(int, argv[3:5])
 
1030
        lines1 = w.get(v1)
 
1031
        lines2 = w.get(v2)
 
1032
        diff_gen = unified_diff(lines1, lines2,
 
1033
                                '%s version %d' % (fn, v1),
 
1034
                                '%s version %d' % (fn, v2))
 
1035
        sys.stdout.writelines(diff_gen)
 
1036
            
799
1037
    elif cmd == 'annotate':
800
1038
        w = readit()
801
1039
        # newline is added to all lines regardless; too hard to get
809
1047
                print '%5d | %s' % (origin, text)
810
1048
                lasto = origin
811
1049
                
812
 
    elif cmd == 'info':
813
 
        weave_info(readit())
 
1050
    elif cmd == 'toc':
 
1051
        weave_toc(readit())
814
1052
 
815
1053
    elif cmd == 'stats':
816
 
        weave_stats(argv[2])
 
1054
        weave_stats(argv[2], ProgressBar())
817
1055
        
818
1056
    elif cmd == 'check':
819
1057
        w = readit()
865
1103
        raise ValueError('unknown command %r' % cmd)
866
1104
    
867
1105
 
 
1106
 
 
1107
def profile_main(argv): 
 
1108
    import tempfile, hotshot, hotshot.stats
 
1109
 
 
1110
    prof_f = tempfile.NamedTemporaryFile()
 
1111
 
 
1112
    prof = hotshot.Profile(prof_f.name)
 
1113
 
 
1114
    ret = prof.runcall(main, argv)
 
1115
    prof.close()
 
1116
 
 
1117
    stats = hotshot.stats.load(prof_f.name)
 
1118
    #stats.strip_dirs()
 
1119
    stats.sort_stats('cumulative')
 
1120
    ## XXX: Might like to write to stderr or the trace file instead but
 
1121
    ## print_stats seems hardcoded to stdout
 
1122
    stats.print_stats(20)
 
1123
            
 
1124
    return ret
 
1125
 
 
1126
 
868
1127
if __name__ == '__main__':
869
1128
    import sys
870
 
    sys.exit(main(sys.argv))
 
1129
    if '--profile' in sys.argv:
 
1130
        args = sys.argv[:]
 
1131
        args.remove('--profile')
 
1132
        sys.exit(profile_main(args))
 
1133
    else:
 
1134
        sys.exit(main(sys.argv))
 
1135