/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: Martin Pool
  • Date: 2006-02-17 20:34:30 UTC
  • mto: This revision was merged to the branch mainline in revision 1569.
  • Revision ID: mbp@sourcefrog.net-20060217203430-d15f555c71a6c0cd
New utility routine rand_chars

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 os
 
71
import sha
 
72
from difflib import SequenceMatcher
 
73
 
 
74
from bzrlib.trace import mutter
 
75
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
 
76
        WeaveRevisionNotPresent, WeaveRevisionAlreadyPresent)
 
77
import bzrlib.errors as errors
 
78
from bzrlib.tsort import topo_sort
 
79
 
88
80
 
89
81
class Weave(object):
90
82
    """weave - versioned text file storage.
118
110
    The instruction can be '{' or '}' for an insertion block, and '['
119
111
    and ']' for a deletion block respectively.  The version is the
120
112
    integer version index.  There is no replace operator, only deletes
121
 
    and inserts.
 
113
    and inserts.  For '}', the end of an insertion, there is no
 
114
    version parameter because it always closes the most recently
 
115
    opened insertion.
122
116
 
123
117
    Constraints/notes:
124
118
 
160
154
        each version; the parent's parents are implied.
161
155
 
162
156
    _sha1s
163
 
        List of hex SHA-1 of each version, or None if not recorded.
 
157
        List of hex SHA-1 of each version.
 
158
 
 
159
    _names
 
160
        List of symbolic names for each version.  Each should be unique.
 
161
 
 
162
    _name_map
 
163
        For each name, the version number.
 
164
 
 
165
    _weave_name
 
166
        Descriptive name of this weave; typically the filename if known.
 
167
        Set by read_weave.
164
168
    """
165
169
 
166
 
    __slots__ = ['_weave', '_parents', '_sha1s']
 
170
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
 
171
                 '_weave_name']
167
172
    
168
 
    def __init__(self):
 
173
    def __init__(self, weave_name=None):
169
174
        self._weave = []
170
175
        self._parents = []
171
176
        self._sha1s = []
172
 
 
 
177
        self._names = []
 
178
        self._name_map = {}
 
179
        self._weave_name = weave_name
 
180
 
 
181
    def __repr__(self):
 
182
        return "Weave(%r)" % self._weave_name
 
183
 
 
184
 
 
185
    def copy(self):
 
186
        """Return a deep copy of self.
 
187
        
 
188
        The copy can be modified without affecting the original weave."""
 
189
        other = Weave()
 
190
        other._weave = self._weave[:]
 
191
        other._parents = self._parents[:]
 
192
        other._sha1s = self._sha1s[:]
 
193
        other._names = self._names[:]
 
194
        other._name_map = self._name_map.copy()
 
195
        other._weave_name = self._weave_name
 
196
        return other
173
197
 
174
198
    def __eq__(self, other):
175
199
        if not isinstance(other, Weave):
176
200
            return False
177
201
        return self._parents == other._parents \
178
 
               and self._weave == other._weave
 
202
               and self._weave == other._weave \
 
203
               and self._sha1s == other._sha1s 
 
204
 
179
205
    
180
 
 
181
206
    def __ne__(self, other):
182
207
        return not self.__eq__(other)
183
208
 
184
 
        
185
 
    def add(self, parents, text):
 
209
    def __contains__(self, name):
 
210
        return self._name_map.has_key(name)
 
211
 
 
212
    def maybe_lookup(self, name_or_index):
 
213
        """Convert possible symbolic name to index, or pass through indexes."""
 
214
        if isinstance(name_or_index, (int, long)):
 
215
            return name_or_index
 
216
        else:
 
217
            return self.lookup(name_or_index)
 
218
 
 
219
        
 
220
    def lookup(self, name):
 
221
        """Convert symbolic version name to index."""
 
222
        try:
 
223
            return self._name_map[name]
 
224
        except KeyError:
 
225
            raise WeaveRevisionNotPresent(name, self)
 
226
 
 
227
    def names(self):
 
228
        return self._names[:]
 
229
 
 
230
    def iter_names(self):
 
231
        """Yield a list of all names in this weave."""
 
232
        return iter(self._names)
 
233
 
 
234
    def idx_to_name(self, version):
 
235
        return self._names[version]
 
236
 
 
237
    def _check_repeated_add(self, name, parents, text, sha1):
 
238
        """Check that a duplicated add is OK.
 
239
 
 
240
        If it is, return the (old) index; otherwise raise an exception.
 
241
        """
 
242
        idx = self.lookup(name)
 
243
        if sorted(self._parents[idx]) != sorted(parents) \
 
244
            or sha1 != self._sha1s[idx]:
 
245
            raise WeaveRevisionAlreadyPresent(name, self)
 
246
        return idx
 
247
        
 
248
    def add(self, name, parents, text, sha1=None):
186
249
        """Add a single text on top of the weave.
187
250
  
188
251
        Returns the index number of the newly added version.
189
252
 
 
253
        name
 
254
            Symbolic name for this version.
 
255
            (Typically the revision-id of the revision that added it.)
 
256
 
190
257
        parents
191
258
            List or set of direct parent version numbers.
192
259
            
193
260
        text
194
 
            Sequence of lines to be added in the new version."""
195
 
 
 
261
            Sequence of lines to be added in the new version.
 
262
 
 
263
        sha -- SHA-1 of the file, if known.  This is trusted to be
 
264
            correct if supplied.
 
265
        """
 
266
        from bzrlib.osutils import sha_strings
 
267
 
 
268
        assert isinstance(name, basestring)
 
269
        if sha1 is None:
 
270
            sha1 = sha_strings(text)
 
271
        if name in self._name_map:
 
272
            return self._check_repeated_add(name, parents, text, sha1)
 
273
 
 
274
        parents = map(self.maybe_lookup, parents)
196
275
        self._check_versions(parents)
197
276
        ## self._check_lines(text)
198
277
        new_version = len(self._parents)
199
278
 
200
 
        import sha
201
 
        s = sha.new()
202
 
        map(s.update, text)
203
 
        sha1 = s.hexdigest()
204
 
        del s
205
279
 
206
 
        # if we abort after here the weave will be corrupt
207
 
        self._parents.append(frozenset(parents))
 
280
        # if we abort after here the (in-memory) weave will be corrupt because only
 
281
        # some fields are updated
 
282
        self._parents.append(parents[:])
208
283
        self._sha1s.append(sha1)
 
284
        self._names.append(name)
 
285
        self._name_map[name] = new_version
209
286
 
210
287
            
211
288
        if not parents:
216
293
            if text:
217
294
                self._weave.append(('{', new_version))
218
295
                self._weave.extend(text)
219
 
                self._weave.append(('}', new_version))
 
296
                self._weave.append(('}', None))
220
297
        
221
298
            return new_version
222
299
 
238
315
            basis_lineno.append(lineno)
239
316
            basis_lines.append(line)
240
317
 
241
 
        # another small special case: a merge, producing the same text as auto-merge
 
318
        # another small special case: a merge, producing the same text
 
319
        # as auto-merge
242
320
        if text == basis_lines:
243
321
            return new_version            
244
322
 
252
330
        #print 'basis_lines:', basis_lines
253
331
        #print 'new_lines:  ', lines
254
332
 
255
 
        from difflib import SequenceMatcher
256
333
        s = SequenceMatcher(None, basis_lines, text)
257
334
 
258
335
        # offset gives the number of lines that have been inserted
287
364
                # we don't destroy ourselves
288
365
                i = i2 + offset
289
366
                self._weave[i:i] = ([('{', new_version)] 
290
 
                                + text[j1:j2] 
291
 
                                + [('}', new_version)])
 
367
                                    + text[j1:j2] 
 
368
                                    + [('}', None)])
292
369
                offset += 2 + (j2 - j1)
293
370
 
294
371
        return new_version
295
372
 
 
373
    def add_identical(self, old_rev_id, new_rev_id, parents):
 
374
        """Add an identical text to old_rev_id as new_rev_id."""
 
375
        old_lines = self.get(self.lookup(old_rev_id))
 
376
        self.add(new_rev_id, parents, old_lines)
296
377
 
297
378
    def inclusions(self, versions):
298
379
        """Return set of all ancestors of given version(s)."""
299
380
        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)
 
381
        for v in xrange(max(versions), 0, -1):
 
382
            if v in i:
 
383
                # include all its parents
 
384
                i.update(self._parents[v])
 
385
        return i
 
386
        ## except IndexError:
 
387
        ##     raise ValueError("version %d not present in weave" % v)
 
388
 
 
389
 
 
390
    def parents(self, version):
 
391
        return self._parents[version]
 
392
 
 
393
 
 
394
    def parent_names(self, version):
 
395
        """Return version names for parents of a version."""
 
396
        return map(self.idx_to_name, self._parents[self.lookup(version)])
310
397
 
311
398
 
312
399
    def minimal_parents(self, version):
352
439
                raise IndexError("invalid version number %r" % i)
353
440
 
354
441
    
355
 
    def annotate(self, index):
356
 
        return list(self.annotate_iter(index))
357
 
 
358
 
 
359
 
    def annotate_iter(self, version):
 
442
    def annotate(self, name_or_index):
 
443
        return list(self.annotate_iter(name_or_index))
 
444
 
 
445
 
 
446
    def annotate_iter(self, name_or_index):
360
447
        """Yield list of (index-id, line) pairs for the specified version.
361
448
 
362
449
        The index indicates when the line originated in the weave."""
363
 
        for origin, lineno, text in self._extract([version]):
 
450
        incls = [self.maybe_lookup(name_or_index)]
 
451
        for origin, lineno, text in self._extract(incls):
364
452
            yield origin, text
365
453
 
366
 
 
367
454
    def _walk(self):
368
455
        """Walk the weave.
369
456
 
384
471
                if c == '{':
385
472
                    istack.append(v)
386
473
                elif c == '}':
387
 
                    oldv = istack.pop()
 
474
                    istack.pop()
388
475
                elif c == '[':
389
476
                    assert v not in dset
390
477
                    dset.add(v)
391
478
                elif c == ']':
392
479
                    dset.remove(v)
393
480
                else:
394
 
                    raise WeaveFormatError('unexpected instruction %r'
395
 
                                           % v)
 
481
                    raise WeaveFormatError('unexpected instruction %r' % v)
396
482
            else:
397
483
                assert isinstance(l, basestring)
398
484
                assert istack
399
485
                yield lineno, istack[-1], dset, l
400
486
            lineno += 1
401
487
 
402
 
 
 
488
        if istack:
 
489
            raise WeaveFormatError("unclosed insertion blocks "
 
490
                    "at end of weave: %s" % istack)
 
491
        if dset:
 
492
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
 
493
                                   % dset)
403
494
 
404
495
    def _extract(self, versions):
405
496
        """Yield annotation of lines in included set.
410
501
 
411
502
        The set typically but not necessarily corresponds to a version.
412
503
        """
 
504
        for i in versions:
 
505
            if not isinstance(i, int):
 
506
                raise ValueError(i)
 
507
            
413
508
        included = self.inclusions(versions)
414
509
 
415
510
        istack = []
431
526
                    assert v not in istack
432
527
                    istack.append(v)
433
528
                elif c == '}':
434
 
                    oldv = istack.pop()
435
 
                    assert oldv == v
 
529
                    istack.pop()
436
530
                elif c == '[':
437
531
                    if v in included:
438
532
                        assert v not in dset
449
543
                if isactive:
450
544
                    result.append((istack[-1], lineno, l))
451
545
            lineno += 1
452
 
 
453
546
        if istack:
454
 
            raise WFE("unclosed insertion blocks at end of weave",
455
 
                                   istack)
 
547
            raise WeaveFormatError("unclosed insertion blocks "
 
548
                    "at end of weave: %s" % istack)
456
549
        if dset:
457
 
            raise WFE("unclosed deletion blocks at end of weave",
458
 
                                   dset)
459
 
 
 
550
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
 
551
                                   % dset)
460
552
        return result
461
 
    
462
 
 
463
 
 
464
 
    def get_iter(self, version):
 
553
 
 
554
 
 
555
    def get_iter(self, name_or_index):
465
556
        """Yield lines for the specified version."""
466
 
        for origin, lineno, line in self._extract([version]):
 
557
        incls = [self.maybe_lookup(name_or_index)]
 
558
        if len(incls) == 1:
 
559
            index = incls[0]
 
560
            cur_sha = sha.new()
 
561
        else:
 
562
            # We don't have sha1 sums for multiple entries
 
563
            cur_sha = None
 
564
        for origin, lineno, line in self._extract(incls):
 
565
            if cur_sha:
 
566
                cur_sha.update(line)
467
567
            yield line
468
 
 
469
 
 
470
 
    def get(self, index):
471
 
        return list(self.get_iter(index))
472
 
 
 
568
        if cur_sha:
 
569
            expected_sha1 = self._sha1s[index]
 
570
            measured_sha1 = cur_sha.hexdigest() 
 
571
            if measured_sha1 != expected_sha1:
 
572
                raise errors.WeaveInvalidChecksum(
 
573
                        'file %s, revision %s, expected: %s, measured %s' 
 
574
                        % (self._weave_name, self._names[index],
 
575
                           expected_sha1, measured_sha1))
 
576
 
 
577
 
 
578
    def get_text(self, name_or_index):
 
579
        return ''.join(self.get_iter(name_or_index))
 
580
        assert isinstance(version, int)
 
581
 
 
582
 
 
583
    def get_lines(self, name_or_index):
 
584
        return list(self.get_iter(name_or_index))
 
585
 
 
586
 
 
587
    get = get_lines
 
588
 
 
589
 
 
590
    def get_sha1(self, name):
 
591
        """Get the stored sha1 sum for the given revision.
 
592
        
 
593
        :param name: The name of the version to lookup
 
594
        """
 
595
        return self._sha1s[self.lookup(name)]
473
596
 
474
597
    def mash_iter(self, included):
475
598
        """Return composed version of multiple included versions."""
 
599
        included = map(self.maybe_lookup, included)
476
600
        for origin, lineno, text in self._extract(included):
477
601
            yield text
478
602
 
495
619
    def __len__(self):
496
620
        return self.numversions()
497
621
 
498
 
 
499
622
    def check(self, progress_bar=None):
500
623
        # check no circular inclusions
501
624
        for version in range(self.numversions()):
506
629
                    raise WeaveFormatError("invalid included version %d for index %d"
507
630
                                           % (inclusions[-1], version))
508
631
 
509
 
        # try extracting all versions; this is a bit slow and parallel
510
 
        # extraction could be used
511
 
        import sha
 
632
        # try extracting all versions; parallel extraction is used
512
633
        nv = self.numversions()
 
634
        sha1s = [sha.new() for i in range(nv)]
 
635
        texts = [[] for i in range(nv)]
 
636
        inclusions = []
 
637
        for i in range(nv):
 
638
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
 
639
            # The problem is that set membership is much more expensive
 
640
            new_inc = set([i])
 
641
            for p in self._parents[i]:
 
642
                new_inc.update(inclusions[p])
 
643
 
 
644
            #assert set(new_inc) == self.inclusions([i]), 'failed %s != %s' % (new_inc, self.inclusions([i]))
 
645
            inclusions.append(new_inc)
 
646
 
 
647
        nlines = len(self._weave)
 
648
 
 
649
        update_text = 'checking weave'
 
650
        if self._weave_name:
 
651
            short_name = os.path.basename(self._weave_name)
 
652
            update_text = 'checking %s' % (short_name,)
 
653
            update_text = update_text[:25]
 
654
 
 
655
        for lineno, insert, deleteset, line in self._walk():
 
656
            if progress_bar:
 
657
                progress_bar.update(update_text, lineno, nlines)
 
658
 
 
659
            for j, j_inc in enumerate(inclusions):
 
660
                # The active inclusion must be an ancestor,
 
661
                # and no ancestors must have deleted this line,
 
662
                # because we don't support resurrection.
 
663
                if (insert in j_inc) and not (deleteset & j_inc):
 
664
                    sha1s[j].update(line)
 
665
 
513
666
        for version in range(nv):
514
 
            if progress_bar:
515
 
                progress_bar.update('checking text', version, nv)
516
 
            s = sha.new()
517
 
            for l in self.get_iter(version):
518
 
                s.update(l)
519
 
            hd = s.hexdigest()
 
667
            hd = sha1s[version].hexdigest()
520
668
            expected = self._sha1s[version]
521
669
            if hd != expected:
522
 
                raise WeaveError("mismatched sha1 for version %d; "
523
 
                                 "got %s, expected %s"
524
 
                                 % (version, hd, expected))
 
670
                raise errors.WeaveInvalidChecksum(
 
671
                        "mismatched sha1 for version %s: "
 
672
                        "got %s, expected %s"
 
673
                        % (self._names[version], hd, expected))
525
674
 
526
675
        # TODO: check insertions are properly nested, that there are
527
676
        # no lines outside of insertion blocks, that deletions are
528
677
        # properly paired, etc.
529
678
 
530
 
 
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
679
    def _delta(self, included, lines):
550
680
        """Return changes from basis to new revision.
551
681
 
565
695
        If line1=line2, this is a pure insert; if newlines=[] this is a
566
696
        pure delete.  (Similar to difflib.)
567
697
        """
568
 
 
 
698
        raise NotImplementedError()
569
699
 
570
700
            
571
701
    def plan_merge(self, ver_a, ver_b):
620
750
        lines_a = []
621
751
        lines_b = []
622
752
        ch_a = ch_b = False
623
 
 
 
753
        # TODO: Return a structured form of the conflicts (e.g. 2-tuples for
 
754
        # conflicted regions), rather than just inserting the markers.
 
755
        # 
 
756
        # TODO: Show some version information (e.g. author, date) on 
 
757
        # conflicted regions.
624
758
        for state, line in plan:
625
759
            if state == 'unchanged' or state == 'killed-both':
626
760
                # resync and flush queued conflicts changes if any
634
768
                elif lines_a == lines_b:
635
769
                    for l in lines_a: yield l
636
770
                else:
637
 
                    yield '<<<<\n'
 
771
                    yield '<<<<<<<\n'
638
772
                    for l in lines_a: yield l
639
 
                    yield '====\n'
 
773
                    yield '=======\n'
640
774
                    for l in lines_b: yield l
641
 
                    yield '>>>>\n'
 
775
                    yield '>>>>>>>\n'
642
776
 
643
777
                del lines_a[:]
644
778
                del lines_b[:]
664
798
                                 'killed-both'), \
665
799
                       state
666
800
 
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):
 
801
 
 
802
    def join(self, other, pb=None, msg=None):
 
803
        import sys, time
 
804
        """Integrate versions from other into this weave.
 
805
 
 
806
        The resulting weave contains all the history of both weaves; 
 
807
        any version you could retrieve from either self or other can be 
 
808
        retrieved from self after this call.
 
809
 
 
810
        It is illegal for the two weaves to contain different values 
 
811
        or different parents for any version.  See also reweave().
 
812
 
 
813
        :param other: The other weave to pull into this one
 
814
        :param pb: An optional progress bar
 
815
        :param msg: An optional message to display for progress
 
816
        """
 
817
        if other.numversions() == 0:
 
818
            return          # nothing to update, easy
 
819
        # two loops so that we do not change ourselves before verifying it
 
820
        # will be ok
 
821
        # work through in index order to make sure we get all dependencies
 
822
        for other_idx, name in enumerate(other._names):
 
823
            self._check_version_consistent(other, other_idx, name)
 
824
 
 
825
        if pb and not msg:
 
826
            msg = 'weave join'
 
827
 
 
828
        merged = 0
 
829
        processed = 0
 
830
        time0 = time.time( )
 
831
        for other_idx, name in enumerate(other._names):
 
832
            # TODO: If all the parents of the other version are already
 
833
            # present then we can avoid some work by just taking the delta
 
834
            # and adjusting the offsets.
 
835
            new_parents = self._imported_parents(other, other_idx)
 
836
            sha1 = other._sha1s[other_idx]
 
837
 
 
838
            processed += 1
 
839
 
 
840
            if name in self._name_map:
 
841
                idx = self.lookup(name)
 
842
                n1 = set(map(other.idx_to_name, other._parents[other_idx]))
 
843
                n2 = set(map(self.idx_to_name, self._parents[idx]))
 
844
                if sha1 ==  self._sha1s[idx] and n1 == n2:
 
845
                        continue
 
846
 
 
847
            if pb:
 
848
                pb.update(msg, other_idx, len(other._names))
 
849
           
 
850
            merged += 1
 
851
            lines = other.get_lines(other_idx)
 
852
            self.add(name, new_parents, lines, sha1)
 
853
 
 
854
        mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
 
855
                merged,processed,self._weave_name, time.time( )-time0))
 
856
 
 
857
 
 
858
 
 
859
 
 
860
    def _imported_parents(self, other, other_idx):
 
861
        """Return list of parents in self corresponding to indexes in other."""
 
862
        new_parents = []
 
863
        for parent_idx in other._parents[other_idx]:
 
864
            parent_name = other._names[parent_idx]
 
865
            if parent_name not in self._names:
 
866
                # should not be possible
 
867
                raise WeaveError("missing parent {%s} of {%s} in %r" 
 
868
                                 % (parent_name, other._name_map[other_idx], self))
 
869
            new_parents.append(self._name_map[parent_name])
 
870
        return new_parents
 
871
 
 
872
    def _check_version_consistent(self, other, other_idx, name):
 
873
        """Check if a version in consistent in this and other.
 
874
 
 
875
        To be consistent it must have:
 
876
 
 
877
         * the same text
 
878
         * the same direct parents (by name, not index, and disregarding
 
879
           order)
 
880
        
 
881
        If present & correct return True;
 
882
        if not present in self return False; 
 
883
        if inconsistent raise error."""
 
884
        this_idx = self._name_map.get(name, -1)
 
885
        if this_idx != -1:
 
886
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
 
887
                raise WeaveError("inconsistent texts for version {%s} "
 
888
                                 "when joining weaves"
 
889
                                 % (name))
 
890
            self_parents = self._parents[this_idx]
 
891
            other_parents = other._parents[other_idx]
 
892
            n1 = set([self._names[i] for i in self_parents])
 
893
            n2 = set([other._names[i] for i in other_parents])
 
894
            if n1 != n2:
 
895
                raise WeaveParentMismatch("inconsistent parents "
 
896
                    "for version {%s}: %s vs %s" % (name, n1, n2))
 
897
            else:
 
898
                return True         # ok!
 
899
        else:
 
900
            return False
 
901
 
 
902
    def reweave(self, other, pb=None, msg=None):
 
903
        """Reweave self with other.
 
904
 
 
905
        :param other: The other weave to merge
 
906
        :param pb: An optional progress bar, indicating how far done we are
 
907
        :param msg: An optional message for the progress
 
908
        """
 
909
        new_weave = reweave(self, other, pb=pb, msg=msg)
 
910
        for attr in self.__slots__:
 
911
            setattr(self, attr, getattr(new_weave, attr))
 
912
 
 
913
 
 
914
def reweave(wa, wb, pb=None, msg=None):
 
915
    """Combine two weaves and return the result.
 
916
 
 
917
    This works even if a revision R has different parents in 
 
918
    wa and wb.  In the resulting weave all the parents are given.
 
919
 
 
920
    This is done by just building up a new weave, maintaining ordering 
 
921
    of the versions in the two inputs.  More efficient approaches
 
922
    might be possible but it should only be necessary to do 
 
923
    this operation rarely, when a new previously ghost version is 
 
924
    inserted.
 
925
 
 
926
    :param pb: An optional progress bar, indicating how far done we are
 
927
    :param msg: An optional message for the progress
 
928
    """
 
929
    wr = Weave()
 
930
    ia = ib = 0
 
931
    queue_a = range(wa.numversions())
 
932
    queue_b = range(wb.numversions())
 
933
    # first determine combined parents of all versions
 
934
    # map from version name -> all parent names
 
935
    combined_parents = _reweave_parent_graphs(wa, wb)
 
936
    mutter("combined parents: %r", combined_parents)
 
937
    order = topo_sort(combined_parents.iteritems())
 
938
    mutter("order to reweave: %r", order)
 
939
 
 
940
    if pb and not msg:
 
941
        msg = 'reweave'
 
942
 
 
943
    for idx, name in enumerate(order):
 
944
        if pb:
 
945
            pb.update(msg, idx, len(order))
 
946
        if name in wa._name_map:
 
947
            lines = wa.get_lines(name)
 
948
            if name in wb._name_map:
 
949
                lines_b = wb.get_lines(name)
 
950
                if lines != lines_b:
 
951
                    mutter('Weaves differ on content. rev_id {%s}', name)
 
952
                    mutter('weaves: %s, %s', wa._weave_name, wb._weave_name)
 
953
                    import difflib
 
954
                    lines = list(difflib.unified_diff(lines, lines_b,
 
955
                            wa._weave_name, wb._weave_name))
 
956
                    mutter('lines:\n%s', ''.join(lines))
 
957
                    raise errors.WeaveTextDiffers(name, wa, wb)
 
958
        else:
 
959
            lines = wb.get_lines(name)
 
960
        wr.add(name, combined_parents[name], lines)
 
961
    return wr
 
962
 
 
963
 
 
964
def _reweave_parent_graphs(wa, wb):
 
965
    """Return combined parent ancestry for two weaves.
 
966
    
 
967
    Returned as a list of (version_name, set(parent_names))"""
 
968
    combined = {}
 
969
    for weave in [wa, wb]:
 
970
        for idx, name in enumerate(weave._names):
 
971
            p = combined.setdefault(name, set())
 
972
            p.update(map(weave.idx_to_name, weave._parents[idx]))
 
973
    return combined
 
974
 
 
975
 
 
976
def weave_toc(w):
 
977
    """Show the weave's table-of-contents"""
 
978
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
 
979
    for i in (6, 50, 10, 10):
677
980
        print '-' * i,
678
981
    print
679
982
    for i in range(w.numversions()):
680
983
        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
 
984
        name = w._names[i]
 
985
        parent_str = ' '.join(map(str, w._parents[i]))
 
986
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
 
987
 
 
988
 
 
989
 
 
990
def weave_stats(weave_file, pb):
687
991
    from bzrlib.weavefile import read_weave
688
992
 
689
 
    pb = ProgressBar()
690
 
 
691
993
    wf = file(weave_file, 'rb')
692
994
    w = read_weave(wf)
693
995
    # FIXME: doesn't work on pipes
697
999
    vers = len(w)
698
1000
    for i in range(vers):
699
1001
        pb.update('checking sizes', i, vers)
700
 
        for line in w.get_iter(i):
 
1002
        for origin, lineno, line in w._extract([i]):
701
1003
            total += len(line)
702
1004
 
703
1005
    pb.clear()
706
1008
    print 'weave file        %9d bytes' % weave_size
707
1009
    print 'total contents    %9d bytes' % total
708
1010
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
709
 
 
 
1011
    if vers:
 
1012
        avg = total/vers
 
1013
        print 'average size      %9d bytes' % avg
 
1014
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
710
1015
 
711
1016
 
712
1017
def usage():
721
1026
        Write out specified version.
722
1027
    weave check WEAVEFILE
723
1028
        Check consistency of all versions.
724
 
    weave info WEAVEFILE
 
1029
    weave toc WEAVEFILE
725
1030
        Display table of contents.
726
 
    weave add WEAVEFILE [BASE...] < NEWTEXT
 
1031
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
727
1032
        Add NEWTEXT, with specified parent versions.
728
1033
    weave annotate WEAVEFILE VERSION
729
1034
        Display origin of each line.
731
1036
        Display composite of all selected versions.
732
1037
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
733
1038
        Auto-merge two versions and display conflicts.
 
1039
    weave diff WEAVEFILE VERSION1 VERSION2 
 
1040
        Show differences between two versions.
734
1041
 
735
1042
example:
736
1043
 
737
1044
    % weave init foo.weave
738
1045
    % vi foo.txt
739
 
    % weave add foo.weave < foo.txt
 
1046
    % weave add foo.weave ver0 < foo.txt
740
1047
    added version 0
741
1048
 
742
1049
    (create updated version)
743
1050
    % vi foo.txt
744
1051
    % weave get foo.weave 0 | diff -u - foo.txt
745
 
    % weave add foo.weave 0 < foo.txt
 
1052
    % weave add foo.weave ver1 0 < foo.txt
746
1053
    added version 1
747
1054
 
748
1055
    % weave get foo.weave 0 > foo.txt       (create forked version)
749
1056
    % vi foo.txt
750
 
    % weave add foo.weave 0 < foo.txt
 
1057
    % weave add foo.weave ver2 0 < foo.txt
751
1058
    added version 2
752
1059
 
753
1060
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
754
1061
    % vi foo.txt                            (resolve conflicts)
755
 
    % weave add foo.weave 1 2 < foo.txt     (commit merged version)     
 
1062
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
756
1063
    
757
1064
"""
758
1065
    
761
1068
def main(argv):
762
1069
    import sys
763
1070
    import os
764
 
    from weavefile import write_weave, read_weave
 
1071
    try:
 
1072
        import bzrlib
 
1073
    except ImportError:
 
1074
        # in case we're run directly from the subdirectory
 
1075
        sys.path.append('..')
 
1076
        import bzrlib
 
1077
    from bzrlib.weavefile import write_weave, read_weave
765
1078
    from bzrlib.progress import ProgressBar
766
1079
 
767
 
    #import psyco
768
 
    #psyco.full()
 
1080
    try:
 
1081
        import psyco
 
1082
        psyco.full()
 
1083
    except ImportError:
 
1084
        pass
 
1085
 
 
1086
    if len(argv) < 2:
 
1087
        usage()
 
1088
        return 0
769
1089
 
770
1090
    cmd = argv[1]
771
1091
 
777
1097
    elif cmd == 'add':
778
1098
        w = readit()
779
1099
        # at the moment, based on everything in the file
780
 
        parents = map(int, argv[3:])
 
1100
        name = argv[3]
 
1101
        parents = map(int, argv[4:])
781
1102
        lines = sys.stdin.readlines()
782
 
        ver = w.add(parents, lines)
 
1103
        ver = w.add(name, parents, lines)
783
1104
        write_weave(w, file(argv[2], 'wb'))
784
 
        print 'added version %d' % ver
 
1105
        print 'added version %r %d' % (name, ver)
785
1106
    elif cmd == 'init':
786
1107
        fn = argv[2]
787
1108
        if os.path.exists(fn):
796
1117
        w = readit()
797
1118
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
798
1119
 
 
1120
    elif cmd == 'diff':
 
1121
        from difflib import unified_diff
 
1122
        w = readit()
 
1123
        fn = argv[2]
 
1124
        v1, v2 = map(int, argv[3:5])
 
1125
        lines1 = w.get(v1)
 
1126
        lines2 = w.get(v2)
 
1127
        diff_gen = unified_diff(lines1, lines2,
 
1128
                                '%s version %d' % (fn, v1),
 
1129
                                '%s version %d' % (fn, v2))
 
1130
        sys.stdout.writelines(diff_gen)
 
1131
            
799
1132
    elif cmd == 'annotate':
800
1133
        w = readit()
801
1134
        # newline is added to all lines regardless; too hard to get
809
1142
                print '%5d | %s' % (origin, text)
810
1143
                lasto = origin
811
1144
                
812
 
    elif cmd == 'info':
813
 
        weave_info(readit())
 
1145
    elif cmd == 'toc':
 
1146
        weave_toc(readit())
814
1147
 
815
1148
    elif cmd == 'stats':
816
 
        weave_stats(argv[2])
 
1149
        weave_stats(argv[2], ProgressBar())
817
1150
        
818
1151
    elif cmd == 'check':
819
1152
        w = readit()
865
1198
        raise ValueError('unknown command %r' % cmd)
866
1199
    
867
1200
 
 
1201
 
 
1202
def profile_main(argv): 
 
1203
    import tempfile, hotshot, hotshot.stats
 
1204
 
 
1205
    prof_f = tempfile.NamedTemporaryFile()
 
1206
 
 
1207
    prof = hotshot.Profile(prof_f.name)
 
1208
 
 
1209
    ret = prof.runcall(main, argv)
 
1210
    prof.close()
 
1211
 
 
1212
    stats = hotshot.stats.load(prof_f.name)
 
1213
    #stats.strip_dirs()
 
1214
    stats.sort_stats('cumulative')
 
1215
    ## XXX: Might like to write to stderr or the trace file instead but
 
1216
    ## print_stats seems hardcoded to stdout
 
1217
    stats.print_stats(20)
 
1218
            
 
1219
    return ret
 
1220
 
 
1221
 
 
1222
def lsprofile_main(argv): 
 
1223
    from bzrlib.lsprof import profile
 
1224
    ret,stats = profile(main, argv)
 
1225
    stats.sort()
 
1226
    stats.pprint()
 
1227
    return ret
 
1228
 
 
1229
 
868
1230
if __name__ == '__main__':
869
1231
    import sys
870
 
    sys.exit(main(sys.argv))
 
1232
    if '--profile' in sys.argv:
 
1233
        args = sys.argv[:]
 
1234
        args.remove('--profile')
 
1235
        sys.exit(profile_main(args))
 
1236
    elif '--lsprof' in sys.argv:
 
1237
        args = sys.argv[:]
 
1238
        args.remove('--lsprof')
 
1239
        sys.exit(lsprofile_main(args))
 
1240
    else:
 
1241
        sys.exit(main(sys.argv))
 
1242