3
# Copyright (C) 2005 Canonical Ltd
 
 
5
# This program is free software; you can redistribute it and/or modify
 
 
6
# it under the terms of the GNU General Public License as published by
 
 
7
# the Free Software Foundation; either version 2 of the License, or
 
 
8
# (at your option) any later version.
 
 
10
# This program is distributed in the hope that it will be useful,
 
 
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
13
# GNU General Public License for more details.
 
 
15
# You should have received a copy of the GNU General Public License
 
 
16
# along with this program; if not, write to the Free Software
 
 
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
19
# Author: Martin Pool <mbp@canonical.com>
 
 
22
"""Weave - storage of related text file versions"""
 
 
25
# XXX: If we do weaves this way, will a merge still behave the same
 
 
26
# way if it's done in a different order?  That's a pretty desirable
 
 
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
 
 
31
# binaries, perhaps by naively splitting on \n or perhaps using
 
 
32
# something like a rolling checksum.
 
 
34
# TODO: End marker for each version so we can stop reading?
 
 
36
# TODO: Check that no insertion occurs inside a deletion that was
 
 
37
# active in the version of the insertion.
 
 
39
# TODO: In addition to the SHA-1 check, perhaps have some code that
 
 
40
# checks structural constraints of the weave: ie that insertions are
 
 
41
# properly nested, that there is no text outside of an insertion, that
 
 
42
# insertions or deletions are not repeated, etc.
 
 
44
# TODO: Parallel-extract that passes back each line along with a
 
 
45
# description of which revisions include it.  Nice for checking all
 
 
46
# shas or calculating stats in parallel.
 
 
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.
 
 
53
# TODO: Probably the API should work only in names to hide the integer
 
 
54
# indexes from the user.
 
 
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
 
 
60
# TODO: Reweave can possibly be made faster by remembering diffs
 
 
61
# where the basis and destination are unchanged.
 
 
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.
 
 
69
# FIXME: the conflict markers should be *7* characters
 
 
72
from cStringIO import StringIO
 
 
81
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
 
 
82
        RevisionAlreadyPresent,
 
 
84
        UnavailableRepresentation,
 
 
85
        WeaveRevisionAlreadyPresent,
 
 
86
        WeaveRevisionNotPresent,
 
 
88
import bzrlib.errors as errors
 
 
89
from bzrlib.osutils import dirname, sha_strings, split_lines
 
 
90
import bzrlib.patiencediff
 
 
91
from bzrlib.revision import NULL_REVISION
 
 
92
from bzrlib.symbol_versioning import *
 
 
93
from bzrlib.trace import mutter
 
 
94
from bzrlib.tsort import topo_sort
 
 
95
from bzrlib.versionedfile import (
 
 
101
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
 
 
104
class WeaveContentFactory(ContentFactory):
 
 
105
    """Content factory for streaming from weaves.
 
 
107
    :seealso ContentFactory:
 
 
110
    def __init__(self, version, weave):
 
 
111
        """Create a WeaveContentFactory for version from weave."""
 
 
112
        ContentFactory.__init__(self)
 
 
113
        self.sha1 = weave.get_sha1s([version])[0]
 
 
114
        self.key = (version,)
 
 
115
        parents = weave.get_parent_map([version])[version]
 
 
116
        self.parents = tuple((parent,) for parent in parents)
 
 
117
        self.storage_kind = 'fulltext'
 
 
120
    def get_bytes_as(self, storage_kind):
 
 
121
        if storage_kind == 'fulltext':
 
 
122
            return self._weave.get_text(self.key[-1])
 
 
124
            raise UnavailableRepresentation(self.key, storage_kind, 'fulltext')
 
 
127
class Weave(VersionedFile):
 
 
128
    """weave - versioned text file storage.
 
 
130
    A Weave manages versions of line-based text files, keeping track
 
 
131
    of the originating version for each line.
 
 
133
    To clients the "lines" of the file are represented as a list of strings.
 
 
134
    These strings  will typically have terminal newline characters, but
 
 
135
    this is not required.  In particular files commonly do not have a newline
 
 
136
    at the end of the file.
 
 
138
    Texts can be identified in either of two ways:
 
 
140
    * a nonnegative index number.
 
 
142
    * a version-id string.
 
 
144
    Typically the index number will be valid only inside this weave and
 
 
145
    the version-id is used to reference it in the larger world.
 
 
147
    The weave is represented as a list mixing edit instructions and
 
 
148
    literal text.  Each entry in _weave can be either a string (or
 
 
149
    unicode), or a tuple.  If a string, it means that the given line
 
 
150
    should be output in the currently active revisions.
 
 
152
    If a tuple, it gives a processing instruction saying in which
 
 
153
    revisions the enclosed lines are active.  The tuple has the form
 
 
154
    (instruction, version).
 
 
156
    The instruction can be '{' or '}' for an insertion block, and '['
 
 
157
    and ']' for a deletion block respectively.  The version is the
 
 
158
    integer version index.  There is no replace operator, only deletes
 
 
159
    and inserts.  For '}', the end of an insertion, there is no
 
 
160
    version parameter because it always closes the most recently
 
 
165
    * A later version can delete lines that were introduced by any
 
 
166
      number of ancestor versions; this implies that deletion
 
 
167
      instructions can span insertion blocks without regard to the
 
 
168
      insertion block's nesting.
 
 
170
    * Similarly, deletions need not be properly nested with regard to
 
 
171
      each other, because they might have been generated by
 
 
172
      independent revisions.
 
 
174
    * Insertions are always made by inserting a new bracketed block
 
 
175
      into a single point in the previous weave.  This implies they
 
 
176
      can nest but not overlap, and the nesting must always have later
 
 
177
      insertions on the inside.
 
 
179
    * It doesn't seem very useful to have an active insertion
 
 
180
      inside an inactive insertion, but it might happen.
 
 
182
    * Therefore, all instructions are always"considered"; that
 
 
183
      is passed onto and off the stack.  An outer inactive block
 
 
184
      doesn't disable an inner block.
 
 
186
    * Lines are enabled if the most recent enclosing insertion is
 
 
187
      active and none of the enclosing deletions are active.
 
 
189
    * There is no point having a deletion directly inside its own
 
 
190
      insertion; you might as well just not write it.  And there
 
 
191
      should be no way to get an earlier version deleting a later
 
 
195
        Text of the weave; list of control instruction tuples and strings.
 
 
198
        List of parents, indexed by version number.
 
 
199
        It is only necessary to store the minimal set of parents for
 
 
200
        each version; the parent's parents are implied.
 
 
203
        List of hex SHA-1 of each version.
 
 
206
        List of symbolic names for each version.  Each should be unique.
 
 
209
        For each name, the version number.
 
 
212
        Descriptive name of this weave; typically the filename if known.
 
 
216
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
 
 
217
                 '_weave_name', '_matcher', '_allow_reserved']
 
 
219
    def __init__(self, weave_name=None, access_mode='w', matcher=None,
 
 
220
                 get_scope=None, allow_reserved=False):
 
 
223
        :param get_scope: A callable that returns an opaque object to be used
 
 
224
            for detecting when this weave goes out of scope (should stop
 
 
225
            answering requests or allowing mutation).
 
 
227
        super(Weave, self).__init__(access_mode)
 
 
233
        self._weave_name = weave_name
 
 
235
            self._matcher = bzrlib.patiencediff.PatienceSequenceMatcher
 
 
237
            self._matcher = matcher
 
 
238
        if get_scope is None:
 
 
239
            get_scope = lambda:None
 
 
240
        self._get_scope = get_scope
 
 
241
        self._scope = get_scope()
 
 
242
        self._access_mode = access_mode
 
 
243
        self._allow_reserved = allow_reserved
 
 
246
        return "Weave(%r)" % self._weave_name
 
 
248
    def _check_write_ok(self):
 
 
249
        """Is the versioned file marked as 'finished' ? Raise if it is."""
 
 
250
        if self._get_scope() != self._scope:
 
 
251
            raise errors.OutSideTransaction()
 
 
252
        if self._access_mode != 'w':
 
 
253
            raise errors.ReadOnlyObjectDirtiedError(self)
 
 
256
        """Return a deep copy of self.
 
 
258
        The copy can be modified without affecting the original weave."""
 
 
260
        other._weave = self._weave[:]
 
 
261
        other._parents = self._parents[:]
 
 
262
        other._sha1s = self._sha1s[:]
 
 
263
        other._names = self._names[:]
 
 
264
        other._name_map = self._name_map.copy()
 
 
265
        other._weave_name = self._weave_name
 
 
268
    def __eq__(self, other):
 
 
269
        if not isinstance(other, Weave):
 
 
271
        return self._parents == other._parents \
 
 
272
               and self._weave == other._weave \
 
 
273
               and self._sha1s == other._sha1s 
 
 
275
    def __ne__(self, other):
 
 
276
        return not self.__eq__(other)
 
 
278
    def _idx_to_name(self, version):
 
 
279
        return self._names[version]
 
 
281
    def _lookup(self, name):
 
 
282
        """Convert symbolic version name to index."""
 
 
283
        if not self._allow_reserved:
 
 
284
            self.check_not_reserved_id(name)
 
 
286
            return self._name_map[name]
 
 
288
            raise RevisionNotPresent(name, self._weave_name)
 
 
291
        """See VersionedFile.versions."""
 
 
292
        return self._names[:]
 
 
294
    def has_version(self, version_id):
 
 
295
        """See VersionedFile.has_version."""
 
 
296
        return (version_id in self._name_map)
 
 
298
    __contains__ = has_version
 
 
300
    def get_record_stream(self, versions, ordering, include_delta_closure):
 
 
301
        """Get a stream of records for versions.
 
 
303
        :param versions: The versions to include. Each version is a tuple
 
 
305
        :param ordering: Either 'unordered' or 'topological'. A topologically
 
 
306
            sorted stream has compression parents strictly before their
 
 
308
        :param include_delta_closure: If True then the closure across any
 
 
309
            compression parents will be included (in the opaque data).
 
 
310
        :return: An iterator of ContentFactory objects, each of which is only
 
 
311
            valid until the iterator is advanced.
 
 
313
        versions = [version[-1] for version in versions]
 
 
314
        if ordering == 'topological':
 
 
315
            parents = self.get_parent_map(versions)
 
 
316
            new_versions = topo_sort(parents)
 
 
317
            new_versions.extend(set(versions).difference(set(parents)))
 
 
318
            versions = new_versions
 
 
319
        for version in versions:
 
 
321
                yield WeaveContentFactory(version, self)
 
 
323
                yield AbsentContentFactory((version,))
 
 
325
    def get_parent_map(self, version_ids):
 
 
326
        """See VersionedFile.get_parent_map."""
 
 
328
        for version_id in version_ids:
 
 
329
            if version_id == NULL_REVISION:
 
 
334
                        map(self._idx_to_name,
 
 
335
                            self._parents[self._lookup(version_id)]))
 
 
336
                except RevisionNotPresent:
 
 
338
            result[version_id] = parents
 
 
341
    def get_parents_with_ghosts(self, version_id):
 
 
342
        raise NotImplementedError(self.get_parents_with_ghosts)
 
 
344
    def insert_record_stream(self, stream):
 
 
345
        """Insert a record stream into this versioned file.
 
 
347
        :param stream: A stream of records to insert. 
 
 
349
        :seealso VersionedFile.get_record_stream:
 
 
352
        for record in stream:
 
 
353
            # Raise an error when a record is missing.
 
 
354
            if record.storage_kind == 'absent':
 
 
355
                raise RevisionNotPresent([record.key[0]], self)
 
 
356
            # adapt to non-tuple interface
 
 
357
            parents = [parent[0] for parent in record.parents]
 
 
358
            if record.storage_kind == 'fulltext':
 
 
359
                self.add_lines(record.key[0], parents,
 
 
360
                    split_lines(record.get_bytes_as('fulltext')))
 
 
362
                adapter_key = record.storage_kind, 'fulltext'
 
 
364
                    adapter = adapters[adapter_key]
 
 
366
                    adapter_factory = adapter_registry.get(adapter_key)
 
 
367
                    adapter = adapter_factory(self)
 
 
368
                    adapters[adapter_key] = adapter
 
 
369
                lines = split_lines(adapter.get_bytes(
 
 
370
                    record, record.get_bytes_as(record.storage_kind)))
 
 
372
                    self.add_lines(record.key[0], parents, lines)
 
 
373
                except RevisionAlreadyPresent:
 
 
376
    def _check_repeated_add(self, name, parents, text, sha1):
 
 
377
        """Check that a duplicated add is OK.
 
 
379
        If it is, return the (old) index; otherwise raise an exception.
 
 
381
        idx = self._lookup(name)
 
 
382
        if sorted(self._parents[idx]) != sorted(parents) \
 
 
383
            or sha1 != self._sha1s[idx]:
 
 
384
            raise RevisionAlreadyPresent(name, self._weave_name)
 
 
387
    def _add_lines(self, version_id, parents, lines, parent_texts,
 
 
388
       left_matching_blocks, nostore_sha, random_id, check_content):
 
 
389
        """See VersionedFile.add_lines."""
 
 
390
        idx = self._add(version_id, lines, map(self._lookup, parents),
 
 
391
            nostore_sha=nostore_sha)
 
 
392
        return sha_strings(lines), sum(map(len, lines)), idx
 
 
394
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
 
 
395
        """Add a single text on top of the weave.
 
 
397
        Returns the index number of the newly added version.
 
 
400
            Symbolic name for this version.
 
 
401
            (Typically the revision-id of the revision that added it.)
 
 
404
            List or set of direct parent version numbers.
 
 
407
            Sequence of lines to be added in the new version.
 
 
409
        :param nostore_sha: See VersionedFile.add_lines.
 
 
411
        self._check_lines_not_unicode(lines)
 
 
412
        self._check_lines_are_lines(lines)
 
 
414
            sha1 = sha_strings(lines)
 
 
415
        if sha1 == nostore_sha:
 
 
416
            raise errors.ExistingContent
 
 
417
        if version_id in self._name_map:
 
 
418
            return self._check_repeated_add(version_id, parents, lines, sha1)
 
 
420
        self._check_versions(parents)
 
 
421
        ## self._check_lines(lines)
 
 
422
        new_version = len(self._parents)
 
 
424
        # if we abort after here the (in-memory) weave will be corrupt because only
 
 
425
        # some fields are updated
 
 
426
        # XXX: FIXME implement a succeed-or-fail of the rest of this routine.
 
 
427
        #      - Robert Collins 20060226
 
 
428
        self._parents.append(parents[:])
 
 
429
        self._sha1s.append(sha1)
 
 
430
        self._names.append(version_id)
 
 
431
        self._name_map[version_id] = new_version
 
 
435
            # special case; adding with no parents revision; can do
 
 
436
            # this more quickly by just appending unconditionally.
 
 
437
            # even more specially, if we're adding an empty text we
 
 
438
            # need do nothing at all.
 
 
440
                self._weave.append(('{', new_version))
 
 
441
                self._weave.extend(lines)
 
 
442
                self._weave.append(('}', None))
 
 
445
        if len(parents) == 1:
 
 
446
            pv = list(parents)[0]
 
 
447
            if sha1 == self._sha1s[pv]:
 
 
448
                # special case: same as the single parent
 
 
452
        ancestors = self._inclusions(parents)
 
 
456
        # basis a list of (origin, lineno, line)
 
 
459
        for origin, lineno, line in self._extract(ancestors):
 
 
460
            basis_lineno.append(lineno)
 
 
461
            basis_lines.append(line)
 
 
463
        # another small special case: a merge, producing the same text
 
 
465
        if lines == basis_lines:
 
 
468
        # add a sentinel, because we can also match against the final line
 
 
469
        basis_lineno.append(len(self._weave))
 
 
471
        # XXX: which line of the weave should we really consider
 
 
472
        # matches the end of the file?  the current code says it's the
 
 
473
        # last line of the weave?
 
 
475
        #print 'basis_lines:', basis_lines
 
 
476
        #print 'new_lines:  ', lines
 
 
478
        s = self._matcher(None, basis_lines, lines)
 
 
480
        # offset gives the number of lines that have been inserted
 
 
481
        # into the weave up to the current point; if the original edit instruction
 
 
482
        # says to change line A then we actually change (A+offset)
 
 
485
        for tag, i1, i2, j1, j2 in s.get_opcodes():
 
 
486
            # i1,i2 are given in offsets within basis_lines; we need to map them
 
 
487
            # back to offsets within the entire weave
 
 
488
            #print 'raw match', tag, i1, i2, j1, j2
 
 
491
            i1 = basis_lineno[i1]
 
 
492
            i2 = basis_lineno[i2]
 
 
493
            # the deletion and insertion are handled separately.
 
 
494
            # first delete the region.
 
 
496
                self._weave.insert(i1+offset, ('[', new_version))
 
 
497
                self._weave.insert(i2+offset+1, (']', new_version))
 
 
501
                # there may have been a deletion spanning up to
 
 
502
                # i2; we want to insert after this region to make sure
 
 
503
                # we don't destroy ourselves
 
 
505
                self._weave[i:i] = ([('{', new_version)] 
 
 
508
                offset += 2 + (j2 - j1)
 
 
511
    def _inclusions(self, versions):
 
 
512
        """Return set of all ancestors of given version(s)."""
 
 
513
        if not len(versions):
 
 
516
        for v in xrange(max(versions), 0, -1):
 
 
518
                # include all its parents
 
 
519
                i.update(self._parents[v])
 
 
521
        ## except IndexError:
 
 
522
        ##     raise ValueError("version %d not present in weave" % v)
 
 
524
    def get_ancestry(self, version_ids, topo_sorted=True):
 
 
525
        """See VersionedFile.get_ancestry."""
 
 
526
        if isinstance(version_ids, basestring):
 
 
527
            version_ids = [version_ids]
 
 
528
        i = self._inclusions([self._lookup(v) for v in version_ids])
 
 
529
        return [self._idx_to_name(v) for v in i]
 
 
531
    def _check_lines(self, text):
 
 
532
        if not isinstance(text, list):
 
 
533
            raise ValueError("text should be a list, not %s" % type(text))
 
 
536
            if not isinstance(l, basestring):
 
 
537
                raise ValueError("text line should be a string or unicode, not %s"
 
 
542
    def _check_versions(self, indexes):
 
 
543
        """Check everything in the sequence of indexes is valid"""
 
 
548
                raise IndexError("invalid version number %r" % i)
 
 
550
    def _compatible_parents(self, my_parents, other_parents):
 
 
551
        """During join check that other_parents are joinable with my_parents.
 
 
553
        Joinable is defined as 'is a subset of' - supersets may require 
 
 
554
        regeneration of diffs, but subsets do not.
 
 
556
        return len(other_parents.difference(my_parents)) == 0
 
 
558
    def annotate(self, version_id):
 
 
559
        """Return a list of (version-id, line) tuples for version_id.
 
 
561
        The index indicates when the line originated in the weave."""
 
 
562
        incls = [self._lookup(version_id)]
 
 
563
        return [(self._idx_to_name(origin), text) for origin, lineno, text in
 
 
564
            self._extract(incls)]
 
 
566
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
 
 
568
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
 
 
569
        if version_ids is None:
 
 
570
            version_ids = self.versions()
 
 
571
        version_ids = set(version_ids)
 
 
572
        for lineno, inserted, deletes, line in self._walk_internal(version_ids):
 
 
573
            # if inserted not in version_ids then it was inserted before the
 
 
574
            # versions we care about, but because weaves cannot represent ghosts
 
 
575
            # properly, we do not filter down to that
 
 
576
            # if inserted not in version_ids: continue
 
 
578
                yield line + '\n', inserted
 
 
582
    def _walk_internal(self, version_ids=None):
 
 
583
        """Helper method for weave actions."""
 
 
588
        lineno = 0         # line of weave, 0-based
 
 
590
        for l in self._weave:
 
 
591
            if l.__class__ == tuple:
 
 
595
                    istack.append(self._names[v])
 
 
599
                    dset.add(self._names[v])
 
 
601
                    dset.remove(self._names[v])
 
 
603
                    raise WeaveFormatError('unexpected instruction %r' % v)
 
 
605
                yield lineno, istack[-1], frozenset(dset), l
 
 
609
            raise WeaveFormatError("unclosed insertion blocks "
 
 
610
                    "at end of weave: %s" % istack)
 
 
612
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
 
 
615
    def plan_merge(self, ver_a, ver_b):
 
 
616
        """Return pseudo-annotation indicating how the two versions merge.
 
 
618
        This is computed between versions a and b and their common
 
 
621
        Weave lines present in none of them are skipped entirely.
 
 
623
        inc_a = set(self.get_ancestry([ver_a]))
 
 
624
        inc_b = set(self.get_ancestry([ver_b]))
 
 
625
        inc_c = inc_a & inc_b
 
 
627
        for lineno, insert, deleteset, line in self._walk_internal([ver_a, ver_b]):
 
 
628
            if deleteset & inc_c:
 
 
629
                # killed in parent; can't be in either a or b
 
 
630
                # not relevant to our work
 
 
631
                yield 'killed-base', line
 
 
632
            elif insert in inc_c:
 
 
633
                # was inserted in base
 
 
634
                killed_a = bool(deleteset & inc_a)
 
 
635
                killed_b = bool(deleteset & inc_b)
 
 
636
                if killed_a and killed_b:
 
 
637
                    yield 'killed-both', line
 
 
639
                    yield 'killed-a', line
 
 
641
                    yield 'killed-b', line
 
 
643
                    yield 'unchanged', line
 
 
644
            elif insert in inc_a:
 
 
645
                if deleteset & inc_a:
 
 
646
                    yield 'ghost-a', line
 
 
650
            elif insert in inc_b:
 
 
651
                if deleteset & inc_b:
 
 
652
                    yield 'ghost-b', line
 
 
656
                # not in either revision
 
 
657
                yield 'irrelevant', line
 
 
659
    def _extract(self, versions):
 
 
660
        """Yield annotation of lines in included set.
 
 
662
        Yields a sequence of tuples (origin, lineno, text), where
 
 
663
        origin is the origin version, lineno the index in the weave,
 
 
664
        and text the text of the line.
 
 
666
        The set typically but not necessarily corresponds to a version.
 
 
669
            if not isinstance(i, int):
 
 
672
        included = self._inclusions(versions)
 
 
678
        lineno = 0         # line of weave, 0-based
 
 
684
        WFE = WeaveFormatError
 
 
687
        #  449       0   4474.6820   2356.5590   bzrlib.weave:556(_extract)
 
 
688
        #  +285282   0   1676.8040   1676.8040   +<isinstance>
 
 
689
        # 1.6 seconds in 'isinstance'.
 
 
690
        # changing the first isinstance:
 
 
691
        #  449       0   2814.2660   1577.1760   bzrlib.weave:556(_extract)
 
 
692
        #  +140414   0    762.8050    762.8050   +<isinstance>
 
 
693
        # note that the inline time actually dropped (less function calls)
 
 
694
        # and total processing time was halved.
 
 
695
        # we're still spending ~1/4 of the method in isinstance though.
 
 
696
        # so lets hard code the acceptable string classes we expect:
 
 
697
        #  449       0   1202.9420    786.2930   bzrlib.weave:556(_extract)
 
 
698
        # +71352     0    377.5560    377.5560   +<method 'append' of 'list' 
 
 
700
        # yay, down to ~1/4 the initial extract time, and our inline time
 
 
701
        # has shrunk again, with isinstance no longer dominating.
 
 
702
        # tweaking the stack inclusion test to use a set gives:
 
 
703
        #  449       0   1122.8030    713.0080   bzrlib.weave:556(_extract)
 
 
704
        # +71352     0    354.9980    354.9980   +<method 'append' of 'list' 
 
 
706
        # - a 5% win, or possibly just noise. However with large istacks that
 
 
707
        # 'in' test could dominate, so I'm leaving this change in place -
 
 
708
        # when its fast enough to consider profiling big datasets we can review.
 
 
713
        for l in self._weave:
 
 
714
            if l.__class__ == tuple:
 
 
721
                    iset.remove(istack.pop())
 
 
729
                    raise AssertionError()
 
 
732
                    isactive = (not dset) and istack and (istack[-1] in included)
 
 
734
                    result.append((istack[-1], lineno, l))
 
 
737
            raise WeaveFormatError("unclosed insertion blocks "
 
 
738
                    "at end of weave: %s" % istack)
 
 
740
            raise WeaveFormatError("unclosed deletion blocks at end of weave: %s"
 
 
744
    def _maybe_lookup(self, name_or_index):
 
 
745
        """Convert possible symbolic name to index, or pass through indexes.
 
 
749
        if isinstance(name_or_index, (int, long)):
 
 
752
            return self._lookup(name_or_index)
 
 
754
    def get_lines(self, version_id):
 
 
755
        """See VersionedFile.get_lines()."""
 
 
756
        int_index = self._maybe_lookup(version_id)
 
 
757
        result = [line for (origin, lineno, line) in self._extract([int_index])]
 
 
758
        expected_sha1 = self._sha1s[int_index]
 
 
759
        measured_sha1 = sha_strings(result)
 
 
760
        if measured_sha1 != expected_sha1:
 
 
761
            raise errors.WeaveInvalidChecksum(
 
 
762
                    'file %s, revision %s, expected: %s, measured %s' 
 
 
763
                    % (self._weave_name, version_id,
 
 
764
                       expected_sha1, measured_sha1))
 
 
767
    def get_sha1s(self, version_ids):
 
 
768
        """See VersionedFile.get_sha1s()."""
 
 
769
        return [self._sha1s[self._lookup(v)] for v in version_ids]
 
 
771
    def num_versions(self):
 
 
772
        """How many versions are in this weave?"""
 
 
773
        l = len(self._parents)
 
 
776
    __len__ = num_versions
 
 
778
    def check(self, progress_bar=None):
 
 
779
        # TODO evaluate performance hit of using string sets in this routine.
 
 
780
        # TODO: check no circular inclusions
 
 
781
        # TODO: create a nested progress bar
 
 
782
        for version in range(self.num_versions()):
 
 
783
            inclusions = list(self._parents[version])
 
 
786
                if inclusions[-1] >= version:
 
 
787
                    raise WeaveFormatError("invalid included version %d for index %d"
 
 
788
                                           % (inclusions[-1], version))
 
 
790
        # try extracting all versions; parallel extraction is used
 
 
791
        nv = self.num_versions()
 
 
796
            # For creating the ancestry, IntSet is much faster (3.7s vs 0.17s)
 
 
797
            # The problem is that set membership is much more expensive
 
 
798
            name = self._idx_to_name(i)
 
 
799
            sha1s[name] = sha.new()
 
 
801
            new_inc = set([name])
 
 
802
            for p in self._parents[i]:
 
 
803
                new_inc.update(inclusions[self._idx_to_name(p)])
 
 
805
            if set(new_inc) != set(self.get_ancestry(name)):
 
 
806
                raise AssertionError(
 
 
808
                    % (set(new_inc), set(self.get_ancestry(name))))
 
 
809
            inclusions[name] = new_inc
 
 
811
        nlines = len(self._weave)
 
 
813
        update_text = 'checking weave'
 
 
815
            short_name = os.path.basename(self._weave_name)
 
 
816
            update_text = 'checking %s' % (short_name,)
 
 
817
            update_text = update_text[:25]
 
 
819
        for lineno, insert, deleteset, line in self._walk_internal():
 
 
821
                progress_bar.update(update_text, lineno, nlines)
 
 
823
            for name, name_inclusions in inclusions.items():
 
 
824
                # The active inclusion must be an ancestor,
 
 
825
                # and no ancestors must have deleted this line,
 
 
826
                # because we don't support resurrection.
 
 
827
                if (insert in name_inclusions) and not (deleteset & name_inclusions):
 
 
828
                    sha1s[name].update(line)
 
 
831
            version = self._idx_to_name(i)
 
 
832
            hd = sha1s[version].hexdigest()
 
 
833
            expected = self._sha1s[i]
 
 
835
                raise errors.WeaveInvalidChecksum(
 
 
836
                        "mismatched sha1 for version %s: "
 
 
837
                        "got %s, expected %s"
 
 
838
                        % (version, hd, expected))
 
 
840
        # TODO: check insertions are properly nested, that there are
 
 
841
        # no lines outside of insertion blocks, that deletions are
 
 
842
        # properly paired, etc.
 
 
844
    def _imported_parents(self, other, other_idx):
 
 
845
        """Return list of parents in self corresponding to indexes in other."""
 
 
847
        for parent_idx in other._parents[other_idx]:
 
 
848
            parent_name = other._names[parent_idx]
 
 
849
            if parent_name not in self._name_map:
 
 
850
                # should not be possible
 
 
851
                raise WeaveError("missing parent {%s} of {%s} in %r" 
 
 
852
                                 % (parent_name, other._name_map[other_idx], self))
 
 
853
            new_parents.append(self._name_map[parent_name])
 
 
856
    def _check_version_consistent(self, other, other_idx, name):
 
 
857
        """Check if a version in consistent in this and other.
 
 
859
        To be consistent it must have:
 
 
862
         * the same direct parents (by name, not index, and disregarding
 
 
865
        If present & correct return True;
 
 
866
        if not present in self return False; 
 
 
867
        if inconsistent raise error."""
 
 
868
        this_idx = self._name_map.get(name, -1)
 
 
870
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
 
 
871
                raise errors.WeaveTextDiffers(name, self, other)
 
 
872
            self_parents = self._parents[this_idx]
 
 
873
            other_parents = other._parents[other_idx]
 
 
874
            n1 = set([self._names[i] for i in self_parents])
 
 
875
            n2 = set([other._names[i] for i in other_parents])
 
 
876
            if not self._compatible_parents(n1, n2):
 
 
877
                raise WeaveParentMismatch("inconsistent parents "
 
 
878
                    "for version {%s}: %s vs %s" % (name, n1, n2))
 
 
884
    def _reweave(self, other, pb, msg):
 
 
885
        """Reweave self with other - internal helper for join().
 
 
887
        :param other: The other weave to merge
 
 
888
        :param pb: An optional progress bar, indicating how far done we are
 
 
889
        :param msg: An optional message for the progress
 
 
891
        new_weave = _reweave(self, other, pb=pb, msg=msg)
 
 
892
        self._copy_weave_content(new_weave)
 
 
894
    def _copy_weave_content(self, otherweave):
 
 
895
        """adsorb the content from otherweave."""
 
 
896
        for attr in self.__slots__:
 
 
897
            if attr != '_weave_name':
 
 
898
                setattr(self, attr, copy(getattr(otherweave, attr)))
 
 
901
class WeaveFile(Weave):
 
 
902
    """A WeaveFile represents a Weave on disk and writes on change."""
 
 
904
    WEAVE_SUFFIX = '.weave'
 
 
906
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
 
 
907
        """Create a WeaveFile.
 
 
909
        :param create: If not True, only open an existing knit.
 
 
911
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
 
 
912
            allow_reserved=False)
 
 
913
        self._transport = transport
 
 
914
        self._filemode = filemode
 
 
916
            _read_weave_v5(self._transport.get(name + WeaveFile.WEAVE_SUFFIX), self)
 
 
917
        except errors.NoSuchFile:
 
 
923
    def _add_lines(self, version_id, parents, lines, parent_texts,
 
 
924
        left_matching_blocks, nostore_sha, random_id, check_content):
 
 
925
        """Add a version and save the weave."""
 
 
926
        self.check_not_reserved_id(version_id)
 
 
927
        result = super(WeaveFile, self)._add_lines(version_id, parents, lines,
 
 
928
            parent_texts, left_matching_blocks, nostore_sha, random_id,
 
 
933
    def copy_to(self, name, transport):
 
 
934
        """See VersionedFile.copy_to()."""
 
 
935
        # as we are all in memory always, just serialise to the new place.
 
 
937
        write_weave_v5(self, sio)
 
 
939
        transport.put_file(name + WeaveFile.WEAVE_SUFFIX, sio, self._filemode)
 
 
942
        """Save the weave."""
 
 
943
        self._check_write_ok()
 
 
945
        write_weave_v5(self, sio)
 
 
947
        bytes = sio.getvalue()
 
 
948
        path = self._weave_name + WeaveFile.WEAVE_SUFFIX
 
 
950
            self._transport.put_bytes(path, bytes, self._filemode)
 
 
951
        except errors.NoSuchFile:
 
 
952
            self._transport.mkdir(dirname(path))
 
 
953
            self._transport.put_bytes(path, bytes, self._filemode)
 
 
957
        """See VersionedFile.get_suffixes()."""
 
 
958
        return [WeaveFile.WEAVE_SUFFIX]
 
 
960
    def insert_record_stream(self, stream):
 
 
961
        super(WeaveFile, self).insert_record_stream(stream)
 
 
964
    @deprecated_method(one_five)
 
 
965
    def join(self, other, pb=None, msg=None, version_ids=None,
 
 
966
             ignore_missing=False):
 
 
967
        """Join other into self and save."""
 
 
968
        super(WeaveFile, self).join(other, pb, msg, version_ids, ignore_missing)
 
 
972
def _reweave(wa, wb, pb=None, msg=None):
 
 
973
    """Combine two weaves and return the result.
 
 
975
    This works even if a revision R has different parents in 
 
 
976
    wa and wb.  In the resulting weave all the parents are given.
 
 
978
    This is done by just building up a new weave, maintaining ordering 
 
 
979
    of the versions in the two inputs.  More efficient approaches
 
 
980
    might be possible but it should only be necessary to do 
 
 
981
    this operation rarely, when a new previously ghost version is 
 
 
984
    :param pb: An optional progress bar, indicating how far done we are
 
 
985
    :param msg: An optional message for the progress
 
 
989
    queue_a = range(wa.num_versions())
 
 
990
    queue_b = range(wb.num_versions())
 
 
991
    # first determine combined parents of all versions
 
 
992
    # map from version name -> all parent names
 
 
993
    combined_parents = _reweave_parent_graphs(wa, wb)
 
 
994
    mutter("combined parents: %r", combined_parents)
 
 
995
    order = topo_sort(combined_parents.iteritems())
 
 
996
    mutter("order to reweave: %r", order)
 
 
1001
    for idx, name in enumerate(order):
 
 
1003
            pb.update(msg, idx, len(order))
 
 
1004
        if name in wa._name_map:
 
 
1005
            lines = wa.get_lines(name)
 
 
1006
            if name in wb._name_map:
 
 
1007
                lines_b = wb.get_lines(name)
 
 
1008
                if lines != lines_b:
 
 
1009
                    mutter('Weaves differ on content. rev_id {%s}', name)
 
 
1010
                    mutter('weaves: %s, %s', wa._weave_name, wb._weave_name)
 
 
1012
                    lines = list(difflib.unified_diff(lines, lines_b,
 
 
1013
                            wa._weave_name, wb._weave_name))
 
 
1014
                    mutter('lines:\n%s', ''.join(lines))
 
 
1015
                    raise errors.WeaveTextDiffers(name, wa, wb)
 
 
1017
            lines = wb.get_lines(name)
 
 
1018
        wr._add(name, lines, [wr._lookup(i) for i in combined_parents[name]])
 
 
1021
def _reweave_parent_graphs(wa, wb):
 
 
1022
    """Return combined parent ancestry for two weaves.
 
 
1024
    Returned as a list of (version_name, set(parent_names))"""
 
 
1026
    for weave in [wa, wb]:
 
 
1027
        for idx, name in enumerate(weave._names):
 
 
1028
            p = combined.setdefault(name, set())
 
 
1029
            p.update(map(weave._idx_to_name, weave._parents[idx]))
 
 
1034
    """Show the weave's table-of-contents"""
 
 
1035
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
 
 
1036
    for i in (6, 50, 10, 10):
 
 
1039
    for i in range(w.num_versions()):
 
 
1042
        parent_str = ' '.join(map(str, w._parents[i]))
 
 
1043
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
 
 
1047
def weave_stats(weave_file, pb):
 
 
1048
    from bzrlib.weavefile import read_weave
 
 
1050
    wf = file(weave_file, 'rb')
 
 
1052
    # FIXME: doesn't work on pipes
 
 
1053
    weave_size = wf.tell()
 
 
1057
    for i in range(vers):
 
 
1058
        pb.update('checking sizes', i, vers)
 
 
1059
        for origin, lineno, line in w._extract([i]):
 
 
1064
    print 'versions          %9d' % vers
 
 
1065
    print 'weave file        %9d bytes' % weave_size
 
 
1066
    print 'total contents    %9d bytes' % total
 
 
1067
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
 
 
1070
        print 'average size      %9d bytes' % avg
 
 
1071
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
 
 
1075
    print """bzr weave tool
 
 
1077
Experimental tool for weave algorithm.
 
 
1080
    weave init WEAVEFILE
 
 
1081
        Create an empty weave file
 
 
1082
    weave get WEAVEFILE VERSION
 
 
1083
        Write out specified version.
 
 
1084
    weave check WEAVEFILE
 
 
1085
        Check consistency of all versions.
 
 
1087
        Display table of contents.
 
 
1088
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
 
 
1089
        Add NEWTEXT, with specified parent versions.
 
 
1090
    weave annotate WEAVEFILE VERSION
 
 
1091
        Display origin of each line.
 
 
1092
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
 
 
1093
        Auto-merge two versions and display conflicts.
 
 
1094
    weave diff WEAVEFILE VERSION1 VERSION2 
 
 
1095
        Show differences between two versions.
 
 
1099
    % weave init foo.weave
 
 
1101
    % weave add foo.weave ver0 < foo.txt
 
 
1104
    (create updated version)
 
 
1106
    % weave get foo.weave 0 | diff -u - foo.txt
 
 
1107
    % weave add foo.weave ver1 0 < foo.txt
 
 
1110
    % weave get foo.weave 0 > foo.txt       (create forked version)
 
 
1112
    % weave add foo.weave ver2 0 < foo.txt
 
 
1115
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
 
 
1116
    % vi foo.txt                            (resolve conflicts)
 
 
1117
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
 
 
1129
        # in case we're run directly from the subdirectory
 
 
1130
        sys.path.append('..')
 
 
1132
    from bzrlib.weavefile import write_weave, read_weave
 
 
1133
    from bzrlib.progress import ProgressBar
 
 
1148
        return read_weave(file(argv[2], 'rb'))
 
 
1154
        # at the moment, based on everything in the file
 
 
1156
        parents = map(int, argv[4:])
 
 
1157
        lines = sys.stdin.readlines()
 
 
1158
        ver = w.add(name, parents, lines)
 
 
1159
        write_weave(w, file(argv[2], 'wb'))
 
 
1160
        print 'added version %r %d' % (name, ver)
 
 
1163
        if os.path.exists(fn):
 
 
1164
            raise IOError("file exists")
 
 
1166
        write_weave(w, file(fn, 'wb'))
 
 
1167
    elif cmd == 'get': # get one version
 
 
1169
        sys.stdout.writelines(w.get_iter(int(argv[3])))
 
 
1174
        v1, v2 = map(int, argv[3:5])
 
 
1177
        diff_gen = bzrlib.patiencediff.unified_diff(lines1, lines2,
 
 
1178
                                '%s version %d' % (fn, v1),
 
 
1179
                                '%s version %d' % (fn, v2))
 
 
1180
        sys.stdout.writelines(diff_gen)
 
 
1182
    elif cmd == 'annotate':
 
 
1184
        # newline is added to all lines regardless; too hard to get
 
 
1185
        # reasonable formatting otherwise
 
 
1187
        for origin, text in w.annotate(int(argv[3])):
 
 
1188
            text = text.rstrip('\r\n')
 
 
1190
                print '      | %s' % (text)
 
 
1192
                print '%5d | %s' % (origin, text)
 
 
1198
    elif cmd == 'stats':
 
 
1199
        weave_stats(argv[2], ProgressBar())
 
 
1201
    elif cmd == 'check':
 
 
1206
        print '%d versions ok' % w.num_versions()
 
 
1208
    elif cmd == 'inclusions':
 
 
1210
        print ' '.join(map(str, w.inclusions([int(argv[3])])))
 
 
1212
    elif cmd == 'parents':
 
 
1214
        print ' '.join(map(str, w._parents[int(argv[3])]))
 
 
1216
    elif cmd == 'plan-merge':
 
 
1217
        # replaced by 'bzr weave-plan-merge'
 
 
1219
        for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
 
 
1221
                print '%14s | %s' % (state, line),
 
 
1222
    elif cmd == 'merge':
 
 
1223
        # replaced by 'bzr weave-merge-text'
 
 
1225
        p = w.plan_merge(int(argv[3]), int(argv[4]))
 
 
1226
        sys.stdout.writelines(w.weave_merge(p))
 
 
1228
        raise ValueError('unknown command %r' % cmd)
 
 
1231
if __name__ == '__main__':
 
 
1233
    sys.exit(main(sys.argv))