/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: Robert Collins
  • Date: 2006-03-01 02:01:47 UTC
  • mto: (1594.2.4 integration)
  • mto: This revision was merged to the branch mainline in revision 1596.
  • Revision ID: robertc@robertcollins.net-20060301020147-62bb5465f75fbf40
Start check tests for knits (pending), and remove dead code.

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
 
    
88
 
 
89
 
class Weave(object):
 
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
import time
 
73
from difflib import SequenceMatcher
 
74
 
 
75
from bzrlib.trace import mutter
 
76
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
 
77
        RevisionAlreadyPresent,
 
78
        RevisionNotPresent,
 
79
        WeaveRevisionAlreadyPresent,
 
80
        WeaveRevisionNotPresent,
 
81
        )
 
82
import bzrlib.errors as errors
 
83
from bzrlib.osutils import sha_strings
 
84
from bzrlib.symbol_versioning import *
 
85
from bzrlib.tsort import topo_sort
 
86
from bzrlib.versionedfile import VersionedFile
 
87
 
 
88
 
 
89
class Weave(VersionedFile):
90
90
    """weave - versioned text file storage.
91
91
    
92
92
    A Weave manages versions of line-based text files, keeping track
118
118
    The instruction can be '{' or '}' for an insertion block, and '['
119
119
    and ']' for a deletion block respectively.  The version is the
120
120
    integer version index.  There is no replace operator, only deletes
121
 
    and inserts.
 
121
    and inserts.  For '}', the end of an insertion, there is no
 
122
    version parameter because it always closes the most recently
 
123
    opened insertion.
122
124
 
123
125
    Constraints/notes:
124
126
 
160
162
        each version; the parent's parents are implied.
161
163
 
162
164
    _sha1s
163
 
        List of hex SHA-1 of each version, or None if not recorded.
 
165
        List of hex SHA-1 of each version.
 
166
 
 
167
    _names
 
168
        List of symbolic names for each version.  Each should be unique.
 
169
 
 
170
    _name_map
 
171
        For each name, the version number.
 
172
 
 
173
    _weave_name
 
174
        Descriptive name of this weave; typically the filename if known.
 
175
        Set by read_weave.
164
176
    """
165
177
 
166
 
    __slots__ = ['_weave', '_parents', '_sha1s']
 
178
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
 
179
                 '_weave_name']
167
180
    
168
 
    def __init__(self):
 
181
    def __init__(self, weave_name=None):
169
182
        self._weave = []
170
183
        self._parents = []
171
184
        self._sha1s = []
172
 
 
 
185
        self._names = []
 
186
        self._name_map = {}
 
187
        self._weave_name = weave_name
 
188
 
 
189
    def __repr__(self):
 
190
        return "Weave(%r)" % self._weave_name
 
191
 
 
192
 
 
193
    def copy(self):
 
194
        """Return a deep copy of self.
 
195
        
 
196
        The copy can be modified without affecting the original weave."""
 
197
        other = Weave()
 
198
        other._weave = self._weave[:]
 
199
        other._parents = self._parents[:]
 
200
        other._sha1s = self._sha1s[:]
 
201
        other._names = self._names[:]
 
202
        other._name_map = self._name_map.copy()
 
203
        other._weave_name = self._weave_name
 
204
        return other
173
205
 
174
206
    def __eq__(self, other):
175
207
        if not isinstance(other, Weave):
176
208
            return False
177
209
        return self._parents == other._parents \
178
 
               and self._weave == other._weave
 
210
               and self._weave == other._weave \
 
211
               and self._sha1s == other._sha1s 
 
212
 
179
213
    
180
 
 
181
214
    def __ne__(self, other):
182
215
        return not self.__eq__(other)
183
216
 
 
217
    @deprecated_method(zero_eight)
 
218
    def idx_to_name(self, index):
 
219
        """Old public interface, the public interface is all names now."""
 
220
        return index
 
221
 
 
222
    def _idx_to_name(self, version):
 
223
        return self._names[version]
 
224
 
 
225
    @deprecated_method(zero_eight)
 
226
    def lookup(self, name):
 
227
        """Backwards compatability thunk:
 
228
 
 
229
        Return name, as name is valid in the api now, and spew deprecation
 
230
        warnings everywhere.
 
231
        """
 
232
        return name
 
233
 
 
234
    def _lookup(self, name):
 
235
        """Convert symbolic version name to index."""
 
236
        try:
 
237
            return self._name_map[name]
 
238
        except KeyError:
 
239
            raise RevisionNotPresent(name, self._weave_name)
 
240
 
 
241
    @deprecated_method(zero_eight)
 
242
    def iter_names(self):
 
243
        """Deprecated convenience function, please see VersionedFile.names()."""
 
244
        return iter(self.names())
 
245
 
 
246
    @deprecated_method(zero_eight)
 
247
    def names(self):
 
248
        """See Weave.versions for the current api."""
 
249
        return self.versions()
 
250
 
 
251
    def versions(self):
 
252
        """See VersionedFile.versions."""
 
253
        return self._names[:]
 
254
 
 
255
    def has_version(self, version_id):
 
256
        """See VersionedFile.has_version."""
 
257
        return self._name_map.has_key(version_id)
 
258
 
 
259
    __contains__ = has_version
 
260
 
 
261
    @deprecated_method(zero_eight)
 
262
    def parent_names(self, version):
 
263
        """Return version names for parents of a version.
184
264
        
185
 
    def add(self, parents, text):
 
265
        See get_parents for the current api.
 
266
        """
 
267
        return self.get_parents(version)
 
268
 
 
269
    def get_parents(self, version_id):
 
270
        """See VersionedFile.get_parent."""
 
271
        return map(self._idx_to_name, self._parents[self._lookup(version_id)])
 
272
 
 
273
    def _check_repeated_add(self, name, parents, text, sha1):
 
274
        """Check that a duplicated add is OK.
 
275
 
 
276
        If it is, return the (old) index; otherwise raise an exception.
 
277
        """
 
278
        idx = self._lookup(name)
 
279
        if sorted(self._parents[idx]) != sorted(parents) \
 
280
            or sha1 != self._sha1s[idx]:
 
281
            raise RevisionAlreadyPresent(name, self._weave_name)
 
282
        return idx
 
283
 
 
284
    @deprecated_method(zero_eight)
 
285
    def add_identical(self, old_rev_id, new_rev_id, parents):
 
286
        """Please use Weave.clone_text now."""
 
287
        return self.clone_text(new_rev_id, old_rev_id, parents)
 
288
 
 
289
    def add_lines(self, version_id, parents, lines):
 
290
        """See VersionedFile.add_lines."""
 
291
        return self._add(version_id, lines, map(self._lookup, parents))
 
292
 
 
293
    @deprecated_method(zero_eight)
 
294
    def add(self, name, parents, text, sha1=None):
 
295
        """See VersionedFile.add_lines for the non deprecated api."""
 
296
        return self._add(name, text, map(self._maybe_lookup, parents), sha1)
 
297
 
 
298
    def _add(self, version_id, lines, parents, sha1=None):
186
299
        """Add a single text on top of the weave.
187
300
  
188
301
        Returns the index number of the newly added version.
189
302
 
 
303
        version_id
 
304
            Symbolic name for this version.
 
305
            (Typically the revision-id of the revision that added it.)
 
306
 
190
307
        parents
191
308
            List or set of direct parent version numbers.
192
309
            
193
 
        text
194
 
            Sequence of lines to be added in the new version."""
 
310
        lines
 
311
            Sequence of lines to be added in the new version.
 
312
        """
 
313
 
 
314
        assert isinstance(version_id, basestring)
 
315
        if not sha1:
 
316
            sha1 = sha_strings(lines)
 
317
        if version_id in self._name_map:
 
318
            return self._check_repeated_add(version_id, parents, lines, sha1)
195
319
 
196
320
        self._check_versions(parents)
197
 
        ## self._check_lines(text)
 
321
        ## self._check_lines(lines)
198
322
        new_version = len(self._parents)
199
323
 
200
 
        import sha
201
 
        s = sha.new()
202
 
        map(s.update, text)
203
 
        sha1 = s.hexdigest()
204
 
        del s
205
 
 
206
 
        # if we abort after here the weave will be corrupt
207
 
        self._parents.append(frozenset(parents))
 
324
        # if we abort after here the (in-memory) weave will be corrupt because only
 
325
        # some fields are updated
 
326
        self._parents.append(parents[:])
208
327
        self._sha1s.append(sha1)
 
328
        self._names.append(version_id)
 
329
        self._name_map[version_id] = new_version
209
330
 
210
331
            
211
332
        if not parents:
213
334
            # this more quickly by just appending unconditionally.
214
335
            # even more specially, if we're adding an empty text we
215
336
            # need do nothing at all.
216
 
            if text:
 
337
            if lines:
217
338
                self._weave.append(('{', new_version))
218
 
                self._weave.extend(text)
219
 
                self._weave.append(('}', new_version))
220
 
        
 
339
                self._weave.extend(lines)
 
340
                self._weave.append(('}', None))
221
341
            return new_version
222
342
 
223
343
        if len(parents) == 1:
227
347
                return new_version
228
348
            
229
349
 
230
 
        ancestors = self.inclusions(parents)
 
350
        ancestors = self._inclusions(parents)
231
351
 
232
352
        l = self._weave
233
353
 
238
358
            basis_lineno.append(lineno)
239
359
            basis_lines.append(line)
240
360
 
241
 
        # another small special case: a merge, producing the same text as auto-merge
242
 
        if text == basis_lines:
 
361
        # another small special case: a merge, producing the same text
 
362
        # as auto-merge
 
363
        if lines == basis_lines:
243
364
            return new_version            
244
365
 
245
366
        # add a sentinal, because we can also match against the final line
252
373
        #print 'basis_lines:', basis_lines
253
374
        #print 'new_lines:  ', lines
254
375
 
255
 
        from difflib import SequenceMatcher
256
 
        s = SequenceMatcher(None, basis_lines, text)
 
376
        s = SequenceMatcher(None, basis_lines, lines)
257
377
 
258
378
        # offset gives the number of lines that have been inserted
259
379
        # into the weave up to the current point; if the original edit instruction
270
390
            i1 = basis_lineno[i1]
271
391
            i2 = basis_lineno[i2]
272
392
 
273
 
            assert 0 <= j1 <= j2 <= len(text)
 
393
            assert 0 <= j1 <= j2 <= len(lines)
274
394
 
275
395
            #print tag, i1, i2, j1, j2
276
396
 
287
407
                # we don't destroy ourselves
288
408
                i = i2 + offset
289
409
                self._weave[i:i] = ([('{', new_version)] 
290
 
                                + text[j1:j2] 
291
 
                                + [('}', new_version)])
 
410
                                    + lines[j1:j2] 
 
411
                                    + [('}', None)])
292
412
                offset += 2 + (j2 - j1)
293
 
 
294
413
        return new_version
295
414
 
 
415
    def clone_text(self, new_version_id, old_version_id, parents):
 
416
        """See VersionedFile.clone_text."""
 
417
        old_lines = self.get_text(old_version_id)
 
418
        self.add_lines(new_version_id, parents, old_lines)
296
419
 
297
 
    def inclusions(self, versions):
 
420
    def _inclusions(self, versions):
298
421
        """Return set of all ancestors of given version(s)."""
299
422
        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)
310
 
 
311
 
 
312
 
    def minimal_parents(self, version):
313
 
        """Find the minimal set of parents for the version."""
314
 
        included = self._parents[version]
315
 
        if not included:
 
423
        for v in xrange(max(versions), 0, -1):
 
424
            if v in i:
 
425
                # include all its parents
 
426
                i.update(self._parents[v])
 
427
        return i
 
428
        ## except IndexError:
 
429
        ##     raise ValueError("version %d not present in weave" % v)
 
430
 
 
431
    @deprecated_method(zero_eight)
 
432
    def inclusions(self, version_ids):
 
433
        """Deprecated - see VersionedFile.get_ancestry for the replacement."""
 
434
        if not version_ids:
316
435
            return []
317
 
        
318
 
        li = list(included)
319
 
        li.sort(reverse=True)
320
 
 
321
 
        mininc = []
322
 
        gotit = set()
323
 
 
324
 
        for pv in li:
325
 
            if pv not in gotit:
326
 
                mininc.append(pv)
327
 
                gotit.update(self.inclusions(pv))
328
 
 
329
 
        assert mininc[0] >= 0
330
 
        assert mininc[-1] < version
331
 
        return mininc
332
 
 
333
 
 
 
436
        if isinstance(version_ids[0], int):
 
437
            return [self._idx_to_name(v) for v in self._inclusions(version_ids)]
 
438
        else:
 
439
            return self.get_ancestry(version_ids)
 
440
 
 
441
    def get_ancestry(self, version_ids):
 
442
        """See VersionedFile.get_ancestry."""
 
443
        if isinstance(version_ids, basestring):
 
444
            version_ids = [version_ids]
 
445
        i = self._inclusions([self._lookup(v) for v in version_ids])
 
446
        return [self._idx_to_name(v) for v in i]
334
447
 
335
448
    def _check_lines(self, text):
336
449
        if not isinstance(text, list):
351
464
            except IndexError:
352
465
                raise IndexError("invalid version number %r" % i)
353
466
 
 
467
    def annotate(self, version_id):
 
468
        if isinstance(version_id, int):
 
469
            warn('Weave.annotate(int) is deprecated. Please use version names'
 
470
                 ' in all circumstances as of 0.8',
 
471
                 DeprecationWarning,
 
472
                 stacklevel=2
 
473
                 )
 
474
            result = []
 
475
            for origin, lineno, text in self._extract([version_id]):
 
476
                result.append((origin, text))
 
477
            return result
 
478
        else:
 
479
            return super(Weave, self).annotate(version_id)
354
480
    
355
 
    def annotate(self, index):
356
 
        return list(self.annotate_iter(index))
357
 
 
358
 
 
359
 
    def annotate_iter(self, version):
360
 
        """Yield list of (index-id, line) pairs for the specified version.
 
481
    def annotate_iter(self, version_id):
 
482
        """Yield list of (version-id, line) pairs for the specified version.
361
483
 
362
484
        The index indicates when the line originated in the weave."""
363
 
        for origin, lineno, text in self._extract([version]):
364
 
            yield origin, text
365
 
 
366
 
 
 
485
        incls = [self._lookup(version_id)]
 
486
        for origin, lineno, text in self._extract(incls):
 
487
            yield self._idx_to_name(origin), text
 
488
 
 
489
    @deprecated_method(zero_eight)
367
490
    def _walk(self):
368
 
        """Walk the weave.
 
491
        """_walk has become walk, a supported api."""
 
492
        return self.walk()
369
493
 
370
 
        Yields sequence of
371
 
        (lineno, insert, deletes, text)
372
 
        for each literal line.
373
 
        """
 
494
    def walk(self, version_ids=None):
 
495
        """See VersionedFile.walk."""
374
496
        
375
497
        istack = []
376
498
        dset = set()
382
504
                c, v = l
383
505
                isactive = None
384
506
                if c == '{':
385
 
                    istack.append(v)
 
507
                    istack.append(self._idx_to_name(v))
386
508
                elif c == '}':
387
 
                    oldv = istack.pop()
 
509
                    istack.pop()
388
510
                elif c == '[':
389
 
                    assert v not in dset
390
 
                    dset.add(v)
 
511
                    assert self._idx_to_name(v) not in dset
 
512
                    dset.add(self._idx_to_name(v))
391
513
                elif c == ']':
392
 
                    dset.remove(v)
 
514
                    dset.remove(self._idx_to_name(v))
393
515
                else:
394
 
                    raise WeaveFormatError('unexpected instruction %r'
395
 
                                           % v)
 
516
                    raise WeaveFormatError('unexpected instruction %r' % v)
396
517
            else:
397
518
                assert isinstance(l, basestring)
398
519
                assert istack
399
 
                yield lineno, istack[-1], dset, l
 
520
                yield lineno, istack[-1], dset.copy(), l
400
521
            lineno += 1
401
522
 
402
 
 
 
523
        if istack:
 
524
            raise WeaveFormatError("unclosed insertion blocks "
 
525
                    "at end of weave: %s" % istack)
 
526
        if dset:
 
527
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
 
528
                                   % dset)
403
529
 
404
530
    def _extract(self, versions):
405
531
        """Yield annotation of lines in included set.
410
536
 
411
537
        The set typically but not necessarily corresponds to a version.
412
538
        """
413
 
        included = self.inclusions(versions)
 
539
        for i in versions:
 
540
            if not isinstance(i, int):
 
541
                raise ValueError(i)
 
542
            
 
543
        included = self._inclusions(versions)
414
544
 
415
545
        istack = []
416
546
        dset = set()
431
561
                    assert v not in istack
432
562
                    istack.append(v)
433
563
                elif c == '}':
434
 
                    oldv = istack.pop()
435
 
                    assert oldv == v
 
564
                    istack.pop()
436
565
                elif c == '[':
437
566
                    if v in included:
438
567
                        assert v not in dset
449
578
                if isactive:
450
579
                    result.append((istack[-1], lineno, l))
451
580
            lineno += 1
452
 
 
453
581
        if istack:
454
 
            raise WFE("unclosed insertion blocks at end of weave",
455
 
                                   istack)
 
582
            raise WeaveFormatError("unclosed insertion blocks "
 
583
                    "at end of weave: %s" % istack)
456
584
        if dset:
457
 
            raise WFE("unclosed deletion blocks at end of weave",
458
 
                                   dset)
459
 
 
 
585
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
 
586
                                   % dset)
460
587
        return result
461
 
    
462
 
 
463
 
 
464
 
    def get_iter(self, version):
 
588
 
 
589
    @deprecated_method(zero_eight)
 
590
    def get_iter(self, name_or_index):
 
591
        """Deprecated, please do not use. Lookups are not not needed."""
 
592
        return self._get_iter(self._maybe_lookup(name_or_index))
 
593
 
 
594
    @deprecated_method(zero_eight)
 
595
    def maybe_lookup(self, name_or_index):
 
596
        """Deprecated, please do not use. Lookups are not not needed."""
 
597
        return self._maybe_lookup(name_or_index)
 
598
 
 
599
    def _maybe_lookup(self, name_or_index):
 
600
        """Convert possible symbolic name to index, or pass through indexes.
 
601
        
 
602
        NOT FOR PUBLIC USE.
 
603
        """
 
604
        if isinstance(name_or_index, (int, long)):
 
605
            return name_or_index
 
606
        else:
 
607
            return self._lookup(name_or_index)
 
608
 
 
609
    def _get_iter(self, version_id):
465
610
        """Yield lines for the specified version."""
466
 
        for origin, lineno, line in self._extract([version]):
 
611
        incls = [self._maybe_lookup(version_id)]
 
612
        if len(incls) == 1:
 
613
            index = incls[0]
 
614
            cur_sha = sha.new()
 
615
        else:
 
616
            # We don't have sha1 sums for multiple entries
 
617
            cur_sha = None
 
618
        for origin, lineno, line in self._extract(incls):
 
619
            if cur_sha:
 
620
                cur_sha.update(line)
467
621
            yield line
468
 
 
469
 
 
470
 
    def get(self, index):
471
 
        return list(self.get_iter(index))
472
 
 
473
 
 
474
 
    def mash_iter(self, included):
475
 
        """Return composed version of multiple included versions."""
476
 
        for origin, lineno, text in self._extract(included):
477
 
            yield text
478
 
 
479
 
 
480
 
    def dump(self, to_file):
481
 
        from pprint import pprint
482
 
        print >>to_file, "Weave._weave = ",
483
 
        pprint(self._weave, to_file)
484
 
        print >>to_file, "Weave._parents = ",
485
 
        pprint(self._parents, to_file)
486
 
 
487
 
 
 
622
        if cur_sha:
 
623
            expected_sha1 = self._sha1s[index]
 
624
            measured_sha1 = cur_sha.hexdigest() 
 
625
            if measured_sha1 != expected_sha1:
 
626
                raise errors.WeaveInvalidChecksum(
 
627
                        'file %s, revision %s, expected: %s, measured %s' 
 
628
                        % (self._weave_name, self._names[index],
 
629
                           expected_sha1, measured_sha1))
 
630
 
 
631
    @deprecated_method(zero_eight)
 
632
    def get(self, version_id):
 
633
        """Please use either Weave.get_text or Weave.get_lines as desired."""
 
634
        return self.get_lines(version_id)
 
635
 
 
636
    def get_lines(self, version_id):
 
637
        """See VersionedFile.get_lines()."""
 
638
        return list(self._get_iter(version_id))
 
639
 
 
640
    def get_sha1(self, name):
 
641
        """Get the stored sha1 sum for the given revision.
 
642
        
 
643
        :param name: The name of the version to lookup
 
644
        """
 
645
        return self._sha1s[self._lookup(name)]
488
646
 
489
647
    def numversions(self):
490
648
        l = len(self._parents)
491
649
        assert l == len(self._sha1s)
492
650
        return l
493
651
 
494
 
 
495
 
    def __len__(self):
496
 
        return self.numversions()
497
 
 
 
652
    __len__ = numversions
498
653
 
499
654
    def check(self, progress_bar=None):
 
655
        # TODO evaluate performance hit of using string sets in this routine.
500
656
        # check no circular inclusions
501
657
        for version in range(self.numversions()):
502
658
            inclusions = list(self._parents[version])
506
662
                    raise WeaveFormatError("invalid included version %d for index %d"
507
663
                                           % (inclusions[-1], version))
508
664
 
509
 
        # try extracting all versions; this is a bit slow and parallel
510
 
        # extraction could be used
511
 
        import sha
 
665
        # try extracting all versions; parallel extraction is used
512
666
        nv = self.numversions()
513
 
        for version in range(nv):
 
667
        sha1s = {}
 
668
        texts = {}
 
669
        inclusions = {}
 
670
        for i in range(nv):
 
671
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
 
672
            # The problem is that set membership is much more expensive
 
673
            name = self._idx_to_name(i)
 
674
            sha1s[name] = sha.new()
 
675
            texts[name] = []
 
676
            new_inc = set([name])
 
677
            for p in self._parents[i]:
 
678
                new_inc.update(inclusions[self._idx_to_name(p)])
 
679
 
 
680
            assert set(new_inc) == set(self.get_ancestry(name)), \
 
681
                'failed %s != %s' % (set(new_inc), set(self.get_ancestry(name)))
 
682
            inclusions[name] = new_inc
 
683
 
 
684
        nlines = len(self._weave)
 
685
 
 
686
        update_text = 'checking weave'
 
687
        if self._weave_name:
 
688
            short_name = os.path.basename(self._weave_name)
 
689
            update_text = 'checking %s' % (short_name,)
 
690
            update_text = update_text[:25]
 
691
 
 
692
        for lineno, insert, deleteset, line in self.walk():
514
693
            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()
520
 
            expected = self._sha1s[version]
 
694
                progress_bar.update(update_text, lineno, nlines)
 
695
 
 
696
            for name, name_inclusions in inclusions.items():
 
697
                # The active inclusion must be an ancestor,
 
698
                # and no ancestors must have deleted this line,
 
699
                # because we don't support resurrection.
 
700
                if (insert in name_inclusions) and not (deleteset & name_inclusions):
 
701
                    sha1s[name].update(line)
 
702
 
 
703
        for i in range(nv):
 
704
            version = self._idx_to_name(i)
 
705
            hd = sha1s[version].hexdigest()
 
706
            expected = self._sha1s[i]
521
707
            if hd != expected:
522
 
                raise WeaveError("mismatched sha1 for version %d; "
523
 
                                 "got %s, expected %s"
524
 
                                 % (version, hd, expected))
 
708
                raise errors.WeaveInvalidChecksum(
 
709
                        "mismatched sha1 for version %s: "
 
710
                        "got %s, expected %s"
 
711
                        % (version, hd, expected))
525
712
 
526
713
        # TODO: check insertions are properly nested, that there are
527
714
        # no lines outside of insertion blocks, that deletions are
528
715
        # properly paired, etc.
529
716
 
530
717
 
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
 
    def _delta(self, included, lines):
550
 
        """Return changes from basis to new revision.
551
 
 
552
 
        The old text for comparison is the union of included revisions.
553
 
 
554
 
        This is used in inserting a new text.
555
 
 
556
 
        Delta is returned as a sequence of
557
 
        (weave1, weave2, newlines).
558
 
 
559
 
        This indicates that weave1:weave2 of the old weave should be
560
 
        replaced by the sequence of lines in newlines.  Note that
561
 
        these line numbers are positions in the total weave and don't
562
 
        correspond to the lines in any extracted version, or even the
563
 
        extracted union of included versions.
564
 
 
565
 
        If line1=line2, this is a pure insert; if newlines=[] this is a
566
 
        pure delete.  (Similar to difflib.)
567
 
        """
568
 
 
569
 
 
570
 
            
571
 
    def plan_merge(self, ver_a, ver_b):
572
 
        """Return pseudo-annotation indicating how the two versions merge.
573
 
 
574
 
        This is computed between versions a and b and their common
575
 
        base.
576
 
 
577
 
        Weave lines present in none of them are skipped entirely.
578
 
        """
579
 
        inc_a = self.inclusions([ver_a])
580
 
        inc_b = self.inclusions([ver_b])
581
 
        inc_c = inc_a & inc_b
582
 
 
583
 
        for lineno, insert, deleteset, line in self._walk():
584
 
            if deleteset & inc_c:
585
 
                # killed in parent; can't be in either a or b
586
 
                # not relevant to our work
587
 
                yield 'killed-base', line
588
 
            elif insert in inc_c:
589
 
                # was inserted in base
590
 
                killed_a = bool(deleteset & inc_a)
591
 
                killed_b = bool(deleteset & inc_b)
592
 
                if killed_a and killed_b:
593
 
                    yield 'killed-both', line
594
 
                elif killed_a:
595
 
                    yield 'killed-a', line
596
 
                elif killed_b:
597
 
                    yield 'killed-b', line
598
 
                else:
599
 
                    yield 'unchanged', line
600
 
            elif insert in inc_a:
601
 
                if deleteset & inc_a:
602
 
                    yield 'ghost-a', line
603
 
                else:
604
 
                    # new in A; not in B
605
 
                    yield 'new-a', line
606
 
            elif insert in inc_b:
607
 
                if deleteset & inc_b:
608
 
                    yield 'ghost-b', line
609
 
                else:
610
 
                    yield 'new-b', line
611
 
            else:
612
 
                # not in either revision
613
 
                yield 'irrelevant', line
614
 
 
615
 
        yield 'unchanged', ''           # terminator
616
 
 
617
 
 
618
 
 
619
 
    def weave_merge(self, plan):
620
 
        lines_a = []
621
 
        lines_b = []
622
 
        ch_a = ch_b = False
623
 
 
624
 
        for state, line in plan:
625
 
            if state == 'unchanged' or state == 'killed-both':
626
 
                # resync and flush queued conflicts changes if any
627
 
                if not lines_a and not lines_b:
628
 
                    pass
629
 
                elif ch_a and not ch_b:
630
 
                    # one-sided change:                    
631
 
                    for l in lines_a: yield l
632
 
                elif ch_b and not ch_a:
633
 
                    for l in lines_b: yield l
634
 
                elif lines_a == lines_b:
635
 
                    for l in lines_a: yield l
636
 
                else:
637
 
                    yield '<<<<\n'
638
 
                    for l in lines_a: yield l
639
 
                    yield '====\n'
640
 
                    for l in lines_b: yield l
641
 
                    yield '>>>>\n'
642
 
 
643
 
                del lines_a[:]
644
 
                del lines_b[:]
645
 
                ch_a = ch_b = False
646
 
                
647
 
            if state == 'unchanged':
648
 
                if line:
649
 
                    yield line
650
 
            elif state == 'killed-a':
651
 
                ch_a = True
652
 
                lines_b.append(line)
653
 
            elif state == 'killed-b':
654
 
                ch_b = True
655
 
                lines_a.append(line)
656
 
            elif state == 'new-a':
657
 
                ch_a = True
658
 
                lines_a.append(line)
659
 
            elif state == 'new-b':
660
 
                ch_b = True
661
 
                lines_b.append(line)
662
 
            else:
663
 
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 'killed-base',
664
 
                                 'killed-both'), \
665
 
                       state
666
 
 
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):
 
718
    def join(self, other, pb=None, msg=None, version_ids=None):
 
719
        import sys, time
 
720
        """Integrate versions from other into this weave.
 
721
 
 
722
        The resulting weave contains all the history of both weaves; 
 
723
        any version you could retrieve from either self or other can be 
 
724
        retrieved from self after this call.
 
725
 
 
726
        It is illegal for the two weaves to contain different values 
 
727
        or different parents for any version.  See also reweave().
 
728
 
 
729
        :param other: The other weave to pull into this one
 
730
        :param pb: An optional progress bar
 
731
        :param msg: An optional message to display for progress
 
732
        """
 
733
        if not other.versions():
 
734
            return          # nothing to update, easy
 
735
 
 
736
        if version_ids:
 
737
            for version_id in version_ids:
 
738
                if not self.has_version(version_id):
 
739
                    raise RevisionNotPresent(version_id, self._weave_name)
 
740
        assert version_ids == None
 
741
 
 
742
        # two loops so that we do not change ourselves before verifying it
 
743
        # will be ok
 
744
        # work through in index order to make sure we get all dependencies
 
745
        names_to_join = []
 
746
        processed = 0
 
747
        for other_idx, name in enumerate(other._names):
 
748
            self._check_version_consistent(other, other_idx, name)
 
749
            sha1 = other._sha1s[other_idx]
 
750
 
 
751
            processed += 1
 
752
 
 
753
            if name in self._name_map:
 
754
                idx = self._lookup(name)
 
755
                n1 = set(map(other._idx_to_name, other._parents[other_idx]))
 
756
                n2 = set(map(self._idx_to_name, self._parents[idx]))
 
757
                if sha1 ==  self._sha1s[idx] and n1 == n2:
 
758
                        continue
 
759
 
 
760
            names_to_join.append((other_idx, name))
 
761
 
 
762
        if pb and not msg:
 
763
            msg = 'weave join'
 
764
 
 
765
        merged = 0
 
766
        time0 = time.time()
 
767
        for other_idx, name in names_to_join:
 
768
            # TODO: If all the parents of the other version are already
 
769
            # present then we can avoid some work by just taking the delta
 
770
            # and adjusting the offsets.
 
771
            new_parents = self._imported_parents(other, other_idx)
 
772
            sha1 = other._sha1s[other_idx]
 
773
 
 
774
            merged += 1
 
775
 
 
776
            if pb:
 
777
                pb.update(msg, merged, len(names_to_join))
 
778
           
 
779
            lines = other.get_lines(other_idx)
 
780
            self._add(name, lines, new_parents, sha1)
 
781
 
 
782
        mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
 
783
                merged, processed, self._weave_name, time.time()-time0))
 
784
 
 
785
    def _imported_parents(self, other, other_idx):
 
786
        """Return list of parents in self corresponding to indexes in other."""
 
787
        new_parents = []
 
788
        for parent_idx in other._parents[other_idx]:
 
789
            parent_name = other._names[parent_idx]
 
790
            if parent_name not in self._names:
 
791
                # should not be possible
 
792
                raise WeaveError("missing parent {%s} of {%s} in %r" 
 
793
                                 % (parent_name, other._name_map[other_idx], self))
 
794
            new_parents.append(self._name_map[parent_name])
 
795
        return new_parents
 
796
 
 
797
    def _check_version_consistent(self, other, other_idx, name):
 
798
        """Check if a version in consistent in this and other.
 
799
 
 
800
        To be consistent it must have:
 
801
 
 
802
         * the same text
 
803
         * the same direct parents (by name, not index, and disregarding
 
804
           order)
 
805
        
 
806
        If present & correct return True;
 
807
        if not present in self return False; 
 
808
        if inconsistent raise error."""
 
809
        this_idx = self._name_map.get(name, -1)
 
810
        if this_idx != -1:
 
811
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
 
812
                raise WeaveError("inconsistent texts for version {%s} "
 
813
                                 "when joining weaves"
 
814
                                 % (name))
 
815
            self_parents = self._parents[this_idx]
 
816
            other_parents = other._parents[other_idx]
 
817
            n1 = set([self._names[i] for i in self_parents])
 
818
            n2 = set([other._names[i] for i in other_parents])
 
819
            if n1 != n2:
 
820
                raise WeaveParentMismatch("inconsistent parents "
 
821
                    "for version {%s}: %s vs %s" % (name, n1, n2))
 
822
            else:
 
823
                return True         # ok!
 
824
        else:
 
825
            return False
 
826
 
 
827
    def reweave(self, other, pb=None, msg=None):
 
828
        """Reweave self with other.
 
829
 
 
830
        :param other: The other weave to merge
 
831
        :param pb: An optional progress bar, indicating how far done we are
 
832
        :param msg: An optional message for the progress
 
833
        """
 
834
        new_weave = reweave(self, other, pb=pb, msg=msg)
 
835
        for attr in self.__slots__:
 
836
            setattr(self, attr, getattr(new_weave, attr))
 
837
 
 
838
 
 
839
def reweave(wa, wb, pb=None, msg=None):
 
840
    """Combine two weaves and return the result.
 
841
 
 
842
    This works even if a revision R has different parents in 
 
843
    wa and wb.  In the resulting weave all the parents are given.
 
844
 
 
845
    This is done by just building up a new weave, maintaining ordering 
 
846
    of the versions in the two inputs.  More efficient approaches
 
847
    might be possible but it should only be necessary to do 
 
848
    this operation rarely, when a new previously ghost version is 
 
849
    inserted.
 
850
 
 
851
    :param pb: An optional progress bar, indicating how far done we are
 
852
    :param msg: An optional message for the progress
 
853
    """
 
854
    wr = Weave()
 
855
    ia = ib = 0
 
856
    queue_a = range(wa.numversions())
 
857
    queue_b = range(wb.numversions())
 
858
    # first determine combined parents of all versions
 
859
    # map from version name -> all parent names
 
860
    combined_parents = _reweave_parent_graphs(wa, wb)
 
861
    mutter("combined parents: %r", combined_parents)
 
862
    order = topo_sort(combined_parents.iteritems())
 
863
    mutter("order to reweave: %r", order)
 
864
 
 
865
    if pb and not msg:
 
866
        msg = 'reweave'
 
867
 
 
868
    for idx, name in enumerate(order):
 
869
        if pb:
 
870
            pb.update(msg, idx, len(order))
 
871
        if name in wa._name_map:
 
872
            lines = wa.get_lines(name)
 
873
            if name in wb._name_map:
 
874
                lines_b = wb.get_lines(name)
 
875
                if lines != lines_b:
 
876
                    mutter('Weaves differ on content. rev_id {%s}', name)
 
877
                    mutter('weaves: %s, %s', wa._weave_name, wb._weave_name)
 
878
                    import difflib
 
879
                    lines = list(difflib.unified_diff(lines, lines_b,
 
880
                            wa._weave_name, wb._weave_name))
 
881
                    mutter('lines:\n%s', ''.join(lines))
 
882
                    raise errors.WeaveTextDiffers(name, wa, wb)
 
883
        else:
 
884
            lines = wb.get_lines(name)
 
885
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
 
886
    return wr
 
887
 
 
888
def _reweave_parent_graphs(wa, wb):
 
889
    """Return combined parent ancestry for two weaves.
 
890
    
 
891
    Returned as a list of (version_name, set(parent_names))"""
 
892
    combined = {}
 
893
    for weave in [wa, wb]:
 
894
        for idx, name in enumerate(weave._names):
 
895
            p = combined.setdefault(name, set())
 
896
            p.update(map(weave._idx_to_name, weave._parents[idx]))
 
897
    return combined
 
898
 
 
899
 
 
900
def weave_toc(w):
 
901
    """Show the weave's table-of-contents"""
 
902
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
 
903
    for i in (6, 50, 10, 10):
677
904
        print '-' * i,
678
905
    print
679
906
    for i in range(w.numversions()):
680
907
        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
 
908
        name = w._names[i]
 
909
        parent_str = ' '.join(map(str, w._parents[i]))
 
910
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
 
911
 
 
912
 
 
913
 
 
914
def weave_stats(weave_file, pb):
687
915
    from bzrlib.weavefile import read_weave
688
916
 
689
 
    pb = ProgressBar()
690
 
 
691
917
    wf = file(weave_file, 'rb')
692
 
    w = read_weave(wf)
 
918
    w = read_weave(wf, WeaveVersionedFile)
693
919
    # FIXME: doesn't work on pipes
694
920
    weave_size = wf.tell()
695
921
 
697
923
    vers = len(w)
698
924
    for i in range(vers):
699
925
        pb.update('checking sizes', i, vers)
700
 
        for line in w.get_iter(i):
 
926
        for origin, lineno, line in w._extract([i]):
701
927
            total += len(line)
702
928
 
703
929
    pb.clear()
706
932
    print 'weave file        %9d bytes' % weave_size
707
933
    print 'total contents    %9d bytes' % total
708
934
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
709
 
 
 
935
    if vers:
 
936
        avg = total/vers
 
937
        print 'average size      %9d bytes' % avg
 
938
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
710
939
 
711
940
 
712
941
def usage():
721
950
        Write out specified version.
722
951
    weave check WEAVEFILE
723
952
        Check consistency of all versions.
724
 
    weave info WEAVEFILE
 
953
    weave toc WEAVEFILE
725
954
        Display table of contents.
726
 
    weave add WEAVEFILE [BASE...] < NEWTEXT
 
955
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
727
956
        Add NEWTEXT, with specified parent versions.
728
957
    weave annotate WEAVEFILE VERSION
729
958
        Display origin of each line.
730
 
    weave mash WEAVEFILE VERSION...
731
 
        Display composite of all selected versions.
732
959
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
733
960
        Auto-merge two versions and display conflicts.
 
961
    weave diff WEAVEFILE VERSION1 VERSION2 
 
962
        Show differences between two versions.
734
963
 
735
964
example:
736
965
 
737
966
    % weave init foo.weave
738
967
    % vi foo.txt
739
 
    % weave add foo.weave < foo.txt
 
968
    % weave add foo.weave ver0 < foo.txt
740
969
    added version 0
741
970
 
742
971
    (create updated version)
743
972
    % vi foo.txt
744
973
    % weave get foo.weave 0 | diff -u - foo.txt
745
 
    % weave add foo.weave 0 < foo.txt
 
974
    % weave add foo.weave ver1 0 < foo.txt
746
975
    added version 1
747
976
 
748
977
    % weave get foo.weave 0 > foo.txt       (create forked version)
749
978
    % vi foo.txt
750
 
    % weave add foo.weave 0 < foo.txt
 
979
    % weave add foo.weave ver2 0 < foo.txt
751
980
    added version 2
752
981
 
753
982
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
754
983
    % vi foo.txt                            (resolve conflicts)
755
 
    % weave add foo.weave 1 2 < foo.txt     (commit merged version)     
 
984
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
756
985
    
757
986
"""
758
987
    
761
990
def main(argv):
762
991
    import sys
763
992
    import os
764
 
    from weavefile import write_weave, read_weave
 
993
    try:
 
994
        import bzrlib
 
995
    except ImportError:
 
996
        # in case we're run directly from the subdirectory
 
997
        sys.path.append('..')
 
998
        import bzrlib
 
999
    from bzrlib.weavefile import write_weave, read_weave
765
1000
    from bzrlib.progress import ProgressBar
766
1001
 
767
 
    #import psyco
768
 
    #psyco.full()
 
1002
    try:
 
1003
        import psyco
 
1004
        psyco.full()
 
1005
    except ImportError:
 
1006
        pass
 
1007
 
 
1008
    if len(argv) < 2:
 
1009
        usage()
 
1010
        return 0
769
1011
 
770
1012
    cmd = argv[1]
771
1013
 
777
1019
    elif cmd == 'add':
778
1020
        w = readit()
779
1021
        # at the moment, based on everything in the file
780
 
        parents = map(int, argv[3:])
 
1022
        name = argv[3]
 
1023
        parents = map(int, argv[4:])
781
1024
        lines = sys.stdin.readlines()
782
 
        ver = w.add(parents, lines)
 
1025
        ver = w.add(name, parents, lines)
783
1026
        write_weave(w, file(argv[2], 'wb'))
784
 
        print 'added version %d' % ver
 
1027
        print 'added version %r %d' % (name, ver)
785
1028
    elif cmd == 'init':
786
1029
        fn = argv[2]
787
1030
        if os.path.exists(fn):
792
1035
        w = readit()
793
1036
        sys.stdout.writelines(w.get_iter(int(argv[3])))
794
1037
        
795
 
    elif cmd == 'mash': # get composite
 
1038
    elif cmd == 'diff':
 
1039
        from difflib import unified_diff
796
1040
        w = readit()
797
 
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
798
 
 
 
1041
        fn = argv[2]
 
1042
        v1, v2 = map(int, argv[3:5])
 
1043
        lines1 = w.get(v1)
 
1044
        lines2 = w.get(v2)
 
1045
        diff_gen = unified_diff(lines1, lines2,
 
1046
                                '%s version %d' % (fn, v1),
 
1047
                                '%s version %d' % (fn, v2))
 
1048
        sys.stdout.writelines(diff_gen)
 
1049
            
799
1050
    elif cmd == 'annotate':
800
1051
        w = readit()
801
1052
        # newline is added to all lines regardless; too hard to get
809
1060
                print '%5d | %s' % (origin, text)
810
1061
                lasto = origin
811
1062
                
812
 
    elif cmd == 'info':
813
 
        weave_info(readit())
 
1063
    elif cmd == 'toc':
 
1064
        weave_toc(readit())
814
1065
 
815
1066
    elif cmd == 'stats':
816
 
        weave_stats(argv[2])
 
1067
        weave_stats(argv[2], ProgressBar())
817
1068
        
818
1069
    elif cmd == 'check':
819
1070
        w = readit()
841
1092
        p = w.plan_merge(int(argv[3]), int(argv[4]))
842
1093
        sys.stdout.writelines(w.weave_merge(p))
843
1094
            
844
 
    elif cmd == 'mash-merge':
845
 
        if len(argv) != 5:
846
 
            usage()
847
 
            return 1
848
 
 
849
 
        w = readit()
850
 
        v1, v2 = map(int, argv[3:5])
851
 
 
852
 
        basis = w.inclusions([v1]).intersection(w.inclusions([v2]))
853
 
 
854
 
        base_lines = list(w.mash_iter(basis))
855
 
        a_lines = list(w.get(v1))
856
 
        b_lines = list(w.get(v2))
857
 
 
858
 
        from bzrlib.merge3 import Merge3
859
 
        m3 = Merge3(base_lines, a_lines, b_lines)
860
 
 
861
 
        name_a = 'version %d' % v1
862
 
        name_b = 'version %d' % v2
863
 
        sys.stdout.writelines(m3.merge_lines(name_a=name_a, name_b=name_b))
864
1095
    else:
865
1096
        raise ValueError('unknown command %r' % cmd)
866
1097
    
867
1098
 
 
1099
 
 
1100
def profile_main(argv): 
 
1101
    import tempfile, hotshot, hotshot.stats
 
1102
 
 
1103
    prof_f = tempfile.NamedTemporaryFile()
 
1104
 
 
1105
    prof = hotshot.Profile(prof_f.name)
 
1106
 
 
1107
    ret = prof.runcall(main, argv)
 
1108
    prof.close()
 
1109
 
 
1110
    stats = hotshot.stats.load(prof_f.name)
 
1111
    #stats.strip_dirs()
 
1112
    stats.sort_stats('cumulative')
 
1113
    ## XXX: Might like to write to stderr or the trace file instead but
 
1114
    ## print_stats seems hardcoded to stdout
 
1115
    stats.print_stats(20)
 
1116
            
 
1117
    return ret
 
1118
 
 
1119
 
 
1120
def lsprofile_main(argv): 
 
1121
    from bzrlib.lsprof import profile
 
1122
    ret,stats = profile(main, argv)
 
1123
    stats.sort()
 
1124
    stats.pprint()
 
1125
    return ret
 
1126
 
 
1127
 
868
1128
if __name__ == '__main__':
869
1129
    import sys
870
 
    sys.exit(main(sys.argv))
 
1130
    if '--profile' in sys.argv:
 
1131
        args = sys.argv[:]
 
1132
        args.remove('--profile')
 
1133
        sys.exit(profile_main(args))
 
1134
    elif '--lsprof' in sys.argv:
 
1135
        args = sys.argv[:]
 
1136
        args.remove('--lsprof')
 
1137
        sys.exit(lsprofile_main(args))
 
1138
    else:
 
1139
        sys.exit(main(sys.argv))
 
1140