/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: John Arbash Meinel
  • Date: 2006-02-15 15:18:44 UTC
  • mto: (1185.79.1 bzr-jam-pending)
  • mto: This revision was merged to the branch mainline in revision 1554.
  • Revision ID: john@arbash-meinel.com-20060215151844-ce3e3efccd19da3f
Reverting gpg changes, should not be mainline, see gpg_uses_tempfile plugin.

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
        names_to_join = []
 
823
        processed = 0
 
824
        for other_idx, name in enumerate(other._names):
 
825
            self._check_version_consistent(other, other_idx, name)
 
826
            sha1 = other._sha1s[other_idx]
 
827
 
 
828
            processed += 1
 
829
 
 
830
            if name in self._name_map:
 
831
                idx = self.lookup(name)
 
832
                n1 = set(map(other.idx_to_name, other._parents[other_idx]))
 
833
                n2 = set(map(self.idx_to_name, self._parents[idx]))
 
834
                if sha1 ==  self._sha1s[idx] and n1 == n2:
 
835
                        continue
 
836
 
 
837
            names_to_join.append((other_idx, name))
 
838
 
 
839
        if pb and not msg:
 
840
            msg = 'weave join'
 
841
 
 
842
        merged = 0
 
843
        time0 = time.time( )
 
844
        for other_idx, name in names_to_join:
 
845
            # TODO: If all the parents of the other version are already
 
846
            # present then we can avoid some work by just taking the delta
 
847
            # and adjusting the offsets.
 
848
            new_parents = self._imported_parents(other, other_idx)
 
849
            sha1 = other._sha1s[other_idx]
 
850
 
 
851
            merged += 1
 
852
 
 
853
            if pb:
 
854
                pb.update(msg, merged, len(names_to_join))
 
855
           
 
856
            lines = other.get_lines(other_idx)
 
857
            self.add(name, new_parents, lines, sha1)
 
858
 
 
859
        mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
 
860
                merged, processed, self._weave_name, time.time( )-time0))
 
861
 
 
862
    def _imported_parents(self, other, other_idx):
 
863
        """Return list of parents in self corresponding to indexes in other."""
 
864
        new_parents = []
 
865
        for parent_idx in other._parents[other_idx]:
 
866
            parent_name = other._names[parent_idx]
 
867
            if parent_name not in self._names:
 
868
                # should not be possible
 
869
                raise WeaveError("missing parent {%s} of {%s} in %r" 
 
870
                                 % (parent_name, other._name_map[other_idx], self))
 
871
            new_parents.append(self._name_map[parent_name])
 
872
        return new_parents
 
873
 
 
874
    def _check_version_consistent(self, other, other_idx, name):
 
875
        """Check if a version in consistent in this and other.
 
876
 
 
877
        To be consistent it must have:
 
878
 
 
879
         * the same text
 
880
         * the same direct parents (by name, not index, and disregarding
 
881
           order)
 
882
        
 
883
        If present & correct return True;
 
884
        if not present in self return False; 
 
885
        if inconsistent raise error."""
 
886
        this_idx = self._name_map.get(name, -1)
 
887
        if this_idx != -1:
 
888
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
 
889
                raise WeaveError("inconsistent texts for version {%s} "
 
890
                                 "when joining weaves"
 
891
                                 % (name))
 
892
            self_parents = self._parents[this_idx]
 
893
            other_parents = other._parents[other_idx]
 
894
            n1 = set([self._names[i] for i in self_parents])
 
895
            n2 = set([other._names[i] for i in other_parents])
 
896
            if n1 != n2:
 
897
                raise WeaveParentMismatch("inconsistent parents "
 
898
                    "for version {%s}: %s vs %s" % (name, n1, n2))
 
899
            else:
 
900
                return True         # ok!
 
901
        else:
 
902
            return False
 
903
 
 
904
    def reweave(self, other, pb=None, msg=None):
 
905
        """Reweave self with other.
 
906
 
 
907
        :param other: The other weave to merge
 
908
        :param pb: An optional progress bar, indicating how far done we are
 
909
        :param msg: An optional message for the progress
 
910
        """
 
911
        new_weave = reweave(self, other, pb=pb, msg=msg)
 
912
        for attr in self.__slots__:
 
913
            setattr(self, attr, getattr(new_weave, attr))
 
914
 
 
915
 
 
916
def reweave(wa, wb, pb=None, msg=None):
 
917
    """Combine two weaves and return the result.
 
918
 
 
919
    This works even if a revision R has different parents in 
 
920
    wa and wb.  In the resulting weave all the parents are given.
 
921
 
 
922
    This is done by just building up a new weave, maintaining ordering 
 
923
    of the versions in the two inputs.  More efficient approaches
 
924
    might be possible but it should only be necessary to do 
 
925
    this operation rarely, when a new previously ghost version is 
 
926
    inserted.
 
927
 
 
928
    :param pb: An optional progress bar, indicating how far done we are
 
929
    :param msg: An optional message for the progress
 
930
    """
 
931
    wr = Weave()
 
932
    ia = ib = 0
 
933
    queue_a = range(wa.numversions())
 
934
    queue_b = range(wb.numversions())
 
935
    # first determine combined parents of all versions
 
936
    # map from version name -> all parent names
 
937
    combined_parents = _reweave_parent_graphs(wa, wb)
 
938
    mutter("combined parents: %r", combined_parents)
 
939
    order = topo_sort(combined_parents.iteritems())
 
940
    mutter("order to reweave: %r", order)
 
941
 
 
942
    if pb and not msg:
 
943
        msg = 'reweave'
 
944
 
 
945
    for idx, name in enumerate(order):
 
946
        if pb:
 
947
            pb.update(msg, idx, len(order))
 
948
        if name in wa._name_map:
 
949
            lines = wa.get_lines(name)
 
950
            if name in wb._name_map:
 
951
                lines_b = wb.get_lines(name)
 
952
                if lines != lines_b:
 
953
                    mutter('Weaves differ on content. rev_id {%s}', name)
 
954
                    mutter('weaves: %s, %s', wa._weave_name, wb._weave_name)
 
955
                    import difflib
 
956
                    lines = list(difflib.unified_diff(lines, lines_b,
 
957
                            wa._weave_name, wb._weave_name))
 
958
                    mutter('lines:\n%s', ''.join(lines))
 
959
                    raise errors.WeaveTextDiffers(name, wa, wb)
 
960
        else:
 
961
            lines = wb.get_lines(name)
 
962
        wr.add(name, combined_parents[name], lines)
 
963
    return wr
 
964
 
 
965
 
 
966
def _reweave_parent_graphs(wa, wb):
 
967
    """Return combined parent ancestry for two weaves.
 
968
    
 
969
    Returned as a list of (version_name, set(parent_names))"""
 
970
    combined = {}
 
971
    for weave in [wa, wb]:
 
972
        for idx, name in enumerate(weave._names):
 
973
            p = combined.setdefault(name, set())
 
974
            p.update(map(weave.idx_to_name, weave._parents[idx]))
 
975
    return combined
 
976
 
 
977
 
 
978
def weave_toc(w):
 
979
    """Show the weave's table-of-contents"""
 
980
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
 
981
    for i in (6, 50, 10, 10):
677
982
        print '-' * i,
678
983
    print
679
984
    for i in range(w.numversions()):
680
985
        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
 
986
        name = w._names[i]
 
987
        parent_str = ' '.join(map(str, w._parents[i]))
 
988
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
 
989
 
 
990
 
 
991
 
 
992
def weave_stats(weave_file, pb):
687
993
    from bzrlib.weavefile import read_weave
688
994
 
689
 
    pb = ProgressBar()
690
 
 
691
995
    wf = file(weave_file, 'rb')
692
996
    w = read_weave(wf)
693
997
    # FIXME: doesn't work on pipes
697
1001
    vers = len(w)
698
1002
    for i in range(vers):
699
1003
        pb.update('checking sizes', i, vers)
700
 
        for line in w.get_iter(i):
 
1004
        for origin, lineno, line in w._extract([i]):
701
1005
            total += len(line)
702
1006
 
703
1007
    pb.clear()
706
1010
    print 'weave file        %9d bytes' % weave_size
707
1011
    print 'total contents    %9d bytes' % total
708
1012
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
709
 
 
 
1013
    if vers:
 
1014
        avg = total/vers
 
1015
        print 'average size      %9d bytes' % avg
 
1016
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
710
1017
 
711
1018
 
712
1019
def usage():
721
1028
        Write out specified version.
722
1029
    weave check WEAVEFILE
723
1030
        Check consistency of all versions.
724
 
    weave info WEAVEFILE
 
1031
    weave toc WEAVEFILE
725
1032
        Display table of contents.
726
 
    weave add WEAVEFILE [BASE...] < NEWTEXT
 
1033
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
727
1034
        Add NEWTEXT, with specified parent versions.
728
1035
    weave annotate WEAVEFILE VERSION
729
1036
        Display origin of each line.
731
1038
        Display composite of all selected versions.
732
1039
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
733
1040
        Auto-merge two versions and display conflicts.
 
1041
    weave diff WEAVEFILE VERSION1 VERSION2 
 
1042
        Show differences between two versions.
734
1043
 
735
1044
example:
736
1045
 
737
1046
    % weave init foo.weave
738
1047
    % vi foo.txt
739
 
    % weave add foo.weave < foo.txt
 
1048
    % weave add foo.weave ver0 < foo.txt
740
1049
    added version 0
741
1050
 
742
1051
    (create updated version)
743
1052
    % vi foo.txt
744
1053
    % weave get foo.weave 0 | diff -u - foo.txt
745
 
    % weave add foo.weave 0 < foo.txt
 
1054
    % weave add foo.weave ver1 0 < foo.txt
746
1055
    added version 1
747
1056
 
748
1057
    % weave get foo.weave 0 > foo.txt       (create forked version)
749
1058
    % vi foo.txt
750
 
    % weave add foo.weave 0 < foo.txt
 
1059
    % weave add foo.weave ver2 0 < foo.txt
751
1060
    added version 2
752
1061
 
753
1062
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
754
1063
    % vi foo.txt                            (resolve conflicts)
755
 
    % weave add foo.weave 1 2 < foo.txt     (commit merged version)     
 
1064
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
756
1065
    
757
1066
"""
758
1067
    
761
1070
def main(argv):
762
1071
    import sys
763
1072
    import os
764
 
    from weavefile import write_weave, read_weave
 
1073
    try:
 
1074
        import bzrlib
 
1075
    except ImportError:
 
1076
        # in case we're run directly from the subdirectory
 
1077
        sys.path.append('..')
 
1078
        import bzrlib
 
1079
    from bzrlib.weavefile import write_weave, read_weave
765
1080
    from bzrlib.progress import ProgressBar
766
1081
 
767
 
    #import psyco
768
 
    #psyco.full()
 
1082
    try:
 
1083
        import psyco
 
1084
        psyco.full()
 
1085
    except ImportError:
 
1086
        pass
 
1087
 
 
1088
    if len(argv) < 2:
 
1089
        usage()
 
1090
        return 0
769
1091
 
770
1092
    cmd = argv[1]
771
1093
 
777
1099
    elif cmd == 'add':
778
1100
        w = readit()
779
1101
        # at the moment, based on everything in the file
780
 
        parents = map(int, argv[3:])
 
1102
        name = argv[3]
 
1103
        parents = map(int, argv[4:])
781
1104
        lines = sys.stdin.readlines()
782
 
        ver = w.add(parents, lines)
 
1105
        ver = w.add(name, parents, lines)
783
1106
        write_weave(w, file(argv[2], 'wb'))
784
 
        print 'added version %d' % ver
 
1107
        print 'added version %r %d' % (name, ver)
785
1108
    elif cmd == 'init':
786
1109
        fn = argv[2]
787
1110
        if os.path.exists(fn):
796
1119
        w = readit()
797
1120
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
798
1121
 
 
1122
    elif cmd == 'diff':
 
1123
        from difflib import unified_diff
 
1124
        w = readit()
 
1125
        fn = argv[2]
 
1126
        v1, v2 = map(int, argv[3:5])
 
1127
        lines1 = w.get(v1)
 
1128
        lines2 = w.get(v2)
 
1129
        diff_gen = unified_diff(lines1, lines2,
 
1130
                                '%s version %d' % (fn, v1),
 
1131
                                '%s version %d' % (fn, v2))
 
1132
        sys.stdout.writelines(diff_gen)
 
1133
            
799
1134
    elif cmd == 'annotate':
800
1135
        w = readit()
801
1136
        # newline is added to all lines regardless; too hard to get
809
1144
                print '%5d | %s' % (origin, text)
810
1145
                lasto = origin
811
1146
                
812
 
    elif cmd == 'info':
813
 
        weave_info(readit())
 
1147
    elif cmd == 'toc':
 
1148
        weave_toc(readit())
814
1149
 
815
1150
    elif cmd == 'stats':
816
 
        weave_stats(argv[2])
 
1151
        weave_stats(argv[2], ProgressBar())
817
1152
        
818
1153
    elif cmd == 'check':
819
1154
        w = readit()
865
1200
        raise ValueError('unknown command %r' % cmd)
866
1201
    
867
1202
 
 
1203
 
 
1204
def profile_main(argv): 
 
1205
    import tempfile, hotshot, hotshot.stats
 
1206
 
 
1207
    prof_f = tempfile.NamedTemporaryFile()
 
1208
 
 
1209
    prof = hotshot.Profile(prof_f.name)
 
1210
 
 
1211
    ret = prof.runcall(main, argv)
 
1212
    prof.close()
 
1213
 
 
1214
    stats = hotshot.stats.load(prof_f.name)
 
1215
    #stats.strip_dirs()
 
1216
    stats.sort_stats('cumulative')
 
1217
    ## XXX: Might like to write to stderr or the trace file instead but
 
1218
    ## print_stats seems hardcoded to stdout
 
1219
    stats.print_stats(20)
 
1220
            
 
1221
    return ret
 
1222
 
 
1223
 
 
1224
def lsprofile_main(argv): 
 
1225
    from bzrlib.lsprof import profile
 
1226
    ret,stats = profile(main, argv)
 
1227
    stats.sort()
 
1228
    stats.pprint()
 
1229
    return ret
 
1230
 
 
1231
 
868
1232
if __name__ == '__main__':
869
1233
    import sys
870
 
    sys.exit(main(sys.argv))
 
1234
    if '--profile' in sys.argv:
 
1235
        args = sys.argv[:]
 
1236
        args.remove('--profile')
 
1237
        sys.exit(profile_main(args))
 
1238
    elif '--lsprof' in sys.argv:
 
1239
        args = sys.argv[:]
 
1240
        args.remove('--lsprof')
 
1241
        sys.exit(lsprofile_main(args))
 
1242
    else:
 
1243
        sys.exit(main(sys.argv))
 
1244