/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

First attempt to merge .dev and resolve the conflicts (but tests are 
failing)

Show diffs side-by-side

added added

removed removed

Lines of Context:
75
75
import time
76
76
import warnings
77
77
 
78
 
from bzrlib.trace import mutter
 
78
from bzrlib import (
 
79
    progress,
 
80
    )
79
81
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
80
82
        RevisionAlreadyPresent,
81
83
        RevisionNotPresent,
 
84
        UnavailableRepresentation,
82
85
        WeaveRevisionAlreadyPresent,
83
86
        WeaveRevisionNotPresent,
84
87
        )
85
88
import bzrlib.errors as errors
86
 
from bzrlib.osutils import sha_strings
 
89
from bzrlib.osutils import dirname, sha_strings, split_lines
87
90
import bzrlib.patiencediff
88
 
from bzrlib.symbol_versioning import (deprecated_method,
89
 
        deprecated_function,
90
 
        zero_eight,
91
 
        )
 
91
from bzrlib.revision import NULL_REVISION
 
92
from bzrlib.symbol_versioning import *
 
93
from bzrlib.trace import mutter
92
94
from bzrlib.tsort import topo_sort
93
 
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
 
95
from bzrlib.versionedfile import (
 
96
    AbsentContentFactory,
 
97
    adapter_registry,
 
98
    ContentFactory,
 
99
    VersionedFile,
 
100
    )
94
101
from bzrlib.weavefile import _read_weave_v5, write_weave_v5
95
102
 
96
103
 
 
104
class WeaveContentFactory(ContentFactory):
 
105
    """Content factory for streaming from weaves.
 
106
 
 
107
    :seealso ContentFactory:
 
108
    """
 
109
 
 
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])[version]
 
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'
 
118
        self._weave = weave
 
119
 
 
120
    def get_bytes_as(self, storage_kind):
 
121
        if storage_kind == 'fulltext':
 
122
            return self._weave.get_text(self.key[-1])
 
123
        else:
 
124
            raise UnavailableRepresentation(self.key, storage_kind, 'fulltext')
 
125
 
 
126
 
97
127
class Weave(VersionedFile):
98
128
    """weave - versioned text file storage.
99
129
    
184
214
    """
185
215
 
186
216
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
187
 
                 '_weave_name', '_matcher']
 
217
                 '_weave_name', '_matcher', '_allow_reserved']
188
218
    
189
 
    def __init__(self, weave_name=None, access_mode='w', matcher=None):
 
219
    def __init__(self, weave_name=None, access_mode='w', matcher=None,
 
220
                 get_scope=None, allow_reserved=False):
 
221
        """Create a weave.
 
222
 
 
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).
 
226
        """
190
227
        super(Weave, self).__init__(access_mode)
191
228
        self._weave = []
192
229
        self._parents = []
198
235
            self._matcher = bzrlib.patiencediff.PatienceSequenceMatcher
199
236
        else:
200
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
201
244
 
202
245
    def __repr__(self):
203
246
        return "Weave(%r)" % self._weave_name
204
247
 
 
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)
 
254
 
205
255
    def copy(self):
206
256
        """Return a deep copy of self.
207
257
        
225
275
    def __ne__(self, other):
226
276
        return not self.__eq__(other)
227
277
 
228
 
    @deprecated_method(zero_eight)
229
 
    def idx_to_name(self, index):
230
 
        """Old public interface, the public interface is all names now."""
231
 
        return index
232
 
 
233
278
    def _idx_to_name(self, version):
234
279
        return self._names[version]
235
280
 
236
 
    @deprecated_method(zero_eight)
237
 
    def lookup(self, name):
238
 
        """Backwards compatibility thunk:
239
 
 
240
 
        Return name, as name is valid in the api now, and spew deprecation
241
 
        warnings everywhere.
242
 
        """
243
 
        return name
244
 
 
245
281
    def _lookup(self, name):
246
282
        """Convert symbolic version name to index."""
 
283
        if not self._allow_reserved:
 
284
            self.check_not_reserved_id(name)
247
285
        try:
248
286
            return self._name_map[name]
249
287
        except KeyError:
250
288
            raise RevisionNotPresent(name, self._weave_name)
251
289
 
252
 
    @deprecated_method(zero_eight)
253
 
    def iter_names(self):
254
 
        """Deprecated convenience function, please see VersionedFile.names()."""
255
 
        return iter(self.names())
256
 
 
257
 
    @deprecated_method(zero_eight)
258
 
    def names(self):
259
 
        """See Weave.versions for the current api."""
260
 
        return self.versions()
261
 
 
262
290
    def versions(self):
263
291
        """See VersionedFile.versions."""
264
292
        return self._names[:]
269
297
 
270
298
    __contains__ = has_version
271
299
 
272
 
    def get_delta(self, version_id):
273
 
        """See VersionedFile.get_delta."""
274
 
        return self.get_deltas([version_id])[version_id]
275
 
 
276
 
    def get_deltas(self, version_ids):
277
 
        """See VersionedFile.get_deltas."""
278
 
        version_ids = self.get_ancestry(version_ids)
 
300
    def get_record_stream(self, versions, ordering, include_delta_closure):
 
301
        """Get a stream of records for versions.
 
302
 
 
303
        :param versions: The versions to include. Each version is a tuple
 
304
            (version,).
 
305
        :param ordering: Either 'unordered' or 'topological'. A topologically
 
306
            sorted stream has compression parents strictly before their
 
307
            children.
 
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.
 
312
        """
 
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:
 
320
            if version in self:
 
321
                yield WeaveContentFactory(version, self)
 
322
            else:
 
323
                yield AbsentContentFactory((version,))
 
324
 
 
325
    def get_parent_map(self, version_ids):
 
326
        """See VersionedFile.get_parent_map."""
 
327
        result = {}
279
328
        for version_id in version_ids:
280
 
            if not self.has_version(version_id):
281
 
                raise RevisionNotPresent(version_id, self)
282
 
        # try extracting all versions; parallel extraction is used
283
 
        nv = self.num_versions()
284
 
        sha1s = {}
285
 
        deltas = {}
286
 
        texts = {}
287
 
        inclusions = {}
288
 
        noeols = {}
289
 
        last_parent_lines = {}
290
 
        parents = {}
291
 
        parent_inclusions = {}
292
 
        parent_linenums = {}
293
 
        parent_noeols = {}
294
 
        current_hunks = {}
295
 
        diff_hunks = {}
296
 
        # its simplest to generate a full set of prepared variables.
297
 
        for i in range(nv):
298
 
            name = self._names[i]
299
 
            sha1s[name] = self.get_sha1(name)
300
 
            parents_list = self.get_parents(name)
301
 
            try:
302
 
                parent = parents_list[0]
303
 
                parents[name] = parent
304
 
                parent_inclusions[name] = inclusions[parent]
305
 
            except IndexError:
306
 
                parents[name] = None
307
 
                parent_inclusions[name] = set()
308
 
            # we want to emit start, finish, replacement_length, replacement_lines tuples.
309
 
            diff_hunks[name] = []
310
 
            current_hunks[name] = [0, 0, 0, []] # #start, finish, repl_length, repl_tuples
311
 
            parent_linenums[name] = 0
312
 
            noeols[name] = False
313
 
            parent_noeols[name] = False
314
 
            last_parent_lines[name] = None
315
 
            new_inc = set([name])
316
 
            for p in self._parents[i]:
317
 
                new_inc.update(inclusions[self._idx_to_name(p)])
318
 
            # debug only, known good so far.
319
 
            #assert set(new_inc) == set(self.get_ancestry(name)), \
320
 
            #    'failed %s != %s' % (set(new_inc), set(self.get_ancestry(name)))
321
 
            inclusions[name] = new_inc
322
 
 
323
 
        nlines = len(self._weave)
324
 
 
325
 
        for lineno, inserted, deletes, line in self._walk_internal():
326
 
            # a line is active in a version if:
327
 
            # insert is in the versions inclusions
328
 
            # and
329
 
            # deleteset & the versions inclusions is an empty set.
330
 
            # so - if we have a included by mapping - version is included by
331
 
            # children, we get a list of children to examine for deletes affect
332
 
            # ing them, which is less than the entire set of children.
333
 
            for version_id in version_ids:  
334
 
                # The active inclusion must be an ancestor,
335
 
                # and no ancestors must have deleted this line,
336
 
                # because we don't support resurrection.
337
 
                parent_inclusion = parent_inclusions[version_id]
338
 
                inclusion = inclusions[version_id]
339
 
                parent_active = inserted in parent_inclusion and not (deletes & parent_inclusion)
340
 
                version_active = inserted in inclusion and not (deletes & inclusion)
341
 
                if not parent_active and not version_active:
342
 
                    # unrelated line of ancestry
 
329
            if version_id == NULL_REVISION:
 
330
                parents = ()
 
331
            else:
 
332
                try:
 
333
                    parents = tuple(
 
334
                        map(self._idx_to_name,
 
335
                            self._parents[self._lookup(version_id)]))
 
336
                except RevisionNotPresent:
343
337
                    continue
344
 
                elif parent_active and version_active:
345
 
                    # shared line
346
 
                    parent_linenum = parent_linenums[version_id]
347
 
                    if current_hunks[version_id] != [parent_linenum, parent_linenum, 0, []]:
348
 
                        diff_hunks[version_id].append(tuple(current_hunks[version_id]))
349
 
                    parent_linenum += 1
350
 
                    current_hunks[version_id] = [parent_linenum, parent_linenum, 0, []]
351
 
                    parent_linenums[version_id] = parent_linenum
352
 
                    try:
353
 
                        if line[-1] != '\n':
354
 
                            noeols[version_id] = True
355
 
                    except IndexError:
356
 
                        pass
357
 
                elif parent_active and not version_active:
358
 
                    # deleted line
359
 
                    current_hunks[version_id][1] += 1
360
 
                    parent_linenums[version_id] += 1
361
 
                    last_parent_lines[version_id] = line
362
 
                elif not parent_active and version_active:
363
 
                    # replacement line
364
 
                    # noeol only occurs at the end of a file because we 
365
 
                    # diff linewise. We want to show noeol changes as a
366
 
                    # empty diff unless the actual eol-less content changed.
367
 
                    theline = line
368
 
                    try:
369
 
                        if last_parent_lines[version_id][-1] != '\n':
370
 
                            parent_noeols[version_id] = True
371
 
                    except (TypeError, IndexError):
372
 
                        pass
373
 
                    try:
374
 
                        if theline[-1] != '\n':
375
 
                            noeols[version_id] = True
376
 
                    except IndexError:
377
 
                        pass
378
 
                    new_line = False
379
 
                    parent_should_go = False
380
 
 
381
 
                    if parent_noeols[version_id] == noeols[version_id]:
382
 
                        # no noeol toggle, so trust the weaves statement
383
 
                        # that this line is changed.
384
 
                        new_line = True
385
 
                        if parent_noeols[version_id]:
386
 
                            theline = theline + '\n'
387
 
                    elif parent_noeols[version_id]:
388
 
                        # parent has no eol, we do:
389
 
                        # our line is new, report as such..
390
 
                        new_line = True
391
 
                    elif noeols[version_id]:
392
 
                        # append a eol so that it looks like
393
 
                        # a normalised delta
394
 
                        theline = theline + '\n'
395
 
                        if parents[version_id] is not None:
396
 
                        #if last_parent_lines[version_id] is not None:
397
 
                            parent_should_go = True
398
 
                        if last_parent_lines[version_id] != theline:
399
 
                            # but changed anyway
400
 
                            new_line = True
401
 
                            #parent_should_go = False
402
 
                    if new_line:
403
 
                        current_hunks[version_id][2] += 1
404
 
                        current_hunks[version_id][3].append((inserted, theline))
405
 
                    if parent_should_go:
406
 
                        # last hunk last parent line is not eaten
407
 
                        current_hunks[version_id][1] -= 1
408
 
                    if current_hunks[version_id][1] < 0:
409
 
                        current_hunks[version_id][1] = 0
410
 
                        # import pdb;pdb.set_trace()
411
 
                    # assert current_hunks[version_id][1] >= 0
412
 
 
413
 
        # flush last hunk
414
 
        for i in range(nv):
415
 
            version = self._idx_to_name(i)
416
 
            if current_hunks[version] != [0, 0, 0, []]:
417
 
                diff_hunks[version].append(tuple(current_hunks[version]))
418
 
        result = {}
419
 
        for version_id in version_ids:
420
 
            result[version_id] = (
421
 
                                  parents[version_id],
422
 
                                  sha1s[version_id],
423
 
                                  noeols[version_id],
424
 
                                  diff_hunks[version_id],
425
 
                                  )
 
338
            result[version_id] = parents
426
339
        return result
427
340
 
428
 
    def get_parents(self, version_id):
429
 
        """See VersionedFile.get_parent."""
430
 
        return map(self._idx_to_name, self._parents[self._lookup(version_id)])
 
341
    def get_parents_with_ghosts(self, version_id):
 
342
        raise NotImplementedError(self.get_parents_with_ghosts)
 
343
 
 
344
    def insert_record_stream(self, stream):
 
345
        """Insert a record stream into this versioned file.
 
346
 
 
347
        :param stream: A stream of records to insert. 
 
348
        :return: None
 
349
        :seealso VersionedFile.get_record_stream:
 
350
        """
 
351
        adapters = {}
 
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')))
 
361
            else:
 
362
                adapter_key = record.storage_kind, 'fulltext'
 
363
                try:
 
364
                    adapter = adapters[adapter_key]
 
365
                except KeyError:
 
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)))
 
371
                try:
 
372
                    self.add_lines(record.key[0], parents, lines)
 
373
                except RevisionAlreadyPresent:
 
374
                    pass
431
375
 
432
376
    def _check_repeated_add(self, name, parents, text, sha1):
433
377
        """Check that a duplicated add is OK.
440
384
            raise RevisionAlreadyPresent(name, self._weave_name)
441
385
        return idx
442
386
 
443
 
    @deprecated_method(zero_eight)
444
 
    def add_identical(self, old_rev_id, new_rev_id, parents):
445
 
        """Please use Weave.clone_text now."""
446
 
        return self.clone_text(new_rev_id, old_rev_id, parents)
447
 
 
448
 
    def _add_lines(self, version_id, parents, lines, parent_texts):
 
387
    def _add_lines(self, version_id, parents, lines, parent_texts,
 
388
       left_matching_blocks, nostore_sha, random_id, check_content):
449
389
        """See VersionedFile.add_lines."""
450
 
        return self._add(version_id, lines, map(self._lookup, parents))
451
 
 
452
 
    @deprecated_method(zero_eight)
453
 
    def add(self, name, parents, text, sha1=None):
454
 
        """See VersionedFile.add_lines for the non deprecated api."""
455
 
        return self._add(name, text, map(self._maybe_lookup, parents), sha1)
456
 
 
457
 
    def _add(self, version_id, lines, parents, sha1=None):
 
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
 
393
 
 
394
    def _add(self, version_id, lines, parents, sha1=None, nostore_sha=None):
458
395
        """Add a single text on top of the weave.
459
396
  
460
397
        Returns the index number of the newly added version.
468
405
            
469
406
        lines
470
407
            Sequence of lines to be added in the new version.
 
408
 
 
409
        :param nostore_sha: See VersionedFile.add_lines.
471
410
        """
472
 
 
473
 
        assert isinstance(version_id, basestring)
474
411
        self._check_lines_not_unicode(lines)
475
412
        self._check_lines_are_lines(lines)
476
413
        if not sha1:
477
414
            sha1 = sha_strings(lines)
 
415
        if sha1 == nostore_sha:
 
416
            raise errors.ExistingContent
478
417
        if version_id in self._name_map:
479
418
            return self._check_repeated_add(version_id, parents, lines, sha1)
480
419
 
524
463
        # another small special case: a merge, producing the same text
525
464
        # as auto-merge
526
465
        if lines == basis_lines:
527
 
            return new_version            
 
466
            return new_version
528
467
 
529
468
        # add a sentinel, because we can also match against the final line
530
469
        basis_lineno.append(len(self._weave))
549
488
            #print 'raw match', tag, i1, i2, j1, j2
550
489
            if tag == 'equal':
551
490
                continue
552
 
 
553
491
            i1 = basis_lineno[i1]
554
492
            i2 = basis_lineno[i2]
555
 
 
556
 
            assert 0 <= j1 <= j2 <= len(lines)
557
 
 
558
 
            #print tag, i1, i2, j1, j2
559
 
 
560
493
            # the deletion and insertion are handled separately.
561
494
            # first delete the region.
562
495
            if i1 != i2:
575
508
                offset += 2 + (j2 - j1)
576
509
        return new_version
577
510
 
578
 
    def _clone_text(self, new_version_id, old_version_id, parents):
579
 
        """See VersionedFile.clone_text."""
580
 
        old_lines = self.get_text(old_version_id)
581
 
        self.add_lines(new_version_id, parents, old_lines)
582
 
 
583
511
    def _inclusions(self, versions):
584
512
        """Return set of all ancestors of given version(s)."""
585
513
        if not len(versions):
593
521
        ## except IndexError:
594
522
        ##     raise ValueError("version %d not present in weave" % v)
595
523
 
596
 
    @deprecated_method(zero_eight)
597
 
    def inclusions(self, version_ids):
598
 
        """Deprecated - see VersionedFile.get_ancestry for the replacement."""
599
 
        if not version_ids:
600
 
            return []
601
 
        if isinstance(version_ids[0], int):
602
 
            return [self._idx_to_name(v) for v in self._inclusions(version_ids)]
603
 
        else:
604
 
            return self.get_ancestry(version_ids)
605
 
 
606
 
    def get_ancestry(self, version_ids):
 
524
    def get_ancestry(self, version_ids, topo_sorted=True):
607
525
        """See VersionedFile.get_ancestry."""
608
526
        if isinstance(version_ids, basestring):
609
527
            version_ids = [version_ids]
638
556
        return len(other_parents.difference(my_parents)) == 0
639
557
 
640
558
    def annotate(self, version_id):
641
 
        if isinstance(version_id, int):
642
 
            warnings.warn('Weave.annotate(int) is deprecated. Please use version names'
643
 
                 ' in all circumstances as of 0.8',
644
 
                 DeprecationWarning,
645
 
                 stacklevel=2
646
 
                 )
647
 
            result = []
648
 
            for origin, lineno, text in self._extract([version_id]):
649
 
                result.append((origin, text))
650
 
            return result
651
 
        else:
652
 
            return super(Weave, self).annotate(version_id)
653
 
    
654
 
    def annotate_iter(self, version_id):
655
 
        """Yield list of (version-id, line) pairs for the specified version.
 
559
        """Return a list of (version-id, line) tuples for version_id.
656
560
 
657
561
        The index indicates when the line originated in the weave."""
658
562
        incls = [self._lookup(version_id)]
659
 
        for origin, lineno, text in self._extract(incls):
660
 
            yield self._idx_to_name(origin), text
661
 
 
662
 
    @deprecated_method(zero_eight)
663
 
    def _walk(self):
664
 
        """_walk has become visit, a supported api."""
665
 
        return self._walk_internal()
666
 
 
667
 
    def iter_lines_added_or_present_in_versions(self, version_ids=None):
 
563
        return [(self._idx_to_name(origin), text) for origin, lineno, text in
 
564
            self._extract(incls)]
 
565
 
 
566
    def iter_lines_added_or_present_in_versions(self, version_ids=None,
 
567
                                                pb=None):
668
568
        """See VersionedFile.iter_lines_added_or_present_in_versions()."""
669
569
        if version_ids is None:
670
570
            version_ids = self.versions()
675
575
            # properly, we do not filter down to that
676
576
            # if inserted not in version_ids: continue
677
577
            if line[-1] != '\n':
678
 
                yield line + '\n'
 
578
                yield line + '\n', inserted
679
579
            else:
680
 
                yield line
681
 
 
682
 
    #@deprecated_method(zero_eight)
683
 
    def walk(self, version_ids=None):
684
 
        """See VersionedFile.walk."""
685
 
        return self._walk_internal(version_ids)
 
580
                yield line, inserted
686
581
 
687
582
    def _walk_internal(self, version_ids=None):
688
583
        """Helper method for weave actions."""
701
596
                elif c == '}':
702
597
                    istack.pop()
703
598
                elif c == '[':
704
 
                    assert self._names[v] not in dset
705
599
                    dset.add(self._names[v])
706
600
                elif c == ']':
707
601
                    dset.remove(self._names[v])
708
602
                else:
709
603
                    raise WeaveFormatError('unexpected instruction %r' % v)
710
604
            else:
711
 
                assert l.__class__ in (str, unicode)
712
 
                assert istack
713
605
                yield lineno, istack[-1], frozenset(dset), l
714
606
            lineno += 1
715
607
 
732
624
        inc_b = set(self.get_ancestry([ver_b]))
733
625
        inc_c = inc_a & inc_b
734
626
 
735
 
        for lineno, insert, deleteset, line in\
736
 
            self.walk([ver_a, ver_b]):
 
627
        for lineno, insert, deleteset, line in self._walk_internal([ver_a, ver_b]):
737
628
            if deleteset & inc_c:
738
629
                # killed in parent; can't be in either a or b
739
630
                # not relevant to our work
765
656
                # not in either revision
766
657
                yield 'irrelevant', line
767
658
 
768
 
        yield 'unchanged', ''           # terminator
769
 
 
770
659
    def _extract(self, versions):
771
660
        """Yield annotation of lines in included set.
772
661
 
826
715
                c, v = l
827
716
                isactive = None
828
717
                if c == '{':
829
 
                    assert v not in iset
830
718
                    istack.append(v)
831
719
                    iset.add(v)
832
720
                elif c == '}':
833
721
                    iset.remove(istack.pop())
834
722
                elif c == '[':
835
723
                    if v in included:
836
 
                        assert v not in dset
837
724
                        dset.add(v)
838
 
                else:
839
 
                    assert c == ']'
 
725
                elif c == ']':
840
726
                    if v in included:
841
 
                        assert v in dset
842
727
                        dset.remove(v)
 
728
                else:
 
729
                    raise AssertionError()
843
730
            else:
844
 
                assert l.__class__ in (str, unicode)
845
731
                if isactive is None:
846
732
                    isactive = (not dset) and istack and (istack[-1] in included)
847
733
                if isactive:
855
741
                                   % dset)
856
742
        return result
857
743
 
858
 
    @deprecated_method(zero_eight)
859
 
    def get_iter(self, name_or_index):
860
 
        """Deprecated, please do not use. Lookups are not not needed.
861
 
        
862
 
        Please use get_lines now.
863
 
        """
864
 
        return iter(self.get_lines(self._maybe_lookup(name_or_index)))
865
 
 
866
 
    @deprecated_method(zero_eight)
867
 
    def maybe_lookup(self, name_or_index):
868
 
        """Deprecated, please do not use. Lookups are not not needed."""
869
 
        return self._maybe_lookup(name_or_index)
870
 
 
871
744
    def _maybe_lookup(self, name_or_index):
872
745
        """Convert possible symbolic name to index, or pass through indexes.
873
746
        
878
751
        else:
879
752
            return self._lookup(name_or_index)
880
753
 
881
 
    @deprecated_method(zero_eight)
882
 
    def get(self, version_id):
883
 
        """Please use either Weave.get_text or Weave.get_lines as desired."""
884
 
        return self.get_lines(version_id)
885
 
 
886
754
    def get_lines(self, version_id):
887
755
        """See VersionedFile.get_lines()."""
888
756
        int_index = self._maybe_lookup(version_id)
896
764
                       expected_sha1, measured_sha1))
897
765
        return result
898
766
 
899
 
    def get_sha1(self, version_id):
900
 
        """See VersionedFile.get_sha1()."""
901
 
        return self._sha1s[self._lookup(version_id)]
902
 
 
903
 
    @deprecated_method(zero_eight)
904
 
    def numversions(self):
905
 
        """How many versions are in this weave?
906
 
 
907
 
        Deprecated in favour of num_versions.
908
 
        """
909
 
        return self.num_versions()
 
767
    def get_sha1s(self, version_ids):
 
768
        """See VersionedFile.get_sha1s()."""
 
769
        result = {}
 
770
        for v in version_ids:
 
771
            result[v] = self._sha1s[self._lookup(v)]
 
772
        return result
910
773
 
911
774
    def num_versions(self):
912
775
        """How many versions are in this weave?"""
913
776
        l = len(self._parents)
914
 
        assert l == len(self._sha1s)
915
777
        return l
916
778
 
917
779
    __len__ = num_versions
943
805
            for p in self._parents[i]:
944
806
                new_inc.update(inclusions[self._idx_to_name(p)])
945
807
 
946
 
            assert set(new_inc) == set(self.get_ancestry(name)), \
947
 
                'failed %s != %s' % (set(new_inc), set(self.get_ancestry(name)))
 
808
            if set(new_inc) != set(self.get_ancestry(name)):
 
809
                raise AssertionError(
 
810
                    'failed %s != %s' 
 
811
                    % (set(new_inc), set(self.get_ancestry(name))))
948
812
            inclusions[name] = new_inc
949
813
 
950
814
        nlines = len(self._weave)
980
844
        # no lines outside of insertion blocks, that deletions are
981
845
        # properly paired, etc.
982
846
 
983
 
    def _join(self, other, pb, msg, version_ids, ignore_missing):
984
 
        """Worker routine for join()."""
985
 
        if not other.versions():
986
 
            return          # nothing to update, easy
987
 
 
988
 
        if not version_ids:
989
 
            # versions is never none, InterWeave checks this.
990
 
            return 0
991
 
 
992
 
        # two loops so that we do not change ourselves before verifying it
993
 
        # will be ok
994
 
        # work through in index order to make sure we get all dependencies
995
 
        names_to_join = []
996
 
        processed = 0
997
 
        # get the selected versions only that are in other.versions.
998
 
        version_ids = set(other.versions()).intersection(set(version_ids))
999
 
        # pull in the referenced graph.
1000
 
        version_ids = other.get_ancestry(version_ids)
1001
 
        pending_graph = [(version, other.get_parents(version)) for
1002
 
                         version in version_ids]
1003
 
        for name in topo_sort(pending_graph):
1004
 
            other_idx = other._name_map[name]
1005
 
            # returns True if we have it, False if we need it.
1006
 
            if not self._check_version_consistent(other, other_idx, name):
1007
 
                names_to_join.append((other_idx, name))
1008
 
            processed += 1
1009
 
 
1010
 
 
1011
 
        if pb and not msg:
1012
 
            msg = 'weave join'
1013
 
 
1014
 
        merged = 0
1015
 
        time0 = time.time()
1016
 
        for other_idx, name in names_to_join:
1017
 
            # TODO: If all the parents of the other version are already
1018
 
            # present then we can avoid some work by just taking the delta
1019
 
            # and adjusting the offsets.
1020
 
            new_parents = self._imported_parents(other, other_idx)
1021
 
            sha1 = other._sha1s[other_idx]
1022
 
 
1023
 
            merged += 1
1024
 
 
1025
 
            if pb:
1026
 
                pb.update(msg, merged, len(names_to_join))
1027
 
           
1028
 
            lines = other.get_lines(other_idx)
1029
 
            self._add(name, lines, new_parents, sha1)
1030
 
 
1031
 
        mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
1032
 
                merged, processed, self._weave_name, time.time()-time0))
1033
 
 
1034
847
    def _imported_parents(self, other, other_idx):
1035
848
        """Return list of parents in self corresponding to indexes in other."""
1036
849
        new_parents = []
1071
884
        else:
1072
885
            return False
1073
886
 
1074
 
    @deprecated_method(zero_eight)
1075
 
    def reweave(self, other, pb=None, msg=None):
1076
 
        """reweave has been superseded by plain use of join."""
1077
 
        return self.join(other, pb, msg)
1078
 
 
1079
887
    def _reweave(self, other, pb, msg):
1080
888
        """Reweave self with other - internal helper for join().
1081
889
 
1098
906
 
1099
907
    WEAVE_SUFFIX = '.weave'
1100
908
    
1101
 
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w'):
 
909
    def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
1102
910
        """Create a WeaveFile.
1103
911
        
1104
912
        :param create: If not True, only open an existing knit.
1105
913
        """
1106
 
        super(WeaveFile, self).__init__(name, access_mode)
 
914
        super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
 
915
            allow_reserved=False)
1107
916
        self._transport = transport
1108
917
        self._filemode = filemode
1109
918
        try:
1114
923
            # new file, save it
1115
924
            self._save()
1116
925
 
1117
 
    def _add_lines(self, version_id, parents, lines, parent_texts):
 
926
    def _add_lines(self, version_id, parents, lines, parent_texts,
 
927
        left_matching_blocks, nostore_sha, random_id, check_content):
1118
928
        """Add a version and save the weave."""
 
929
        self.check_not_reserved_id(version_id)
1119
930
        result = super(WeaveFile, self)._add_lines(version_id, parents, lines,
1120
 
                                                   parent_texts)
 
931
            parent_texts, left_matching_blocks, nostore_sha, random_id,
 
932
            check_content)
1121
933
        self._save()
1122
934
        return result
1123
935
 
1124
 
    def _clone_text(self, new_version_id, old_version_id, parents):
1125
 
        """See VersionedFile.clone_text."""
1126
 
        super(WeaveFile, self)._clone_text(new_version_id, old_version_id, parents)
1127
 
        self._save
1128
 
 
1129
936
    def copy_to(self, name, transport):
1130
937
        """See VersionedFile.copy_to()."""
1131
938
        # as we are all in memory always, just serialise to the new place.
1134
941
        sio.seek(0)
1135
942
        transport.put_file(name + WeaveFile.WEAVE_SUFFIX, sio, self._filemode)
1136
943
 
1137
 
    def create_empty(self, name, transport, filemode=None):
1138
 
        return WeaveFile(name, transport, filemode, create=True)
1139
 
 
1140
944
    def _save(self):
1141
945
        """Save the weave."""
1142
946
        self._check_write_ok()
1143
947
        sio = StringIO()
1144
948
        write_weave_v5(self, sio)
1145
949
        sio.seek(0)
1146
 
        self._transport.put_file(self._weave_name + WeaveFile.WEAVE_SUFFIX,
1147
 
                                 sio,
1148
 
                                 self._filemode)
 
950
        bytes = sio.getvalue()
 
951
        path = self._weave_name + WeaveFile.WEAVE_SUFFIX
 
952
        try:
 
953
            self._transport.put_bytes(path, bytes, self._filemode)
 
954
        except errors.NoSuchFile:
 
955
            self._transport.mkdir(dirname(path))
 
956
            self._transport.put_bytes(path, bytes, self._filemode)
1149
957
 
1150
958
    @staticmethod
1151
959
    def get_suffixes():
1152
960
        """See VersionedFile.get_suffixes()."""
1153
961
        return [WeaveFile.WEAVE_SUFFIX]
1154
962
 
 
963
    def insert_record_stream(self, stream):
 
964
        super(WeaveFile, self).insert_record_stream(stream)
 
965
        self._save()
 
966
 
 
967
    @deprecated_method(one_five)
1155
968
    def join(self, other, pb=None, msg=None, version_ids=None,
1156
969
             ignore_missing=False):
1157
970
        """Join other into self and save."""
1159
972
        self._save()
1160
973
 
1161
974
 
1162
 
@deprecated_function(zero_eight)
1163
 
def reweave(wa, wb, pb=None, msg=None):
1164
 
    """reweaving is deprecation, please just use weave.join()."""
1165
 
    _reweave(wa, wb, pb, msg)
1166
 
 
1167
975
def _reweave(wa, wb, pb=None, msg=None):
1168
976
    """Combine two weaves and return the result.
1169
977
 
1426
1234
if __name__ == '__main__':
1427
1235
    import sys
1428
1236
    sys.exit(main(sys.argv))
1429
 
 
1430
 
 
1431
 
class InterWeave(InterVersionedFile):
1432
 
    """Optimised code paths for weave to weave operations."""
1433
 
    
1434
 
    _matching_file_from_factory = staticmethod(WeaveFile)
1435
 
    _matching_file_to_factory = staticmethod(WeaveFile)
1436
 
    
1437
 
    @staticmethod
1438
 
    def is_compatible(source, target):
1439
 
        """Be compatible with weaves."""
1440
 
        try:
1441
 
            return (isinstance(source, Weave) and
1442
 
                    isinstance(target, Weave))
1443
 
        except AttributeError:
1444
 
            return False
1445
 
 
1446
 
    def join(self, pb=None, msg=None, version_ids=None, ignore_missing=False):
1447
 
        """See InterVersionedFile.join."""
1448
 
        version_ids = self._get_source_version_ids(version_ids, ignore_missing)
1449
 
        if self.target.versions() == [] and version_ids is None:
1450
 
            self.target._copy_weave_content(self.source)
1451
 
            return
1452
 
        try:
1453
 
            self.target._join(self.source, pb, msg, version_ids, ignore_missing)
1454
 
        except errors.WeaveParentMismatch:
1455
 
            self.target._reweave(self.source, pb, msg)
1456
 
 
1457
 
 
1458
 
InterVersionedFile.register_optimiser(InterWeave)