~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: Martin Pool
  • Date: 2005-09-12 09:50:44 UTC
  • Revision ID: mbp@sourcefrog.net-20050912095044-6acfdb5611729987
- no tests in bzrlib.fetch anymore

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
 
 
52
 
 
53
 
 
54
# TODO: Perhaps have copy method for Weave instances?
24
55
 
25
56
# XXX: If we do weaves this way, will a merge still behave the same
26
57
# way if it's done in a different order?  That's a pretty desirable
43
74
 
44
75
# TODO: Parallel-extract that passes back each line along with a
45
76
# description of which revisions include it.  Nice for checking all
46
 
# shas or calculating stats in parallel.
 
77
# shas in parallel.
47
78
 
48
79
# TODO: Using a single _extract routine and then processing the output
49
80
# is probably inefficient.  It's simple enough that we can afford to
50
81
# have slight specializations for different ways its used: annotate,
51
82
# basis for add, get, etc.
52
83
 
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
 
from copy import copy
 
84
# TODO: Perhaps the API should work only in names to hide the integer
 
85
# indexes from the user?
 
86
 
 
87
 
 
88
 
 
89
import sha
71
90
from cStringIO import StringIO
72
 
from difflib import SequenceMatcher
73
 
import os
74
 
import sha
75
 
import time
76
 
 
77
 
from bzrlib.trace import mutter
78
 
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
79
 
        RevisionAlreadyPresent,
80
 
        RevisionNotPresent,
81
 
        WeaveRevisionAlreadyPresent,
82
 
        WeaveRevisionNotPresent,
83
 
        )
84
 
import bzrlib.errors as errors
85
 
from bzrlib.osutils import sha_strings
86
 
from bzrlib.symbol_versioning import *
87
 
from bzrlib.tsort import topo_sort
88
 
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
89
 
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
90
 
 
91
 
 
92
 
class Weave(VersionedFile):
 
91
 
 
92
 
 
93
class WeaveError(Exception):
 
94
    """Exception in processing weave"""
 
95
 
 
96
 
 
97
class WeaveFormatError(WeaveError):
 
98
    """Weave invariant violated"""
 
99
    
 
100
 
 
101
class Weave(object):
93
102
    """weave - versioned text file storage.
94
103
    
95
104
    A Weave manages versions of line-based text files, keeping track
104
113
 
105
114
    * a nonnegative index number.
106
115
 
107
 
    * a version-id string.
 
116
    * a version-id string. (not implemented yet)
108
117
 
109
118
    Typically the index number will be valid only inside this weave and
110
119
    the version-id is used to reference it in the larger world.
181
190
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
182
191
                 '_weave_name']
183
192
    
184
 
    def __init__(self, weave_name=None, access_mode='w'):
185
 
        super(Weave, self).__init__(access_mode)
 
193
    def __init__(self, weave_name=None):
186
194
        self._weave = []
187
195
        self._parents = []
188
196
        self._sha1s = []
190
198
        self._name_map = {}
191
199
        self._weave_name = weave_name
192
200
 
193
 
    def __repr__(self):
194
 
        return "Weave(%r)" % self._weave_name
195
 
 
196
 
    def copy(self):
197
 
        """Return a deep copy of self.
198
 
        
199
 
        The copy can be modified without affecting the original weave."""
200
 
        other = Weave()
201
 
        other._weave = self._weave[:]
202
 
        other._parents = self._parents[:]
203
 
        other._sha1s = self._sha1s[:]
204
 
        other._names = self._names[:]
205
 
        other._name_map = self._name_map.copy()
206
 
        other._weave_name = self._weave_name
207
 
        return other
208
201
 
209
202
    def __eq__(self, other):
210
203
        if not isinstance(other, Weave):
212
205
        return self._parents == other._parents \
213
206
               and self._weave == other._weave \
214
207
               and self._sha1s == other._sha1s 
 
208
 
215
209
    
216
210
    def __ne__(self, other):
217
211
        return not self.__eq__(other)
218
212
 
219
 
    @deprecated_method(zero_eight)
220
 
    def idx_to_name(self, index):
221
 
        """Old public interface, the public interface is all names now."""
222
 
        return index
223
 
 
224
 
    def _idx_to_name(self, version):
225
 
        return self._names[version]
226
 
 
227
 
    @deprecated_method(zero_eight)
 
213
 
228
214
    def lookup(self, name):
229
 
        """Backwards compatability thunk:
230
 
 
231
 
        Return name, as name is valid in the api now, and spew deprecation
232
 
        warnings everywhere.
233
 
        """
234
 
        return name
235
 
 
236
 
    def _lookup(self, name):
237
 
        """Convert symbolic version name to index."""
238
215
        try:
239
216
            return self._name_map[name]
240
217
        except KeyError:
241
 
            raise RevisionNotPresent(name, self._weave_name)
242
 
 
243
 
    @deprecated_method(zero_eight)
244
 
    def iter_names(self):
245
 
        """Deprecated convenience function, please see VersionedFile.names()."""
246
 
        return iter(self.names())
247
 
 
248
 
    @deprecated_method(zero_eight)
249
 
    def names(self):
250
 
        """See Weave.versions for the current api."""
251
 
        return self.versions()
252
 
 
253
 
    def versions(self):
254
 
        """See VersionedFile.versions."""
255
 
        return self._names[:]
256
 
 
257
 
    def has_version(self, version_id):
258
 
        """See VersionedFile.has_version."""
259
 
        return self._name_map.has_key(version_id)
260
 
 
261
 
    __contains__ = has_version
262
 
 
263
 
    def get_parents(self, version_id):
264
 
        """See VersionedFile.get_parent."""
265
 
        return map(self._idx_to_name, self._parents[self._lookup(version_id)])
266
 
 
267
 
    def _check_repeated_add(self, name, parents, text, sha1):
268
 
        """Check that a duplicated add is OK.
269
 
 
270
 
        If it is, return the (old) index; otherwise raise an exception.
271
 
        """
272
 
        idx = self._lookup(name)
273
 
        if sorted(self._parents[idx]) != sorted(parents) \
274
 
            or sha1 != self._sha1s[idx]:
275
 
            raise RevisionAlreadyPresent(name, self._weave_name)
276
 
        return idx
277
 
 
278
 
    @deprecated_method(zero_eight)
279
 
    def add_identical(self, old_rev_id, new_rev_id, parents):
280
 
        """Please use Weave.clone_text now."""
281
 
        return self.clone_text(new_rev_id, old_rev_id, parents)
282
 
 
283
 
    def _add_lines(self, version_id, parents, lines):
284
 
        """See VersionedFile.add_lines."""
285
 
        return self._add(version_id, lines, map(self._lookup, parents))
286
 
 
287
 
    @deprecated_method(zero_eight)
288
 
    def add(self, name, parents, text, sha1=None):
289
 
        """See VersionedFile.add_lines for the non deprecated api."""
290
 
        return self._add(name, text, map(self._maybe_lookup, parents), sha1)
291
 
 
292
 
    def _add(self, version_id, lines, parents, sha1=None):
 
218
            raise WeaveError("name %s not present in weave %s" %
 
219
                             (name, self._weave_name))
 
220
 
 
221
        
 
222
    def add(self, name, parents, text):
293
223
        """Add a single text on top of the weave.
294
224
  
295
225
        Returns the index number of the newly added version.
296
226
 
297
 
        version_id
 
227
        name
298
228
            Symbolic name for this version.
299
229
            (Typically the revision-id of the revision that added it.)
300
230
 
301
231
        parents
302
232
            List or set of direct parent version numbers.
303
233
            
304
 
        lines
305
 
            Sequence of lines to be added in the new version.
306
 
        """
307
 
 
308
 
        assert isinstance(version_id, basestring)
309
 
        if not sha1:
310
 
            sha1 = sha_strings(lines)
311
 
        if version_id in self._name_map:
312
 
            return self._check_repeated_add(version_id, parents, lines, sha1)
313
 
 
 
234
        text
 
235
            Sequence of lines to be added in the new version."""
 
236
 
 
237
        assert isinstance(name, basestring)
 
238
        if name in self._name_map:
 
239
            raise WeaveError("name %r already present in weave" % name)
 
240
        
314
241
        self._check_versions(parents)
315
 
        ## self._check_lines(lines)
 
242
        ## self._check_lines(text)
316
243
        new_version = len(self._parents)
317
244
 
 
245
        s = sha.new()
 
246
        map(s.update, text)
 
247
        sha1 = s.hexdigest()
 
248
        del s
 
249
 
318
250
        # if we abort after here the (in-memory) weave will be corrupt because only
319
251
        # some fields are updated
320
 
        # XXX: FIXME implement a succeed-or-fail of the rest of this routine.
321
 
        #      - Robert Collins 20060226
322
252
        self._parents.append(parents[:])
323
253
        self._sha1s.append(sha1)
324
 
        self._names.append(version_id)
325
 
        self._name_map[version_id] = new_version
 
254
        self._names.append(name)
 
255
        self._name_map[name] = new_version
326
256
 
327
257
            
328
258
        if not parents:
330
260
            # this more quickly by just appending unconditionally.
331
261
            # even more specially, if we're adding an empty text we
332
262
            # need do nothing at all.
333
 
            if lines:
 
263
            if text:
334
264
                self._weave.append(('{', new_version))
335
 
                self._weave.extend(lines)
 
265
                self._weave.extend(text)
336
266
                self._weave.append(('}', None))
 
267
        
337
268
            return new_version
338
269
 
339
270
        if len(parents) == 1:
343
274
                return new_version
344
275
            
345
276
 
346
 
        ancestors = self._inclusions(parents)
 
277
        ancestors = self.inclusions(parents)
347
278
 
348
279
        l = self._weave
349
280
 
356
287
 
357
288
        # another small special case: a merge, producing the same text
358
289
        # as auto-merge
359
 
        if lines == basis_lines:
 
290
        if text == basis_lines:
360
291
            return new_version            
361
292
 
362
293
        # add a sentinal, because we can also match against the final line
369
300
        #print 'basis_lines:', basis_lines
370
301
        #print 'new_lines:  ', lines
371
302
 
372
 
        s = SequenceMatcher(None, basis_lines, lines)
 
303
        from difflib import SequenceMatcher
 
304
        s = SequenceMatcher(None, basis_lines, text)
373
305
 
374
306
        # offset gives the number of lines that have been inserted
375
307
        # into the weave up to the current point; if the original edit instruction
386
318
            i1 = basis_lineno[i1]
387
319
            i2 = basis_lineno[i2]
388
320
 
389
 
            assert 0 <= j1 <= j2 <= len(lines)
 
321
            assert 0 <= j1 <= j2 <= len(text)
390
322
 
391
323
            #print tag, i1, i2, j1, j2
392
324
 
403
335
                # we don't destroy ourselves
404
336
                i = i2 + offset
405
337
                self._weave[i:i] = ([('{', new_version)] 
406
 
                                    + lines[j1:j2] 
 
338
                                    + text[j1:j2] 
407
339
                                    + [('}', None)])
408
340
                offset += 2 + (j2 - j1)
 
341
 
409
342
        return new_version
410
343
 
411
 
    def _clone_text(self, new_version_id, old_version_id, parents):
412
 
        """See VersionedFile.clone_text."""
413
 
        old_lines = self.get_text(old_version_id)
414
 
        self.add_lines(new_version_id, parents, old_lines)
415
344
 
416
 
    def _inclusions(self, versions):
 
345
    def inclusions(self, versions):
417
346
        """Return set of all ancestors of given version(s)."""
418
 
        if not len(versions):
419
 
            return []
420
347
        i = set(versions)
421
 
        for v in xrange(max(versions), 0, -1):
422
 
            if v in i:
423
 
                # include all its parents
424
 
                i.update(self._parents[v])
425
 
        return i
426
 
        ## except IndexError:
427
 
        ##     raise ValueError("version %d not present in weave" % v)
428
 
 
429
 
    @deprecated_method(zero_eight)
430
 
    def inclusions(self, version_ids):
431
 
        """Deprecated - see VersionedFile.get_ancestry for the replacement."""
432
 
        if not version_ids:
 
348
        v = max(versions)
 
349
        try:
 
350
            while v >= 0:
 
351
                if v in i:
 
352
                    # include all its parents
 
353
                    i.update(self._parents[v])
 
354
                v -= 1
 
355
            return i
 
356
        except IndexError:
 
357
            raise ValueError("version %d not present in weave" % v)
 
358
 
 
359
 
 
360
    def minimal_parents(self, version):
 
361
        """Find the minimal set of parents for the version."""
 
362
        included = self._parents[version]
 
363
        if not included:
433
364
            return []
434
 
        if isinstance(version_ids[0], int):
435
 
            return [self._idx_to_name(v) for v in self._inclusions(version_ids)]
436
 
        else:
437
 
            return self.get_ancestry(version_ids)
438
 
 
439
 
    def get_ancestry(self, version_ids):
440
 
        """See VersionedFile.get_ancestry."""
441
 
        if isinstance(version_ids, basestring):
442
 
            version_ids = [version_ids]
443
 
        i = self._inclusions([self._lookup(v) for v in version_ids])
444
 
        return [self._idx_to_name(v) for v in i]
 
365
        
 
366
        li = list(included)
 
367
        li.sort(reverse=True)
 
368
 
 
369
        mininc = []
 
370
        gotit = set()
 
371
 
 
372
        for pv in li:
 
373
            if pv not in gotit:
 
374
                mininc.append(pv)
 
375
                gotit.update(self.inclusions(pv))
 
376
 
 
377
        assert mininc[0] >= 0
 
378
        assert mininc[-1] < version
 
379
        return mininc
 
380
 
 
381
 
445
382
 
446
383
    def _check_lines(self, text):
447
384
        if not isinstance(text, list):
462
399
            except IndexError:
463
400
                raise IndexError("invalid version number %r" % i)
464
401
 
465
 
    def _compatible_parents(self, my_parents, other_parents):
466
 
        """During join check that other_parents are joinable with my_parents.
467
 
 
468
 
        Joinable is defined as 'is a subset of' - supersets may require 
469
 
        regeneration of diffs, but subsets do not.
470
 
        """
471
 
        return len(other_parents.difference(my_parents)) == 0
472
 
 
473
 
    def annotate(self, version_id):
474
 
        if isinstance(version_id, int):
475
 
            warn('Weave.annotate(int) is deprecated. Please use version names'
476
 
                 ' in all circumstances as of 0.8',
477
 
                 DeprecationWarning,
478
 
                 stacklevel=2
479
 
                 )
480
 
            result = []
481
 
            for origin, lineno, text in self._extract([version_id]):
482
 
                result.append((origin, text))
483
 
            return result
484
 
        else:
485
 
            return super(Weave, self).annotate(version_id)
486
402
    
487
 
    def annotate_iter(self, version_id):
488
 
        """Yield list of (version-id, line) pairs for the specified version.
 
403
    def annotate(self, index):
 
404
        return list(self.annotate_iter(index))
 
405
 
 
406
 
 
407
    def annotate_iter(self, version):
 
408
        """Yield list of (index-id, line) pairs for the specified version.
489
409
 
490
410
        The index indicates when the line originated in the weave."""
491
 
        incls = [self._lookup(version_id)]
492
 
        for origin, lineno, text in self._extract(incls):
493
 
            yield self._idx_to_name(origin), text
494
 
 
495
 
    @deprecated_method(zero_eight)
 
411
        for origin, lineno, text in self._extract([version]):
 
412
            yield origin, text
 
413
 
 
414
 
496
415
    def _walk(self):
497
 
        """_walk has become visit, a supported api."""
498
 
        return self._walk_internal()
499
 
 
500
 
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
501
 
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
502
 
        if version_ids is None:
503
 
            version_ids = self.versions()
504
 
        version_ids = set(version_ids)
505
 
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
506
 
            # if inserted not in version_ids then it was inserted before the
507
 
            # versions we care about, but because weaves cannot represent ghosts
508
 
            # properly, we do not filter down to that
509
 
            # if inserted not in version_ids: continue
510
 
            if line[-1] != '\n':
511
 
                yield line + '\n'
512
 
            else:
513
 
                yield line
514
 
 
515
 
    #@deprecated_method(zero_eight)
516
 
    def walk(self, version_ids=None):
517
 
        """See VersionedFile.walk."""
518
 
        return self._walk_internal(version_ids)
519
 
 
520
 
    def _walk_internal(self, version_ids=None):
521
 
        """Helper method for weave actions."""
 
416
        """Walk the weave.
 
417
 
 
418
        Yields sequence of
 
419
        (lineno, insert, deletes, text)
 
420
        for each literal line.
 
421
        """
522
422
        
523
423
        istack = []
524
424
        dset = set()
530
430
                c, v = l
531
431
                isactive = None
532
432
                if c == '{':
533
 
                    istack.append(self._idx_to_name(v))
 
433
                    istack.append(v)
534
434
                elif c == '}':
535
435
                    istack.pop()
536
436
                elif c == '[':
537
 
                    assert self._idx_to_name(v) not in dset
538
 
                    dset.add(self._idx_to_name(v))
 
437
                    assert v not in dset
 
438
                    dset.add(v)
539
439
                elif c == ']':
540
 
                    dset.remove(self._idx_to_name(v))
 
440
                    dset.remove(v)
541
441
                else:
542
 
                    raise WeaveFormatError('unexpected instruction %r' % v)
 
442
                    raise WeaveFormatError('unexpected instruction %r'
 
443
                                           % v)
543
444
            else:
544
445
                assert isinstance(l, basestring)
545
446
                assert istack
546
 
                yield lineno, istack[-1], dset.copy(), l
 
447
                yield lineno, istack[-1], dset, l
547
448
            lineno += 1
548
449
 
549
 
        if istack:
550
 
            raise WeaveFormatError("unclosed insertion blocks "
551
 
                    "at end of weave: %s" % istack)
552
 
        if dset:
553
 
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
554
 
                                   % dset)
 
450
 
555
451
 
556
452
    def _extract(self, versions):
557
453
        """Yield annotation of lines in included set.
566
462
            if not isinstance(i, int):
567
463
                raise ValueError(i)
568
464
            
569
 
        included = self._inclusions(versions)
 
465
        included = self.inclusions(versions)
570
466
 
571
467
        istack = []
572
468
        dset = set()
604
500
                if isactive:
605
501
                    result.append((istack[-1], lineno, l))
606
502
            lineno += 1
 
503
 
607
504
        if istack:
608
 
            raise WeaveFormatError("unclosed insertion blocks "
609
 
                    "at end of weave: %s" % istack)
 
505
            raise WFE("unclosed insertion blocks at end of weave",
 
506
                                   istack)
610
507
        if dset:
611
 
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
612
 
                                   % dset)
 
508
            raise WFE("unclosed deletion blocks at end of weave",
 
509
                                   dset)
 
510
 
613
511
        return result
614
 
 
615
 
    @deprecated_method(zero_eight)
616
 
    def get_iter(self, name_or_index):
617
 
        """Deprecated, please do not use. Lookups are not not needed.
618
 
        
619
 
        Please use get_lines now.
620
 
        """
621
 
        return self._get_iter(self._maybe_lookup(name_or_index))
622
 
 
623
 
    @deprecated_method(zero_eight)
624
 
    def maybe_lookup(self, name_or_index):
625
 
        """Deprecated, please do not use. Lookups are not not needed."""
626
 
        return self._maybe_lookup(name_or_index)
627
 
 
628
 
    def _maybe_lookup(self, name_or_index):
629
 
        """Convert possible symbolic name to index, or pass through indexes.
630
 
        
631
 
        NOT FOR PUBLIC USE.
632
 
        """
633
 
        if isinstance(name_or_index, (int, long)):
634
 
            return name_or_index
635
 
        else:
636
 
            return self._lookup(name_or_index)
637
 
 
638
 
    def _get_iter(self, version_id):
 
512
    
 
513
 
 
514
 
 
515
    def get_iter(self, version):
639
516
        """Yield lines for the specified version."""
640
 
        incls = [self._maybe_lookup(version_id)]
641
 
        if len(incls) == 1:
642
 
            index = incls[0]
643
 
            cur_sha = sha.new()
644
 
        else:
645
 
            # We don't have sha1 sums for multiple entries
646
 
            cur_sha = None
647
 
        for origin, lineno, line in self._extract(incls):
648
 
            if cur_sha:
649
 
                cur_sha.update(line)
 
517
        for origin, lineno, line in self._extract([version]):
650
518
            yield line
651
 
        if cur_sha:
652
 
            expected_sha1 = self._sha1s[index]
653
 
            measured_sha1 = cur_sha.hexdigest() 
654
 
            if measured_sha1 != expected_sha1:
655
 
                raise errors.WeaveInvalidChecksum(
656
 
                        'file %s, revision %s, expected: %s, measured %s' 
657
 
                        % (self._weave_name, self._names[index],
658
 
                           expected_sha1, measured_sha1))
659
 
 
660
 
    @deprecated_method(zero_eight)
661
 
    def get(self, version_id):
662
 
        """Please use either Weave.get_text or Weave.get_lines as desired."""
663
 
        return self.get_lines(version_id)
664
 
 
665
 
    def get_lines(self, version_id):
666
 
        """See VersionedFile.get_lines()."""
667
 
        return list(self._get_iter(version_id))
668
 
 
669
 
    def get_sha1(self, name):
670
 
        """Get the stored sha1 sum for the given revision.
671
 
        
672
 
        :param name: The name of the version to lookup
673
 
        """
674
 
        return self._sha1s[self._lookup(name)]
675
 
 
676
 
    @deprecated_method(zero_eight)
 
519
 
 
520
 
 
521
    def get_text(self, version):
 
522
        assert isinstance(version, int)
 
523
        s = StringIO()
 
524
        s.writelines(self.get_iter(version))
 
525
        return s.getvalue()
 
526
 
 
527
 
 
528
    def get(self, index):
 
529
        return list(self.get_iter(index))
 
530
 
 
531
 
 
532
    def mash_iter(self, included):
 
533
        """Return composed version of multiple included versions."""
 
534
        for origin, lineno, text in self._extract(included):
 
535
            yield text
 
536
 
 
537
 
 
538
    def dump(self, to_file):
 
539
        from pprint import pprint
 
540
        print >>to_file, "Weave._weave = ",
 
541
        pprint(self._weave, to_file)
 
542
        print >>to_file, "Weave._parents = ",
 
543
        pprint(self._parents, to_file)
 
544
 
 
545
 
 
546
 
677
547
    def numversions(self):
678
 
        """How many versions are in this weave?
679
 
 
680
 
        Deprecated in favour of num_versions.
681
 
        """
682
 
        return self.num_versions()
683
 
 
684
 
    def num_versions(self):
685
 
        """How many versions are in this weave?"""
686
548
        l = len(self._parents)
687
549
        assert l == len(self._sha1s)
688
550
        return l
689
551
 
690
 
    __len__ = num_versions
 
552
 
 
553
    def __len__(self):
 
554
        return self.numversions()
 
555
 
691
556
 
692
557
    def check(self, progress_bar=None):
693
 
        # TODO evaluate performance hit of using string sets in this routine.
694
558
        # check no circular inclusions
695
 
        for version in range(self.num_versions()):
 
559
        for version in range(self.numversions()):
696
560
            inclusions = list(self._parents[version])
697
561
            if inclusions:
698
562
                inclusions.sort()
700
564
                    raise WeaveFormatError("invalid included version %d for index %d"
701
565
                                           % (inclusions[-1], version))
702
566
 
703
 
        # try extracting all versions; parallel extraction is used
704
 
        nv = self.num_versions()
705
 
        sha1s = {}
706
 
        texts = {}
707
 
        inclusions = {}
708
 
        for i in range(nv):
709
 
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
710
 
            # The problem is that set membership is much more expensive
711
 
            name = self._idx_to_name(i)
712
 
            sha1s[name] = sha.new()
713
 
            texts[name] = []
714
 
            new_inc = set([name])
715
 
            for p in self._parents[i]:
716
 
                new_inc.update(inclusions[self._idx_to_name(p)])
717
 
 
718
 
            assert set(new_inc) == set(self.get_ancestry(name)), \
719
 
                'failed %s != %s' % (set(new_inc), set(self.get_ancestry(name)))
720
 
            inclusions[name] = new_inc
721
 
 
722
 
        nlines = len(self._weave)
723
 
 
724
 
        update_text = 'checking weave'
725
 
        if self._weave_name:
726
 
            short_name = os.path.basename(self._weave_name)
727
 
            update_text = 'checking %s' % (short_name,)
728
 
            update_text = update_text[:25]
729
 
 
730
 
        for lineno, insert, deleteset, line in self._walk_internal():
 
567
        # try extracting all versions; this is a bit slow and parallel
 
568
        # extraction could be used
 
569
        nv = self.numversions()
 
570
        for version in range(nv):
731
571
            if progress_bar:
732
 
                progress_bar.update(update_text, lineno, nlines)
733
 
 
734
 
            for name, name_inclusions in inclusions.items():
735
 
                # The active inclusion must be an ancestor,
736
 
                # and no ancestors must have deleted this line,
737
 
                # because we don't support resurrection.
738
 
                if (insert in name_inclusions) and not (deleteset & name_inclusions):
739
 
                    sha1s[name].update(line)
740
 
 
741
 
        for i in range(nv):
742
 
            version = self._idx_to_name(i)
743
 
            hd = sha1s[version].hexdigest()
744
 
            expected = self._sha1s[i]
 
572
                progress_bar.update('checking text', version, nv)
 
573
            s = sha.new()
 
574
            for l in self.get_iter(version):
 
575
                s.update(l)
 
576
            hd = s.hexdigest()
 
577
            expected = self._sha1s[version]
745
578
            if hd != expected:
746
 
                raise errors.WeaveInvalidChecksum(
747
 
                        "mismatched sha1 for version %s: "
748
 
                        "got %s, expected %s"
749
 
                        % (version, hd, expected))
 
579
                raise WeaveError("mismatched sha1 for version %d; "
 
580
                                 "got %s, expected %s"
 
581
                                 % (version, hd, expected))
750
582
 
751
583
        # TODO: check insertions are properly nested, that there are
752
584
        # no lines outside of insertion blocks, that deletions are
753
585
        # properly paired, etc.
754
586
 
755
 
    def _join(self, other, pb, msg, version_ids, ignore_missing):
756
 
        """Worker routine for join()."""
757
 
        if not other.versions():
758
 
            return          # nothing to update, easy
759
 
 
760
 
        if version_ids:
761
 
            for version_id in version_ids:
762
 
                if not other.has_version(version_id) and not ignore_missing:
763
 
                    raise RevisionNotPresent(version_id, self._weave_name)
764
 
        else:
765
 
            version_ids = other.versions()
766
 
 
767
 
        # two loops so that we do not change ourselves before verifying it
768
 
        # will be ok
769
 
        # work through in index order to make sure we get all dependencies
770
 
        names_to_join = []
771
 
        processed = 0
772
 
        # get the selected versions only that are in other.versions.
773
 
        version_ids = set(other.versions()).intersection(set(version_ids))
774
 
        # pull in the referenced graph.
775
 
        version_ids = other.get_ancestry(version_ids)
776
 
        pending_graph = [(version, other.get_parents(version)) for
777
 
                         version in version_ids]
778
 
        for name in topo_sort(pending_graph):
779
 
            other_idx = other._name_map[name]
780
 
            # returns True if we have it, False if we need it.
781
 
            if not self._check_version_consistent(other, other_idx, name):
782
 
                names_to_join.append((other_idx, name))
783
 
            processed += 1
784
 
 
785
 
 
786
 
        if pb and not msg:
787
 
            msg = 'weave join'
788
 
 
789
 
        merged = 0
790
 
        time0 = time.time()
791
 
        for other_idx, name in names_to_join:
792
 
            # TODO: If all the parents of the other version are already
793
 
            # present then we can avoid some work by just taking the delta
794
 
            # and adjusting the offsets.
795
 
            new_parents = self._imported_parents(other, other_idx)
796
 
            sha1 = other._sha1s[other_idx]
797
 
 
798
 
            merged += 1
799
 
 
800
 
            if pb:
801
 
                pb.update(msg, merged, len(names_to_join))
802
 
           
803
 
            lines = other.get_lines(other_idx)
804
 
            self._add(name, lines, new_parents, sha1)
805
 
 
806
 
        mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
807
 
                merged, processed, self._weave_name, time.time()-time0))
808
 
 
809
 
    def _imported_parents(self, other, other_idx):
810
 
        """Return list of parents in self corresponding to indexes in other."""
811
 
        new_parents = []
812
 
        for parent_idx in other._parents[other_idx]:
813
 
            parent_name = other._names[parent_idx]
814
 
            if parent_name not in self._names:
815
 
                # should not be possible
816
 
                raise WeaveError("missing parent {%s} of {%s} in %r" 
817
 
                                 % (parent_name, other._name_map[other_idx], self))
818
 
            new_parents.append(self._name_map[parent_name])
819
 
        return new_parents
820
 
 
821
 
    def _check_version_consistent(self, other, other_idx, name):
822
 
        """Check if a version in consistent in this and other.
823
 
 
824
 
        To be consistent it must have:
825
 
 
826
 
         * the same text
827
 
         * the same direct parents (by name, not index, and disregarding
828
 
           order)
829
 
        
830
 
        If present & correct return True;
831
 
        if not present in self return False; 
832
 
        if inconsistent raise error."""
833
 
        this_idx = self._name_map.get(name, -1)
834
 
        if this_idx != -1:
835
 
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
836
 
                raise errors.WeaveTextDiffers(name, self, other)
837
 
            self_parents = self._parents[this_idx]
838
 
            other_parents = other._parents[other_idx]
839
 
            n1 = set([self._names[i] for i in self_parents])
840
 
            n2 = set([other._names[i] for i in other_parents])
841
 
            if not self._compatible_parents(n1, n2):
842
 
                raise WeaveParentMismatch("inconsistent parents "
843
 
                    "for version {%s}: %s vs %s" % (name, n1, n2))
844
 
            else:
845
 
                return True         # ok!
846
 
        else:
847
 
            return False
848
 
 
849
 
    @deprecated_method(zero_eight)
850
 
    def reweave(self, other, pb=None, msg=None):
851
 
        """reweave has been superceded by plain use of join."""
852
 
        return self.join(other, pb, msg)
853
 
 
854
 
    def _reweave(self, other, pb, msg):
855
 
        """Reweave self with other - internal helper for join().
856
 
 
857
 
        :param other: The other weave to merge
858
 
        :param pb: An optional progress bar, indicating how far done we are
859
 
        :param msg: An optional message for the progress
860
 
        """
861
 
        new_weave = _reweave(self, other, pb=pb, msg=msg)
862
 
        self._copy_weave_content(new_weave)
863
 
 
864
 
    def _copy_weave_content(self, otherweave):
865
 
        """adsorb the content from otherweave."""
866
 
        for attr in self.__slots__:
867
 
            if attr != '_weave_name':
868
 
                setattr(self, attr, copy(getattr(otherweave, attr)))
869
 
 
870
 
 
871
 
class WeaveFile(Weave):
872
 
    """A WeaveFile represents a Weave on disk and writes on change."""
873
 
 
874
 
    WEAVE_SUFFIX = '.weave'
875
 
    
876
 
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w'):
877
 
        """Create a WeaveFile.
878
 
        
879
 
        :param create: If not True, only open an existing knit.
880
 
        """
881
 
        super(WeaveFile, self).__init__(name, access_mode)
882
 
        self._transport = transport
883
 
        self._filemode = filemode
884
 
        try:
885
 
            _read_weave_v5(self._transport.get(name + WeaveFile.WEAVE_SUFFIX), self)
886
 
        except errors.NoSuchFile:
887
 
            if not create:
888
 
                raise
889
 
            # new file, save it
890
 
            self._save()
891
 
 
892
 
    def _add_lines(self, version_id, parents, lines):
893
 
        """Add a version and save the weave."""
894
 
        super(WeaveFile, self)._add_lines(version_id, parents, lines)
895
 
        self._save()
896
 
 
897
 
    def _clone_text(self, new_version_id, old_version_id, parents):
898
 
        """See VersionedFile.clone_text."""
899
 
        super(WeaveFile, self)._clone_text(new_version_id, old_version_id, parents)
900
 
        self._save
901
 
 
902
 
    def copy_to(self, name, transport):
903
 
        """See VersionedFile.copy_to()."""
904
 
        # as we are all in memory always, just serialise to the new place.
905
 
        sio = StringIO()
906
 
        write_weave_v5(self, sio)
907
 
        sio.seek(0)
908
 
        transport.put(name + WeaveFile.WEAVE_SUFFIX, sio, self._filemode)
909
 
 
910
 
    def create_empty(self, name, transport, filemode=None):
911
 
        return WeaveFile(name, transport, filemode, create=True)
912
 
 
913
 
    def _save(self):
914
 
        """Save the weave."""
915
 
        self._check_write_ok()
916
 
        sio = StringIO()
917
 
        write_weave_v5(self, sio)
918
 
        sio.seek(0)
919
 
        self._transport.put(self._weave_name + WeaveFile.WEAVE_SUFFIX,
920
 
                            sio,
921
 
                            self._filemode)
922
 
 
923
 
    @staticmethod
924
 
    def get_suffixes():
925
 
        """See VersionedFile.get_suffixes()."""
926
 
        return [WeaveFile.WEAVE_SUFFIX]
927
 
 
928
 
    def join(self, other, pb=None, msg=None, version_ids=None,
929
 
             ignore_missing=False):
930
 
        """Join other into self and save."""
931
 
        super(WeaveFile, self).join(other, pb, msg, version_ids, ignore_missing)
932
 
        self._save()
933
 
 
934
 
 
935
 
@deprecated_function(zero_eight)
936
 
def reweave(wa, wb, pb=None, msg=None):
937
 
    """reweaving is deprecation, please just use weave.join()."""
938
 
    _reweave(wa, wb, pb, msg)
939
 
 
940
 
def _reweave(wa, wb, pb=None, msg=None):
941
 
    """Combine two weaves and return the result.
942
 
 
943
 
    This works even if a revision R has different parents in 
944
 
    wa and wb.  In the resulting weave all the parents are given.
945
 
 
946
 
    This is done by just building up a new weave, maintaining ordering 
947
 
    of the versions in the two inputs.  More efficient approaches
948
 
    might be possible but it should only be necessary to do 
949
 
    this operation rarely, when a new previously ghost version is 
950
 
    inserted.
951
 
 
952
 
    :param pb: An optional progress bar, indicating how far done we are
953
 
    :param msg: An optional message for the progress
954
 
    """
955
 
    wr = Weave()
956
 
    ia = ib = 0
957
 
    queue_a = range(wa.num_versions())
958
 
    queue_b = range(wb.num_versions())
959
 
    # first determine combined parents of all versions
960
 
    # map from version name -> all parent names
961
 
    combined_parents = _reweave_parent_graphs(wa, wb)
962
 
    mutter("combined parents: %r", combined_parents)
963
 
    order = topo_sort(combined_parents.iteritems())
964
 
    mutter("order to reweave: %r", order)
965
 
 
966
 
    if pb and not msg:
967
 
        msg = 'reweave'
968
 
 
969
 
    for idx, name in enumerate(order):
970
 
        if pb:
971
 
            pb.update(msg, idx, len(order))
972
 
        if name in wa._name_map:
973
 
            lines = wa.get_lines(name)
974
 
            if name in wb._name_map:
975
 
                lines_b = wb.get_lines(name)
976
 
                if lines != lines_b:
977
 
                    mutter('Weaves differ on content. rev_id {%s}', name)
978
 
                    mutter('weaves: %s, %s', wa._weave_name, wb._weave_name)
979
 
                    import difflib
980
 
                    lines = list(difflib.unified_diff(lines, lines_b,
981
 
                            wa._weave_name, wb._weave_name))
982
 
                    mutter('lines:\n%s', ''.join(lines))
983
 
                    raise errors.WeaveTextDiffers(name, wa, wb)
984
 
        else:
985
 
            lines = wb.get_lines(name)
986
 
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
987
 
    return wr
988
 
 
989
 
def _reweave_parent_graphs(wa, wb):
990
 
    """Return combined parent ancestry for two weaves.
991
 
    
992
 
    Returned as a list of (version_name, set(parent_names))"""
993
 
    combined = {}
994
 
    for weave in [wa, wb]:
995
 
        for idx, name in enumerate(weave._names):
996
 
            p = combined.setdefault(name, set())
997
 
            p.update(map(weave._idx_to_name, weave._parents[idx]))
998
 
    return combined
 
587
 
 
588
 
 
589
    def merge(self, merge_versions):
 
590
        """Automerge and mark conflicts between versions.
 
591
 
 
592
        This returns a sequence, each entry describing alternatives
 
593
        for a chunk of the file.  Each of the alternatives is given as
 
594
        a list of lines.
 
595
 
 
596
        If there is a chunk of the file where there's no diagreement,
 
597
        only one alternative is given.
 
598
        """
 
599
 
 
600
        # approach: find the included versions common to all the
 
601
        # merged versions
 
602
        raise NotImplementedError()
 
603
 
 
604
 
 
605
 
 
606
    def _delta(self, included, lines):
 
607
        """Return changes from basis to new revision.
 
608
 
 
609
        The old text for comparison is the union of included revisions.
 
610
 
 
611
        This is used in inserting a new text.
 
612
 
 
613
        Delta is returned as a sequence of
 
614
        (weave1, weave2, newlines).
 
615
 
 
616
        This indicates that weave1:weave2 of the old weave should be
 
617
        replaced by the sequence of lines in newlines.  Note that
 
618
        these line numbers are positions in the total weave and don't
 
619
        correspond to the lines in any extracted version, or even the
 
620
        extracted union of included versions.
 
621
 
 
622
        If line1=line2, this is a pure insert; if newlines=[] this is a
 
623
        pure delete.  (Similar to difflib.)
 
624
        """
 
625
 
 
626
 
 
627
            
 
628
    def plan_merge(self, ver_a, ver_b):
 
629
        """Return pseudo-annotation indicating how the two versions merge.
 
630
 
 
631
        This is computed between versions a and b and their common
 
632
        base.
 
633
 
 
634
        Weave lines present in none of them are skipped entirely.
 
635
        """
 
636
        inc_a = self.inclusions([ver_a])
 
637
        inc_b = self.inclusions([ver_b])
 
638
        inc_c = inc_a & inc_b
 
639
 
 
640
        for lineno, insert, deleteset, line in self._walk():
 
641
            if deleteset & inc_c:
 
642
                # killed in parent; can't be in either a or b
 
643
                # not relevant to our work
 
644
                yield 'killed-base', line
 
645
            elif insert in inc_c:
 
646
                # was inserted in base
 
647
                killed_a = bool(deleteset & inc_a)
 
648
                killed_b = bool(deleteset & inc_b)
 
649
                if killed_a and killed_b:
 
650
                    yield 'killed-both', line
 
651
                elif killed_a:
 
652
                    yield 'killed-a', line
 
653
                elif killed_b:
 
654
                    yield 'killed-b', line
 
655
                else:
 
656
                    yield 'unchanged', line
 
657
            elif insert in inc_a:
 
658
                if deleteset & inc_a:
 
659
                    yield 'ghost-a', line
 
660
                else:
 
661
                    # new in A; not in B
 
662
                    yield 'new-a', line
 
663
            elif insert in inc_b:
 
664
                if deleteset & inc_b:
 
665
                    yield 'ghost-b', line
 
666
                else:
 
667
                    yield 'new-b', line
 
668
            else:
 
669
                # not in either revision
 
670
                yield 'irrelevant', line
 
671
 
 
672
        yield 'unchanged', ''           # terminator
 
673
 
 
674
 
 
675
 
 
676
    def weave_merge(self, plan):
 
677
        lines_a = []
 
678
        lines_b = []
 
679
        ch_a = ch_b = False
 
680
 
 
681
        for state, line in plan:
 
682
            if state == 'unchanged' or state == 'killed-both':
 
683
                # resync and flush queued conflicts changes if any
 
684
                if not lines_a and not lines_b:
 
685
                    pass
 
686
                elif ch_a and not ch_b:
 
687
                    # one-sided change:                    
 
688
                    for l in lines_a: yield l
 
689
                elif ch_b and not ch_a:
 
690
                    for l in lines_b: yield l
 
691
                elif lines_a == lines_b:
 
692
                    for l in lines_a: yield l
 
693
                else:
 
694
                    yield '<<<<\n'
 
695
                    for l in lines_a: yield l
 
696
                    yield '====\n'
 
697
                    for l in lines_b: yield l
 
698
                    yield '>>>>\n'
 
699
 
 
700
                del lines_a[:]
 
701
                del lines_b[:]
 
702
                ch_a = ch_b = False
 
703
                
 
704
            if state == 'unchanged':
 
705
                if line:
 
706
                    yield line
 
707
            elif state == 'killed-a':
 
708
                ch_a = True
 
709
                lines_b.append(line)
 
710
            elif state == 'killed-b':
 
711
                ch_b = True
 
712
                lines_a.append(line)
 
713
            elif state == 'new-a':
 
714
                ch_a = True
 
715
                lines_a.append(line)
 
716
            elif state == 'new-b':
 
717
                ch_b = True
 
718
                lines_b.append(line)
 
719
            else:
 
720
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 'killed-base',
 
721
                                 'killed-both'), \
 
722
                       state
 
723
 
 
724
                
 
725
 
 
726
 
 
727
 
999
728
 
1000
729
 
1001
730
def weave_toc(w):
1004
733
    for i in (6, 50, 10, 10):
1005
734
        print '-' * i,
1006
735
    print
1007
 
    for i in range(w.num_versions()):
 
736
    for i in range(w.numversions()):
1008
737
        sha1 = w._sha1s[i]
1009
738
        name = w._names[i]
1010
739
        parent_str = ' '.join(map(str, w._parents[i]))
1012
741
 
1013
742
 
1014
743
 
1015
 
def weave_stats(weave_file, pb):
 
744
def weave_stats(weave_file):
 
745
    from bzrlib.progress import ProgressBar
1016
746
    from bzrlib.weavefile import read_weave
1017
747
 
 
748
    pb = ProgressBar()
 
749
 
1018
750
    wf = file(weave_file, 'rb')
1019
 
    w = read_weave(wf, WeaveVersionedFile)
 
751
    w = read_weave(wf)
1020
752
    # FIXME: doesn't work on pipes
1021
753
    weave_size = wf.tell()
1022
754
 
1024
756
    vers = len(w)
1025
757
    for i in range(vers):
1026
758
        pb.update('checking sizes', i, vers)
1027
 
        for origin, lineno, line in w._extract([i]):
 
759
        for line in w.get_iter(i):
1028
760
            total += len(line)
1029
761
 
1030
762
    pb.clear()
1057
789
        Add NEWTEXT, with specified parent versions.
1058
790
    weave annotate WEAVEFILE VERSION
1059
791
        Display origin of each line.
 
792
    weave mash WEAVEFILE VERSION...
 
793
        Display composite of all selected versions.
1060
794
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
1061
795
        Auto-merge two versions and display conflicts.
1062
 
    weave diff WEAVEFILE VERSION1 VERSION2 
1063
 
        Show differences between two versions.
1064
796
 
1065
797
example:
1066
798
 
1091
823
def main(argv):
1092
824
    import sys
1093
825
    import os
1094
 
    try:
1095
 
        import bzrlib
1096
 
    except ImportError:
1097
 
        # in case we're run directly from the subdirectory
1098
 
        sys.path.append('..')
1099
 
        import bzrlib
1100
 
    from bzrlib.weavefile import write_weave, read_weave
 
826
    from weavefile import write_weave, read_weave
1101
827
    from bzrlib.progress import ProgressBar
1102
828
 
1103
829
    try:
1136
862
        w = readit()
1137
863
        sys.stdout.writelines(w.get_iter(int(argv[3])))
1138
864
        
1139
 
    elif cmd == 'diff':
1140
 
        from difflib import unified_diff
 
865
    elif cmd == 'mash': # get composite
1141
866
        w = readit()
1142
 
        fn = argv[2]
1143
 
        v1, v2 = map(int, argv[3:5])
1144
 
        lines1 = w.get(v1)
1145
 
        lines2 = w.get(v2)
1146
 
        diff_gen = unified_diff(lines1, lines2,
1147
 
                                '%s version %d' % (fn, v1),
1148
 
                                '%s version %d' % (fn, v2))
1149
 
        sys.stdout.writelines(diff_gen)
1150
 
            
 
867
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
 
868
 
1151
869
    elif cmd == 'annotate':
1152
870
        w = readit()
1153
871
        # newline is added to all lines regardless; too hard to get
1165
883
        weave_toc(readit())
1166
884
 
1167
885
    elif cmd == 'stats':
1168
 
        weave_stats(argv[2], ProgressBar())
 
886
        weave_stats(argv[2])
1169
887
        
1170
888
    elif cmd == 'check':
1171
889
        w = readit()
1172
890
        pb = ProgressBar()
1173
891
        w.check(pb)
1174
892
        pb.clear()
1175
 
        print '%d versions ok' % w.num_versions()
 
893
        print '%d versions ok' % w.numversions()
1176
894
 
1177
895
    elif cmd == 'inclusions':
1178
896
        w = readit()
1193
911
        p = w.plan_merge(int(argv[3]), int(argv[4]))
1194
912
        sys.stdout.writelines(w.weave_merge(p))
1195
913
            
 
914
    elif cmd == 'mash-merge':
 
915
        if len(argv) != 5:
 
916
            usage()
 
917
            return 1
 
918
 
 
919
        w = readit()
 
920
        v1, v2 = map(int, argv[3:5])
 
921
 
 
922
        basis = w.inclusions([v1]).intersection(w.inclusions([v2]))
 
923
 
 
924
        base_lines = list(w.mash_iter(basis))
 
925
        a_lines = list(w.get(v1))
 
926
        b_lines = list(w.get(v2))
 
927
 
 
928
        from bzrlib.merge3 import Merge3
 
929
        m3 = Merge3(base_lines, a_lines, b_lines)
 
930
 
 
931
        name_a = 'version %d' % v1
 
932
        name_b = 'version %d' % v2
 
933
        sys.stdout.writelines(m3.merge_lines(name_a=name_a, name_b=name_b))
1196
934
    else:
1197
935
        raise ValueError('unknown command %r' % cmd)
1198
936
    
1218
956
    return ret
1219
957
 
1220
958
 
1221
 
def lsprofile_main(argv): 
1222
 
    from bzrlib.lsprof import profile
1223
 
    ret,stats = profile(main, argv)
1224
 
    stats.sort()
1225
 
    stats.pprint()
1226
 
    return ret
1227
 
 
1228
 
 
1229
959
if __name__ == '__main__':
1230
960
    import sys
1231
961
    if '--profile' in sys.argv:
1232
962
        args = sys.argv[:]
1233
963
        args.remove('--profile')
1234
964
        sys.exit(profile_main(args))
1235
 
    elif '--lsprof' in sys.argv:
1236
 
        args = sys.argv[:]
1237
 
        args.remove('--lsprof')
1238
 
        sys.exit(lsprofile_main(args))
1239
965
    else:
1240
966
        sys.exit(main(sys.argv))
1241
967
 
1242
 
 
1243
 
class InterWeave(InterVersionedFile):
1244
 
    """Optimised code paths for weave to weave operations."""
1245
 
    
1246
 
    _matching_file_factory = staticmethod(WeaveFile)
1247
 
    
1248
 
    @staticmethod
1249
 
    def is_compatible(source, target):
1250
 
        """Be compatible with weaves."""
1251
 
        try:
1252
 
            return (isinstance(source, Weave) and
1253
 
                    isinstance(target, Weave))
1254
 
        except AttributeError:
1255
 
            return False
1256
 
 
1257
 
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1258
 
        """See InterVersionedFile.join."""
1259
 
        if self.target.versions() == []:
1260
 
            # optimised copy
1261
 
            self.target._copy_weave_content(self.source)
1262
 
            return
1263
 
        try:
1264
 
            self.target._join(self.source, pb, msg, version_ids, ignore_missing)
1265
 
        except errors.WeaveParentMismatch:
1266
 
            self.target._reweave(self.source, pb, msg)
1267
 
 
1268
 
 
1269
 
InterVersionedFile.register_optimiser(InterWeave)