~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

[merge] 0.7-bugfix: Fix fileid_involved to unescape xml characters, fix StubServer to handle paramiko > 1.5.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#! /usr/bin/python
2
2
 
3
3
# Copyright (C) 2005 Canonical Ltd
4
 
#
 
4
 
5
5
# This program is free software; you can redistribute it and/or modify
6
6
# it under the terms of the GNU General Public License as published by
7
7
# the Free Software Foundation; either version 2 of the License, or
8
8
# (at your option) any later version.
9
 
#
 
9
 
10
10
# This program is distributed in the hope that it will be useful,
11
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
13
# GNU General Public License for more details.
14
 
#
 
14
 
15
15
# You should have received a copy of the GNU General Public License
16
16
# along with this program; if not, write to the Free Software
17
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
27
# property.
28
28
 
29
29
# TODO: Nothing here so far assumes the lines are really \n newlines,
30
 
# rather than being split up in some other way.  We could accommodate
 
30
# rather than being split up in some other way.  We could accomodate
31
31
# binaries, perhaps by naively splitting on \n or perhaps using
32
32
# something like a rolling checksum.
33
33
 
66
66
# be done fairly efficiently because the sequence numbers constrain
67
67
# the possible relationships.
68
68
 
69
 
# FIXME: the conflict markers should be *7* characters
70
69
 
71
 
from copy import copy
72
 
from cStringIO import StringIO
73
70
import os
74
71
import sha
75
 
import time
76
 
import warnings
 
72
from difflib import SequenceMatcher
77
73
 
78
 
from bzrlib import (
79
 
    progress,
80
 
    )
81
74
from bzrlib.trace import mutter
82
75
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
83
 
        RevisionAlreadyPresent,
84
 
        RevisionNotPresent,
85
 
        WeaveRevisionAlreadyPresent,
86
 
        WeaveRevisionNotPresent,
87
 
        )
 
76
        WeaveRevisionNotPresent, WeaveRevisionAlreadyPresent)
88
77
import bzrlib.errors as errors
89
 
from bzrlib.osutils import sha_strings
90
 
import bzrlib.patiencediff
91
78
from bzrlib.tsort import topo_sort
92
 
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
93
 
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
94
 
 
95
 
 
96
 
class Weave(VersionedFile):
 
79
 
 
80
 
 
81
class Weave(object):
97
82
    """weave - versioned text file storage.
98
83
    
99
84
    A Weave manages versions of line-based text files, keeping track
183
168
    """
184
169
 
185
170
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
186
 
                 '_weave_name', '_matcher']
 
171
                 '_weave_name']
187
172
    
188
 
    def __init__(self, weave_name=None, access_mode='w', matcher=None):
189
 
        super(Weave, self).__init__(access_mode)
 
173
    def __init__(self, weave_name=None):
190
174
        self._weave = []
191
175
        self._parents = []
192
176
        self._sha1s = []
193
177
        self._names = []
194
178
        self._name_map = {}
195
179
        self._weave_name = weave_name
196
 
        if matcher is None:
197
 
            self._matcher = bzrlib.patiencediff.PatienceSequenceMatcher
198
 
        else:
199
 
            self._matcher = matcher
200
180
 
201
181
    def __repr__(self):
202
182
        return "Weave(%r)" % self._weave_name
203
183
 
 
184
 
204
185
    def copy(self):
205
186
        """Return a deep copy of self.
206
187
        
220
201
        return self._parents == other._parents \
221
202
               and self._weave == other._weave \
222
203
               and self._sha1s == other._sha1s 
 
204
 
223
205
    
224
206
    def __ne__(self, other):
225
207
        return not self.__eq__(other)
226
208
 
227
 
    def _idx_to_name(self, version):
228
 
        return self._names[version]
229
 
 
230
 
    def _lookup(self, name):
 
209
    def __contains__(self, name):
 
210
        return self._name_map.has_key(name)
 
211
 
 
212
    def maybe_lookup(self, name_or_index):
 
213
        """Convert possible symbolic name to index, or pass through indexes."""
 
214
        if isinstance(name_or_index, (int, long)):
 
215
            return name_or_index
 
216
        else:
 
217
            return self.lookup(name_or_index)
 
218
 
 
219
        
 
220
    def lookup(self, name):
231
221
        """Convert symbolic version name to index."""
232
 
        self.check_not_reserved_id(name)
233
222
        try:
234
223
            return self._name_map[name]
235
224
        except KeyError:
236
 
            raise RevisionNotPresent(name, self._weave_name)
 
225
            raise WeaveRevisionNotPresent(name, self)
237
226
 
238
 
    def versions(self):
239
 
        """See VersionedFile.versions."""
 
227
    def names(self):
240
228
        return self._names[:]
241
229
 
242
 
    def has_version(self, version_id):
243
 
        """See VersionedFile.has_version."""
244
 
        return (version_id in self._name_map)
245
 
 
246
 
    __contains__ = has_version
247
 
 
248
 
    def get_parents(self, version_id):
249
 
        """See VersionedFile.get_parent."""
250
 
        return map(self._idx_to_name, self._parents[self._lookup(version_id)])
 
230
    def iter_names(self):
 
231
        """Yield a list of all names in this weave."""
 
232
        return iter(self._names)
 
233
 
 
234
    def idx_to_name(self, version):
 
235
        return self._names[version]
251
236
 
252
237
    def _check_repeated_add(self, name, parents, text, sha1):
253
238
        """Check that a duplicated add is OK.
254
239
 
255
240
        If it is, return the (old) index; otherwise raise an exception.
256
241
        """
257
 
        idx = self._lookup(name)
 
242
        idx = self.lookup(name)
258
243
        if sorted(self._parents[idx]) != sorted(parents) \
259
244
            or sha1 != self._sha1s[idx]:
260
 
            raise RevisionAlreadyPresent(name, self._weave_name)
 
245
            raise WeaveRevisionAlreadyPresent(name, self)
261
246
        return idx
262
 
 
263
 
    def _add_lines(self, version_id, parents, lines, parent_texts,
264
 
       left_matching_blocks, nostore_sha, random_id, check_content):
265
 
        """See VersionedFile.add_lines."""
266
 
        idx = self._add(version_id, lines, map(self._lookup, parents),
267
 
            nostore_sha=nostore_sha)
268
 
        return sha_strings(lines), sum(map(len, lines)), idx
269
 
 
270
 
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
 
247
        
 
248
    def add(self, name, parents, text, sha1=None):
271
249
        """Add a single text on top of the weave.
272
250
  
273
251
        Returns the index number of the newly added version.
274
252
 
275
 
        version_id
 
253
        name
276
254
            Symbolic name for this version.
277
255
            (Typically the revision-id of the revision that added it.)
278
256
 
279
257
        parents
280
258
            List or set of direct parent version numbers.
281
259
            
282
 
        lines
 
260
        text
283
261
            Sequence of lines to be added in the new version.
284
262
 
285
 
        :param nostore_sha: See VersionedFile.add_lines.
 
263
        sha -- SHA-1 of the file, if known.  This is trusted to be
 
264
            correct if supplied.
286
265
        """
287
 
        assert isinstance(version_id, basestring)
288
 
        self._check_lines_not_unicode(lines)
289
 
        self._check_lines_are_lines(lines)
290
 
        if not sha1:
291
 
            sha1 = sha_strings(lines)
292
 
        if sha1 == nostore_sha:
293
 
            raise errors.ExistingContent
294
 
        if version_id in self._name_map:
295
 
            return self._check_repeated_add(version_id, parents, lines, sha1)
296
 
 
 
266
        from bzrlib.osutils import sha_strings
 
267
 
 
268
        assert isinstance(name, basestring)
 
269
        if sha1 is None:
 
270
            sha1 = sha_strings(text)
 
271
        if name in self._name_map:
 
272
            return self._check_repeated_add(name, parents, text, sha1)
 
273
 
 
274
        parents = map(self.maybe_lookup, parents)
297
275
        self._check_versions(parents)
298
 
        ## self._check_lines(lines)
 
276
        ## self._check_lines(text)
299
277
        new_version = len(self._parents)
300
278
 
 
279
 
301
280
        # if we abort after here the (in-memory) weave will be corrupt because only
302
281
        # some fields are updated
303
 
        # XXX: FIXME implement a succeed-or-fail of the rest of this routine.
304
 
        #      - Robert Collins 20060226
305
282
        self._parents.append(parents[:])
306
283
        self._sha1s.append(sha1)
307
 
        self._names.append(version_id)
308
 
        self._name_map[version_id] = new_version
 
284
        self._names.append(name)
 
285
        self._name_map[name] = new_version
309
286
 
310
287
            
311
288
        if not parents:
313
290
            # this more quickly by just appending unconditionally.
314
291
            # even more specially, if we're adding an empty text we
315
292
            # need do nothing at all.
316
 
            if lines:
 
293
            if text:
317
294
                self._weave.append(('{', new_version))
318
 
                self._weave.extend(lines)
 
295
                self._weave.extend(text)
319
296
                self._weave.append(('}', None))
 
297
        
320
298
            return new_version
321
299
 
322
300
        if len(parents) == 1:
326
304
                return new_version
327
305
            
328
306
 
329
 
        ancestors = self._inclusions(parents)
 
307
        ancestors = self.inclusions(parents)
330
308
 
331
309
        l = self._weave
332
310
 
339
317
 
340
318
        # another small special case: a merge, producing the same text
341
319
        # as auto-merge
342
 
        if lines == basis_lines:
343
 
            return new_version
 
320
        if text == basis_lines:
 
321
            return new_version            
344
322
 
345
 
        # add a sentinel, because we can also match against the final line
 
323
        # add a sentinal, because we can also match against the final line
346
324
        basis_lineno.append(len(self._weave))
347
325
 
348
326
        # XXX: which line of the weave should we really consider
352
330
        #print 'basis_lines:', basis_lines
353
331
        #print 'new_lines:  ', lines
354
332
 
355
 
        s = self._matcher(None, basis_lines, lines)
 
333
        s = SequenceMatcher(None, basis_lines, text)
356
334
 
357
335
        # offset gives the number of lines that have been inserted
358
336
        # into the weave up to the current point; if the original edit instruction
369
347
            i1 = basis_lineno[i1]
370
348
            i2 = basis_lineno[i2]
371
349
 
372
 
            assert 0 <= j1 <= j2 <= len(lines)
 
350
            assert 0 <= j1 <= j2 <= len(text)
373
351
 
374
352
            #print tag, i1, i2, j1, j2
375
353
 
386
364
                # we don't destroy ourselves
387
365
                i = i2 + offset
388
366
                self._weave[i:i] = ([('{', new_version)] 
389
 
                                    + lines[j1:j2] 
 
367
                                    + text[j1:j2] 
390
368
                                    + [('}', None)])
391
369
                offset += 2 + (j2 - j1)
 
370
 
392
371
        return new_version
393
372
 
394
 
    def _clone_text(self, new_version_id, old_version_id, parents):
395
 
        """See VersionedFile.clone_text."""
396
 
        old_lines = self.get_text(old_version_id)
397
 
        self.add_lines(new_version_id, parents, old_lines)
 
373
    def add_identical(self, old_rev_id, new_rev_id, parents):
 
374
        """Add an identical text to old_rev_id as new_rev_id."""
 
375
        old_lines = self.get(self.lookup(old_rev_id))
 
376
        self.add(new_rev_id, parents, old_lines)
398
377
 
399
 
    def _inclusions(self, versions):
 
378
    def inclusions(self, versions):
400
379
        """Return set of all ancestors of given version(s)."""
401
 
        if not len(versions):
402
 
            return []
403
380
        i = set(versions)
404
381
        for v in xrange(max(versions), 0, -1):
405
382
            if v in i:
409
386
        ## except IndexError:
410
387
        ##     raise ValueError("version %d not present in weave" % v)
411
388
 
412
 
    def get_ancestry(self, version_ids, topo_sorted=True):
413
 
        """See VersionedFile.get_ancestry."""
414
 
        if isinstance(version_ids, basestring):
415
 
            version_ids = [version_ids]
416
 
        i = self._inclusions([self._lookup(v) for v in version_ids])
417
 
        return [self._idx_to_name(v) for v in i]
 
389
 
 
390
    def parents(self, version):
 
391
        return self._parents[version]
 
392
 
 
393
 
 
394
    def parent_names(self, version):
 
395
        """Return version names for parents of a version."""
 
396
        return map(self.idx_to_name, self._parents[self.lookup(version)])
 
397
 
 
398
 
 
399
    def minimal_parents(self, version):
 
400
        """Find the minimal set of parents for the version."""
 
401
        included = self._parents[version]
 
402
        if not included:
 
403
            return []
 
404
        
 
405
        li = list(included)
 
406
        li.sort(reverse=True)
 
407
 
 
408
        mininc = []
 
409
        gotit = set()
 
410
 
 
411
        for pv in li:
 
412
            if pv not in gotit:
 
413
                mininc.append(pv)
 
414
                gotit.update(self.inclusions(pv))
 
415
 
 
416
        assert mininc[0] >= 0
 
417
        assert mininc[-1] < version
 
418
        return mininc
 
419
 
 
420
 
418
421
 
419
422
    def _check_lines(self, text):
420
423
        if not isinstance(text, list):
435
438
            except IndexError:
436
439
                raise IndexError("invalid version number %r" % i)
437
440
 
438
 
    def _compatible_parents(self, my_parents, other_parents):
439
 
        """During join check that other_parents are joinable with my_parents.
440
 
 
441
 
        Joinable is defined as 'is a subset of' - supersets may require 
442
 
        regeneration of diffs, but subsets do not.
443
 
        """
444
 
        return len(other_parents.difference(my_parents)) == 0
445
 
 
446
 
    def annotate_iter(self, version_id):
447
 
        """Yield list of (version-id, line) pairs for the specified version.
 
441
    
 
442
    def annotate(self, name_or_index):
 
443
        return list(self.annotate_iter(name_or_index))
 
444
 
 
445
 
 
446
    def annotate_iter(self, name_or_index):
 
447
        """Yield list of (index-id, line) pairs for the specified version.
448
448
 
449
449
        The index indicates when the line originated in the weave."""
450
 
        incls = [self._lookup(version_id)]
 
450
        incls = [self.maybe_lookup(name_or_index)]
451
451
        for origin, lineno, text in self._extract(incls):
452
 
            yield self._idx_to_name(origin), text
453
 
 
454
 
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
455
 
                                                pb=None):
456
 
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
457
 
        if version_ids is None:
458
 
            version_ids = self.versions()
459
 
        version_ids = set(version_ids)
460
 
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
461
 
            # if inserted not in version_ids then it was inserted before the
462
 
            # versions we care about, but because weaves cannot represent ghosts
463
 
            # properly, we do not filter down to that
464
 
            # if inserted not in version_ids: continue
465
 
            if line[-1] != '\n':
466
 
                yield line + '\n'
467
 
            else:
468
 
                yield line
469
 
 
470
 
    def _walk_internal(self, version_ids=None):
471
 
        """Helper method for weave actions."""
 
452
            yield origin, text
 
453
 
 
454
    def _walk(self):
 
455
        """Walk the weave.
 
456
 
 
457
        Yields sequence of
 
458
        (lineno, insert, deletes, text)
 
459
        for each literal line.
 
460
        """
472
461
        
473
462
        istack = []
474
463
        dset = set()
476
465
        lineno = 0         # line of weave, 0-based
477
466
 
478
467
        for l in self._weave:
479
 
            if l.__class__ == tuple:
 
468
            if isinstance(l, tuple):
480
469
                c, v = l
481
470
                isactive = None
482
471
                if c == '{':
483
 
                    istack.append(self._names[v])
 
472
                    istack.append(v)
484
473
                elif c == '}':
485
474
                    istack.pop()
486
475
                elif c == '[':
487
 
                    assert self._names[v] not in dset
488
 
                    dset.add(self._names[v])
 
476
                    assert v not in dset
 
477
                    dset.add(v)
489
478
                elif c == ']':
490
 
                    dset.remove(self._names[v])
 
479
                    dset.remove(v)
491
480
                else:
492
481
                    raise WeaveFormatError('unexpected instruction %r' % v)
493
482
            else:
494
 
                assert l.__class__ in (str, unicode)
 
483
                assert isinstance(l, basestring)
495
484
                assert istack
496
 
                yield lineno, istack[-1], frozenset(dset), l
 
485
                yield lineno, istack[-1], dset, l
497
486
            lineno += 1
498
487
 
499
488
        if istack:
503
492
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
504
493
                                   % dset)
505
494
 
506
 
    def plan_merge(self, ver_a, ver_b):
507
 
        """Return pseudo-annotation indicating how the two versions merge.
508
 
 
509
 
        This is computed between versions a and b and their common
510
 
        base.
511
 
 
512
 
        Weave lines present in none of them are skipped entirely.
513
 
        """
514
 
        inc_a = set(self.get_ancestry([ver_a]))
515
 
        inc_b = set(self.get_ancestry([ver_b]))
516
 
        inc_c = inc_a & inc_b
517
 
 
518
 
        for lineno, insert, deleteset, line in self._walk_internal([ver_a, ver_b]):
519
 
            if deleteset & inc_c:
520
 
                # killed in parent; can't be in either a or b
521
 
                # not relevant to our work
522
 
                yield 'killed-base', line
523
 
            elif insert in inc_c:
524
 
                # was inserted in base
525
 
                killed_a = bool(deleteset & inc_a)
526
 
                killed_b = bool(deleteset & inc_b)
527
 
                if killed_a and killed_b:
528
 
                    yield 'killed-both', line
529
 
                elif killed_a:
530
 
                    yield 'killed-a', line
531
 
                elif killed_b:
532
 
                    yield 'killed-b', line
533
 
                else:
534
 
                    yield 'unchanged', line
535
 
            elif insert in inc_a:
536
 
                if deleteset & inc_a:
537
 
                    yield 'ghost-a', line
538
 
                else:
539
 
                    # new in A; not in B
540
 
                    yield 'new-a', line
541
 
            elif insert in inc_b:
542
 
                if deleteset & inc_b:
543
 
                    yield 'ghost-b', line
544
 
                else:
545
 
                    yield 'new-b', line
546
 
            else:
547
 
                # not in either revision
548
 
                yield 'irrelevant', line
549
 
 
550
 
        yield 'unchanged', ''           # terminator
551
 
 
552
495
    def _extract(self, versions):
553
496
        """Yield annotation of lines in included set.
554
497
 
562
505
            if not isinstance(i, int):
563
506
                raise ValueError(i)
564
507
            
565
 
        included = self._inclusions(versions)
 
508
        included = self.inclusions(versions)
566
509
 
567
510
        istack = []
568
 
        iset = set()
569
511
        dset = set()
570
512
 
571
513
        lineno = 0         # line of weave, 0-based
576
518
 
577
519
        WFE = WeaveFormatError
578
520
 
579
 
        # wow. 
580
 
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
581
 
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
582
 
        # 1.6 seconds in 'isinstance'.
583
 
        # changing the first isinstance:
584
 
        #  449       0   2814.2660   1577.1760   bzrlib.weave:556(_extract)
585
 
        #  +140414   0    762.8050    762.8050   +<isinstance>
586
 
        # note that the inline time actually dropped (less function calls)
587
 
        # and total processing time was halved.
588
 
        # we're still spending ~1/4 of the method in isinstance though.
589
 
        # so lets hard code the acceptable string classes we expect:
590
 
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
591
 
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list' 
592
 
        #                                          objects>
593
 
        # yay, down to ~1/4 the initial extract time, and our inline time
594
 
        # has shrunk again, with isinstance no longer dominating.
595
 
        # tweaking the stack inclusion test to use a set gives:
596
 
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
597
 
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list' 
598
 
        #                                          objects>
599
 
        # - a 5% win, or possibly just noise. However with large istacks that
600
 
        # 'in' test could dominate, so I'm leaving this change in place -
601
 
        # when its fast enough to consider profiling big datasets we can review.
602
 
 
603
 
              
604
 
             
605
 
 
606
521
        for l in self._weave:
607
 
            if l.__class__ == tuple:
 
522
            if isinstance(l, tuple):
608
523
                c, v = l
609
524
                isactive = None
610
525
                if c == '{':
611
 
                    assert v not in iset
 
526
                    assert v not in istack
612
527
                    istack.append(v)
613
 
                    iset.add(v)
614
528
                elif c == '}':
615
 
                    iset.remove(istack.pop())
 
529
                    istack.pop()
616
530
                elif c == '[':
617
531
                    if v in included:
618
532
                        assert v not in dset
623
537
                        assert v in dset
624
538
                        dset.remove(v)
625
539
            else:
626
 
                assert l.__class__ in (str, unicode)
 
540
                assert isinstance(l, basestring)
627
541
                if isactive is None:
628
542
                    isactive = (not dset) and istack and (istack[-1] in included)
629
543
                if isactive:
637
551
                                   % dset)
638
552
        return result
639
553
 
640
 
    def _maybe_lookup(self, name_or_index):
641
 
        """Convert possible symbolic name to index, or pass through indexes.
 
554
 
 
555
    def get_iter(self, name_or_index):
 
556
        """Yield lines for the specified version."""
 
557
        incls = [self.maybe_lookup(name_or_index)]
 
558
        if len(incls) == 1:
 
559
            index = incls[0]
 
560
            cur_sha = sha.new()
 
561
        else:
 
562
            # We don't have sha1 sums for multiple entries
 
563
            cur_sha = None
 
564
        for origin, lineno, line in self._extract(incls):
 
565
            if cur_sha:
 
566
                cur_sha.update(line)
 
567
            yield line
 
568
        if cur_sha:
 
569
            expected_sha1 = self._sha1s[index]
 
570
            measured_sha1 = cur_sha.hexdigest() 
 
571
            if measured_sha1 != expected_sha1:
 
572
                raise errors.WeaveInvalidChecksum(
 
573
                        'file %s, revision %s, expected: %s, measured %s' 
 
574
                        % (self._weave_name, self._names[index],
 
575
                           expected_sha1, measured_sha1))
 
576
 
 
577
 
 
578
    def get_text(self, name_or_index):
 
579
        return ''.join(self.get_iter(name_or_index))
 
580
        assert isinstance(version, int)
 
581
 
 
582
 
 
583
    def get_lines(self, name_or_index):
 
584
        return list(self.get_iter(name_or_index))
 
585
 
 
586
 
 
587
    get = get_lines
 
588
 
 
589
 
 
590
    def get_sha1(self, name):
 
591
        """Get the stored sha1 sum for the given revision.
642
592
        
643
 
        NOT FOR PUBLIC USE.
 
593
        :param name: The name of the version to lookup
644
594
        """
645
 
        if isinstance(name_or_index, (int, long)):
646
 
            return name_or_index
647
 
        else:
648
 
            return self._lookup(name_or_index)
649
 
 
650
 
    def get_lines(self, version_id):
651
 
        """See VersionedFile.get_lines()."""
652
 
        int_index = self._maybe_lookup(version_id)
653
 
        result = [line for (origin, lineno, line) in self._extract([int_index])]
654
 
        expected_sha1 = self._sha1s[int_index]
655
 
        measured_sha1 = sha_strings(result)
656
 
        if measured_sha1 != expected_sha1:
657
 
            raise errors.WeaveInvalidChecksum(
658
 
                    'file %s, revision %s, expected: %s, measured %s' 
659
 
                    % (self._weave_name, version_id,
660
 
                       expected_sha1, measured_sha1))
661
 
        return result
662
 
 
663
 
    def get_sha1(self, version_id):
664
 
        """See VersionedFile.get_sha1()."""
665
 
        return self._sha1s[self._lookup(version_id)]
666
 
 
667
 
    def get_sha1s(self, version_ids):
668
 
        """See VersionedFile.get_sha1s()."""
669
 
        return [self._sha1s[self._lookup(v)] for v in version_ids]
670
 
 
671
 
    def num_versions(self):
672
 
        """How many versions are in this weave?"""
 
595
        return self._sha1s[self.lookup(name)]
 
596
 
 
597
    def mash_iter(self, included):
 
598
        """Return composed version of multiple included versions."""
 
599
        included = map(self.maybe_lookup, included)
 
600
        for origin, lineno, text in self._extract(included):
 
601
            yield text
 
602
 
 
603
 
 
604
    def dump(self, to_file):
 
605
        from pprint import pprint
 
606
        print >>to_file, "Weave._weave = ",
 
607
        pprint(self._weave, to_file)
 
608
        print >>to_file, "Weave._parents = ",
 
609
        pprint(self._parents, to_file)
 
610
 
 
611
 
 
612
 
 
613
    def numversions(self):
673
614
        l = len(self._parents)
674
615
        assert l == len(self._sha1s)
675
616
        return l
676
617
 
677
 
    __len__ = num_versions
 
618
 
 
619
    def __len__(self):
 
620
        return self.numversions()
678
621
 
679
622
    def check(self, progress_bar=None):
680
 
        # TODO evaluate performance hit of using string sets in this routine.
681
 
        # TODO: check no circular inclusions
682
 
        # TODO: create a nested progress bar
683
 
        for version in range(self.num_versions()):
 
623
        # check no circular inclusions
 
624
        for version in range(self.numversions()):
684
625
            inclusions = list(self._parents[version])
685
626
            if inclusions:
686
627
                inclusions.sort()
689
630
                                           % (inclusions[-1], version))
690
631
 
691
632
        # try extracting all versions; parallel extraction is used
692
 
        nv = self.num_versions()
693
 
        sha1s = {}
694
 
        texts = {}
695
 
        inclusions = {}
 
633
        nv = self.numversions()
 
634
        sha1s = [sha.new() for i in range(nv)]
 
635
        texts = [[] for i in range(nv)]
 
636
        inclusions = []
696
637
        for i in range(nv):
697
638
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
698
639
            # The problem is that set membership is much more expensive
699
 
            name = self._idx_to_name(i)
700
 
            sha1s[name] = sha.new()
701
 
            texts[name] = []
702
 
            new_inc = set([name])
 
640
            new_inc = set([i])
703
641
            for p in self._parents[i]:
704
 
                new_inc.update(inclusions[self._idx_to_name(p)])
 
642
                new_inc.update(inclusions[p])
705
643
 
706
 
            assert set(new_inc) == set(self.get_ancestry(name)), \
707
 
                'failed %s != %s' % (set(new_inc), set(self.get_ancestry(name)))
708
 
            inclusions[name] = new_inc
 
644
            #assert set(new_inc) == self.inclusions([i]), 'failed %s != %s' % (new_inc, self.inclusions([i]))
 
645
            inclusions.append(new_inc)
709
646
 
710
647
        nlines = len(self._weave)
711
648
 
715
652
            update_text = 'checking %s' % (short_name,)
716
653
            update_text = update_text[:25]
717
654
 
718
 
        for lineno, insert, deleteset, line in self._walk_internal():
 
655
        for lineno, insert, deleteset, line in self._walk():
719
656
            if progress_bar:
720
657
                progress_bar.update(update_text, lineno, nlines)
721
658
 
722
 
            for name, name_inclusions in inclusions.items():
 
659
            for j, j_inc in enumerate(inclusions):
723
660
                # The active inclusion must be an ancestor,
724
661
                # and no ancestors must have deleted this line,
725
662
                # because we don't support resurrection.
726
 
                if (insert in name_inclusions) and not (deleteset & name_inclusions):
727
 
                    sha1s[name].update(line)
 
663
                if (insert in j_inc) and not (deleteset & j_inc):
 
664
                    sha1s[j].update(line)
728
665
 
729
 
        for i in range(nv):
730
 
            version = self._idx_to_name(i)
 
666
        for version in range(nv):
731
667
            hd = sha1s[version].hexdigest()
732
 
            expected = self._sha1s[i]
 
668
            expected = self._sha1s[version]
733
669
            if hd != expected:
734
670
                raise errors.WeaveInvalidChecksum(
735
671
                        "mismatched sha1 for version %s: "
736
672
                        "got %s, expected %s"
737
 
                        % (version, hd, expected))
 
673
                        % (self._names[version], hd, expected))
738
674
 
739
675
        # TODO: check insertions are properly nested, that there are
740
676
        # no lines outside of insertion blocks, that deletions are
741
677
        # properly paired, etc.
742
678
 
743
 
    def _join(self, other, pb, msg, version_ids, ignore_missing):
744
 
        """Worker routine for join()."""
745
 
        if not other.versions():
 
679
    def _delta(self, included, lines):
 
680
        """Return changes from basis to new revision.
 
681
 
 
682
        The old text for comparison is the union of included revisions.
 
683
 
 
684
        This is used in inserting a new text.
 
685
 
 
686
        Delta is returned as a sequence of
 
687
        (weave1, weave2, newlines).
 
688
 
 
689
        This indicates that weave1:weave2 of the old weave should be
 
690
        replaced by the sequence of lines in newlines.  Note that
 
691
        these line numbers are positions in the total weave and don't
 
692
        correspond to the lines in any extracted version, or even the
 
693
        extracted union of included versions.
 
694
 
 
695
        If line1=line2, this is a pure insert; if newlines=[] this is a
 
696
        pure delete.  (Similar to difflib.)
 
697
        """
 
698
        raise NotImplementedError()
 
699
 
 
700
            
 
701
    def plan_merge(self, ver_a, ver_b):
 
702
        """Return pseudo-annotation indicating how the two versions merge.
 
703
 
 
704
        This is computed between versions a and b and their common
 
705
        base.
 
706
 
 
707
        Weave lines present in none of them are skipped entirely.
 
708
        """
 
709
        inc_a = self.inclusions([ver_a])
 
710
        inc_b = self.inclusions([ver_b])
 
711
        inc_c = inc_a & inc_b
 
712
 
 
713
        for lineno, insert, deleteset, line in self._walk():
 
714
            if deleteset & inc_c:
 
715
                # killed in parent; can't be in either a or b
 
716
                # not relevant to our work
 
717
                yield 'killed-base', line
 
718
            elif insert in inc_c:
 
719
                # was inserted in base
 
720
                killed_a = bool(deleteset & inc_a)
 
721
                killed_b = bool(deleteset & inc_b)
 
722
                if killed_a and killed_b:
 
723
                    yield 'killed-both', line
 
724
                elif killed_a:
 
725
                    yield 'killed-a', line
 
726
                elif killed_b:
 
727
                    yield 'killed-b', line
 
728
                else:
 
729
                    yield 'unchanged', line
 
730
            elif insert in inc_a:
 
731
                if deleteset & inc_a:
 
732
                    yield 'ghost-a', line
 
733
                else:
 
734
                    # new in A; not in B
 
735
                    yield 'new-a', line
 
736
            elif insert in inc_b:
 
737
                if deleteset & inc_b:
 
738
                    yield 'ghost-b', line
 
739
                else:
 
740
                    yield 'new-b', line
 
741
            else:
 
742
                # not in either revision
 
743
                yield 'irrelevant', line
 
744
 
 
745
        yield 'unchanged', ''           # terminator
 
746
 
 
747
 
 
748
 
 
749
    def weave_merge(self, plan):
 
750
        lines_a = []
 
751
        lines_b = []
 
752
        ch_a = ch_b = False
 
753
        # TODO: Return a structured form of the conflicts (e.g. 2-tuples for
 
754
        # conflicted regions), rather than just inserting the markers.
 
755
        # 
 
756
        # TODO: Show some version information (e.g. author, date) on 
 
757
        # conflicted regions.
 
758
        for state, line in plan:
 
759
            if state == 'unchanged' or state == 'killed-both':
 
760
                # resync and flush queued conflicts changes if any
 
761
                if not lines_a and not lines_b:
 
762
                    pass
 
763
                elif ch_a and not ch_b:
 
764
                    # one-sided change:                    
 
765
                    for l in lines_a: yield l
 
766
                elif ch_b and not ch_a:
 
767
                    for l in lines_b: yield l
 
768
                elif lines_a == lines_b:
 
769
                    for l in lines_a: yield l
 
770
                else:
 
771
                    yield '<<<<<<<\n'
 
772
                    for l in lines_a: yield l
 
773
                    yield '=======\n'
 
774
                    for l in lines_b: yield l
 
775
                    yield '>>>>>>>\n'
 
776
 
 
777
                del lines_a[:]
 
778
                del lines_b[:]
 
779
                ch_a = ch_b = False
 
780
                
 
781
            if state == 'unchanged':
 
782
                if line:
 
783
                    yield line
 
784
            elif state == 'killed-a':
 
785
                ch_a = True
 
786
                lines_b.append(line)
 
787
            elif state == 'killed-b':
 
788
                ch_b = True
 
789
                lines_a.append(line)
 
790
            elif state == 'new-a':
 
791
                ch_a = True
 
792
                lines_a.append(line)
 
793
            elif state == 'new-b':
 
794
                ch_b = True
 
795
                lines_b.append(line)
 
796
            else:
 
797
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 'killed-base',
 
798
                                 'killed-both'), \
 
799
                       state
 
800
 
 
801
 
 
802
    def join(self, other):
 
803
        import sys, time
 
804
        """Integrate versions from other into this weave.
 
805
 
 
806
        The resulting weave contains all the history of both weaves; 
 
807
        any version you could retrieve from either self or other can be 
 
808
        retrieved from self after this call.
 
809
 
 
810
        It is illegal for the two weaves to contain different values 
 
811
        or different parents for any version.  See also reweave().
 
812
        """
 
813
        if other.numversions() == 0:
746
814
            return          # nothing to update, easy
747
 
 
748
 
        if not version_ids:
749
 
            # versions is never none, InterWeave checks this.
750
 
            return 0
751
 
 
752
815
        # two loops so that we do not change ourselves before verifying it
753
816
        # will be ok
754
817
        # work through in index order to make sure we get all dependencies
755
 
        names_to_join = []
 
818
        for other_idx, name in enumerate(other._names):
 
819
            self._check_version_consistent(other, other_idx, name)
 
820
 
 
821
        merged = 0
756
822
        processed = 0
757
 
        # get the selected versions only that are in other.versions.
758
 
        version_ids = set(other.versions()).intersection(set(version_ids))
759
 
        # pull in the referenced graph.
760
 
        version_ids = other.get_ancestry(version_ids)
761
 
        pending_graph = [(version, other.get_parents(version)) for
762
 
                         version in version_ids]
763
 
        for name in topo_sort(pending_graph):
764
 
            other_idx = other._name_map[name]
765
 
            # returns True if we have it, False if we need it.
766
 
            if not self._check_version_consistent(other, other_idx, name):
767
 
                names_to_join.append((other_idx, name))
768
 
            processed += 1
769
 
 
770
 
 
771
 
        if pb and not msg:
772
 
            msg = 'weave join'
773
 
 
774
 
        merged = 0
775
 
        time0 = time.time()
776
 
        for other_idx, name in names_to_join:
 
823
        time0 = time.time( )
 
824
        for other_idx, name in enumerate(other._names):
777
825
            # TODO: If all the parents of the other version are already
778
826
            # present then we can avoid some work by just taking the delta
779
827
            # and adjusting the offsets.
780
828
            new_parents = self._imported_parents(other, other_idx)
781
829
            sha1 = other._sha1s[other_idx]
782
830
 
 
831
            processed += 1
 
832
           
 
833
            if name in self._names:
 
834
                idx = self.lookup(name)
 
835
                n1 = map(other.idx_to_name, other._parents[other_idx] )
 
836
                n2 = map(self.idx_to_name, self._parents[other_idx] )
 
837
                if sha1 ==  self._sha1s[idx] and n1 == n2:
 
838
                        continue
 
839
 
783
840
            merged += 1
784
 
 
785
 
            if pb:
786
 
                pb.update(msg, merged, len(names_to_join))
787
 
           
788
841
            lines = other.get_lines(other_idx)
789
 
            self._add(name, lines, new_parents, sha1)
 
842
            self.add(name, new_parents, lines, sha1)
790
843
 
791
844
        mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
792
 
                merged, processed, self._weave_name, time.time()-time0))
 
845
                merged,processed,self._weave_name, time.time( )-time0))
 
846
 
 
847
 
 
848
 
793
849
 
794
850
    def _imported_parents(self, other, other_idx):
795
851
        """Return list of parents in self corresponding to indexes in other."""
796
852
        new_parents = []
797
853
        for parent_idx in other._parents[other_idx]:
798
854
            parent_name = other._names[parent_idx]
799
 
            if parent_name not in self._name_map:
 
855
            if parent_name not in self._names:
800
856
                # should not be possible
801
857
                raise WeaveError("missing parent {%s} of {%s} in %r" 
802
858
                                 % (parent_name, other._name_map[other_idx], self))
818
874
        this_idx = self._name_map.get(name, -1)
819
875
        if this_idx != -1:
820
876
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
821
 
                raise errors.WeaveTextDiffers(name, self, other)
 
877
                raise WeaveError("inconsistent texts for version {%s} "
 
878
                                 "when joining weaves"
 
879
                                 % (name))
822
880
            self_parents = self._parents[this_idx]
823
881
            other_parents = other._parents[other_idx]
824
 
            n1 = set([self._names[i] for i in self_parents])
825
 
            n2 = set([other._names[i] for i in other_parents])
826
 
            if not self._compatible_parents(n1, n2):
 
882
            n1 = [self._names[i] for i in self_parents]
 
883
            n2 = [other._names[i] for i in other_parents]
 
884
            n1.sort()
 
885
            n2.sort()
 
886
            if n1 != n2:
827
887
                raise WeaveParentMismatch("inconsistent parents "
828
888
                    "for version {%s}: %s vs %s" % (name, n1, n2))
829
889
            else:
831
891
        else:
832
892
            return False
833
893
 
834
 
    def _reweave(self, other, pb, msg):
835
 
        """Reweave self with other - internal helper for join().
836
 
 
837
 
        :param other: The other weave to merge
838
 
        :param pb: An optional progress bar, indicating how far done we are
839
 
        :param msg: An optional message for the progress
840
 
        """
841
 
        new_weave = _reweave(self, other, pb=pb, msg=msg)
842
 
        self._copy_weave_content(new_weave)
843
 
 
844
 
    def _copy_weave_content(self, otherweave):
845
 
        """adsorb the content from otherweave."""
 
894
    def reweave(self, other):
 
895
        """Reweave self with other."""
 
896
        new_weave = reweave(self, other)
846
897
        for attr in self.__slots__:
847
 
            if attr != '_weave_name':
848
 
                setattr(self, attr, copy(getattr(otherweave, attr)))
849
 
 
850
 
 
851
 
class WeaveFile(Weave):
852
 
    """A WeaveFile represents a Weave on disk and writes on change."""
853
 
 
854
 
    WEAVE_SUFFIX = '.weave'
855
 
    
856
 
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w'):
857
 
        """Create a WeaveFile.
858
 
        
859
 
        :param create: If not True, only open an existing knit.
860
 
        """
861
 
        super(WeaveFile, self).__init__(name, access_mode)
862
 
        self._transport = transport
863
 
        self._filemode = filemode
864
 
        try:
865
 
            _read_weave_v5(self._transport.get(name + WeaveFile.WEAVE_SUFFIX), self)
866
 
        except errors.NoSuchFile:
867
 
            if not create:
868
 
                raise
869
 
            # new file, save it
870
 
            self._save()
871
 
 
872
 
    def _add_lines(self, version_id, parents, lines, parent_texts,
873
 
        left_matching_blocks, nostore_sha, random_id, check_content):
874
 
        """Add a version and save the weave."""
875
 
        self.check_not_reserved_id(version_id)
876
 
        result = super(WeaveFile, self)._add_lines(version_id, parents, lines,
877
 
            parent_texts, left_matching_blocks, nostore_sha, random_id,
878
 
            check_content)
879
 
        self._save()
880
 
        return result
881
 
 
882
 
    def _clone_text(self, new_version_id, old_version_id, parents):
883
 
        """See VersionedFile.clone_text."""
884
 
        super(WeaveFile, self)._clone_text(new_version_id, old_version_id, parents)
885
 
        self._save
886
 
 
887
 
    def copy_to(self, name, transport):
888
 
        """See VersionedFile.copy_to()."""
889
 
        # as we are all in memory always, just serialise to the new place.
890
 
        sio = StringIO()
891
 
        write_weave_v5(self, sio)
892
 
        sio.seek(0)
893
 
        transport.put_file(name + WeaveFile.WEAVE_SUFFIX, sio, self._filemode)
894
 
 
895
 
    def create_empty(self, name, transport, filemode=None):
896
 
        return WeaveFile(name, transport, filemode, create=True)
897
 
 
898
 
    def _save(self):
899
 
        """Save the weave."""
900
 
        self._check_write_ok()
901
 
        sio = StringIO()
902
 
        write_weave_v5(self, sio)
903
 
        sio.seek(0)
904
 
        self._transport.put_file(self._weave_name + WeaveFile.WEAVE_SUFFIX,
905
 
                                 sio,
906
 
                                 self._filemode)
907
 
 
908
 
    @staticmethod
909
 
    def get_suffixes():
910
 
        """See VersionedFile.get_suffixes()."""
911
 
        return [WeaveFile.WEAVE_SUFFIX]
912
 
 
913
 
    def join(self, other, pb=None, msg=None, version_ids=None,
914
 
             ignore_missing=False):
915
 
        """Join other into self and save."""
916
 
        super(WeaveFile, self).join(other, pb, msg, version_ids, ignore_missing)
917
 
        self._save()
918
 
 
919
 
 
920
 
def _reweave(wa, wb, pb=None, msg=None):
 
898
            setattr(self, attr, getattr(new_weave, attr))
 
899
 
 
900
 
 
901
def reweave(wa, wb):
921
902
    """Combine two weaves and return the result.
922
903
 
923
904
    This works even if a revision R has different parents in 
928
909
    might be possible but it should only be necessary to do 
929
910
    this operation rarely, when a new previously ghost version is 
930
911
    inserted.
931
 
 
932
 
    :param pb: An optional progress bar, indicating how far done we are
933
 
    :param msg: An optional message for the progress
934
912
    """
935
913
    wr = Weave()
936
914
    ia = ib = 0
937
 
    queue_a = range(wa.num_versions())
938
 
    queue_b = range(wb.num_versions())
 
915
    queue_a = range(wa.numversions())
 
916
    queue_b = range(wb.numversions())
939
917
    # first determine combined parents of all versions
940
918
    # map from version name -> all parent names
941
919
    combined_parents = _reweave_parent_graphs(wa, wb)
942
920
    mutter("combined parents: %r", combined_parents)
943
921
    order = topo_sort(combined_parents.iteritems())
944
922
    mutter("order to reweave: %r", order)
945
 
 
946
 
    if pb and not msg:
947
 
        msg = 'reweave'
948
 
 
949
 
    for idx, name in enumerate(order):
950
 
        if pb:
951
 
            pb.update(msg, idx, len(order))
 
923
    for name in order:
952
924
        if name in wa._name_map:
953
925
            lines = wa.get_lines(name)
954
926
            if name in wb._name_map:
955
 
                lines_b = wb.get_lines(name)
956
 
                if lines != lines_b:
957
 
                    mutter('Weaves differ on content. rev_id {%s}', name)
958
 
                    mutter('weaves: %s, %s', wa._weave_name, wb._weave_name)
959
 
                    import difflib
960
 
                    lines = list(difflib.unified_diff(lines, lines_b,
961
 
                            wa._weave_name, wb._weave_name))
962
 
                    mutter('lines:\n%s', ''.join(lines))
963
 
                    raise errors.WeaveTextDiffers(name, wa, wb)
 
927
                assert lines == wb.get_lines(name)
964
928
        else:
965
929
            lines = wb.get_lines(name)
966
 
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
 
930
        wr.add(name, combined_parents[name], lines)
967
931
    return wr
968
932
 
 
933
 
969
934
def _reweave_parent_graphs(wa, wb):
970
935
    """Return combined parent ancestry for two weaves.
971
936
    
974
939
    for weave in [wa, wb]:
975
940
        for idx, name in enumerate(weave._names):
976
941
            p = combined.setdefault(name, set())
977
 
            p.update(map(weave._idx_to_name, weave._parents[idx]))
 
942
            p.update(map(weave.idx_to_name, weave._parents[idx]))
978
943
    return combined
979
944
 
980
945
 
984
949
    for i in (6, 50, 10, 10):
985
950
        print '-' * i,
986
951
    print
987
 
    for i in range(w.num_versions()):
 
952
    for i in range(w.numversions()):
988
953
        sha1 = w._sha1s[i]
989
954
        name = w._names[i]
990
955
        parent_str = ' '.join(map(str, w._parents[i]))
1037
1002
        Add NEWTEXT, with specified parent versions.
1038
1003
    weave annotate WEAVEFILE VERSION
1039
1004
        Display origin of each line.
 
1005
    weave mash WEAVEFILE VERSION...
 
1006
        Display composite of all selected versions.
1040
1007
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
1041
1008
        Auto-merge two versions and display conflicts.
1042
1009
    weave diff WEAVEFILE VERSION1 VERSION2 
1116
1083
        w = readit()
1117
1084
        sys.stdout.writelines(w.get_iter(int(argv[3])))
1118
1085
        
 
1086
    elif cmd == 'mash': # get composite
 
1087
        w = readit()
 
1088
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
 
1089
 
1119
1090
    elif cmd == 'diff':
 
1091
        from difflib import unified_diff
1120
1092
        w = readit()
1121
1093
        fn = argv[2]
1122
1094
        v1, v2 = map(int, argv[3:5])
1123
1095
        lines1 = w.get(v1)
1124
1096
        lines2 = w.get(v2)
1125
 
        diff_gen = bzrlib.patiencediff.unified_diff(lines1, lines2,
 
1097
        diff_gen = unified_diff(lines1, lines2,
1126
1098
                                '%s version %d' % (fn, v1),
1127
1099
                                '%s version %d' % (fn, v2))
1128
1100
        sys.stdout.writelines(diff_gen)
1151
1123
        pb = ProgressBar()
1152
1124
        w.check(pb)
1153
1125
        pb.clear()
1154
 
        print '%d versions ok' % w.num_versions()
 
1126
        print '%d versions ok' % w.numversions()
1155
1127
 
1156
1128
    elif cmd == 'inclusions':
1157
1129
        w = readit()
1162
1134
        print ' '.join(map(str, w._parents[int(argv[3])]))
1163
1135
 
1164
1136
    elif cmd == 'plan-merge':
1165
 
        # replaced by 'bzr weave-plan-merge'
1166
1137
        w = readit()
1167
1138
        for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
1168
1139
            if line:
1169
1140
                print '%14s | %s' % (state, line),
 
1141
 
1170
1142
    elif cmd == 'merge':
1171
 
        # replaced by 'bzr weave-merge-text'
1172
1143
        w = readit()
1173
1144
        p = w.plan_merge(int(argv[3]), int(argv[4]))
1174
1145
        sys.stdout.writelines(w.weave_merge(p))
 
1146
            
 
1147
    elif cmd == 'mash-merge':
 
1148
        if len(argv) != 5:
 
1149
            usage()
 
1150
            return 1
 
1151
 
 
1152
        w = readit()
 
1153
        v1, v2 = map(int, argv[3:5])
 
1154
 
 
1155
        basis = w.inclusions([v1]).intersection(w.inclusions([v2]))
 
1156
 
 
1157
        base_lines = list(w.mash_iter(basis))
 
1158
        a_lines = list(w.get(v1))
 
1159
        b_lines = list(w.get(v2))
 
1160
 
 
1161
        from bzrlib.merge3 import Merge3
 
1162
        m3 = Merge3(base_lines, a_lines, b_lines)
 
1163
 
 
1164
        name_a = 'version %d' % v1
 
1165
        name_b = 'version %d' % v2
 
1166
        sys.stdout.writelines(m3.merge_lines(name_a=name_a, name_b=name_b))
1175
1167
    else:
1176
1168
        raise ValueError('unknown command %r' % cmd)
1177
1169
    
1178
1170
 
 
1171
 
 
1172
def profile_main(argv): 
 
1173
    import tempfile, hotshot, hotshot.stats
 
1174
 
 
1175
    prof_f = tempfile.NamedTemporaryFile()
 
1176
 
 
1177
    prof = hotshot.Profile(prof_f.name)
 
1178
 
 
1179
    ret = prof.runcall(main, argv)
 
1180
    prof.close()
 
1181
 
 
1182
    stats = hotshot.stats.load(prof_f.name)
 
1183
    #stats.strip_dirs()
 
1184
    stats.sort_stats('cumulative')
 
1185
    ## XXX: Might like to write to stderr or the trace file instead but
 
1186
    ## print_stats seems hardcoded to stdout
 
1187
    stats.print_stats(20)
 
1188
            
 
1189
    return ret
 
1190
 
 
1191
 
 
1192
def lsprofile_main(argv): 
 
1193
    from bzrlib.lsprof import profile
 
1194
    ret,stats = profile(main, argv)
 
1195
    stats.sort()
 
1196
    stats.pprint()
 
1197
    return ret
 
1198
 
 
1199
 
1179
1200
if __name__ == '__main__':
1180
1201
    import sys
1181
 
    sys.exit(main(sys.argv))
1182
 
 
1183
 
 
1184
 
class InterWeave(InterVersionedFile):
1185
 
    """Optimised code paths for weave to weave operations."""
1186
 
    
1187
 
    _matching_file_from_factory = staticmethod(WeaveFile)
1188
 
    _matching_file_to_factory = staticmethod(WeaveFile)
1189
 
    
1190
 
    @staticmethod
1191
 
    def is_compatible(source, target):
1192
 
        """Be compatible with weaves."""
1193
 
        try:
1194
 
            return (isinstance(source, Weave) and
1195
 
                    isinstance(target, Weave))
1196
 
        except AttributeError:
1197
 
            return False
1198
 
 
1199
 
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1200
 
        """See InterVersionedFile.join."""
1201
 
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1202
 
        if self.target.versions() == [] and version_ids is None:
1203
 
            self.target._copy_weave_content(self.source)
1204
 
            return
1205
 
        self.target._join(self.source, pb, msg, version_ids, ignore_missing)
1206
 
 
1207
 
 
1208
 
InterVersionedFile.register_optimiser(InterWeave)
 
1202
    if '--profile' in sys.argv:
 
1203
        args = sys.argv[:]
 
1204
        args.remove('--profile')
 
1205
        sys.exit(profile_main(args))
 
1206
    elif '--lsprof' in sys.argv:
 
1207
        args = sys.argv[:]
 
1208
        args.remove('--lsprof')
 
1209
        sys.exit(lsprofile_main(args))
 
1210
    else:
 
1211
        sys.exit(main(sys.argv))
 
1212