3
3
# Copyright (C) 2005 Canonical Ltd
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.
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.
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
66
66
# be done fairly efficiently because the sequence numbers constrain
67
67
# the possible relationships.
69
# FIXME: the conflict markers should be *7* characters
72
70
from cStringIO import StringIO
71
from difflib import SequenceMatcher
76
from bzrlib.trace import mutter
81
77
from bzrlib.errors import (WeaveError, WeaveFormatError, WeaveParentMismatch,
82
78
RevisionAlreadyPresent,
83
79
RevisionNotPresent,
84
UnavailableRepresentation,
85
80
WeaveRevisionAlreadyPresent,
86
81
WeaveRevisionNotPresent,
88
83
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
84
from bzrlib.osutils import sha_strings
92
85
from bzrlib.symbol_versioning import *
93
from bzrlib.trace import mutter
94
86
from bzrlib.tsort import topo_sort
95
from bzrlib.versionedfile import (
87
from bzrlib.versionedfile import VersionedFile, InterVersionedFile
101
88
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])[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'
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
91
class Weave(VersionedFile):
128
92
"""weave - versioned text file storage.
216
180
__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)
183
def __init__(self, weave_name=None):
229
185
self._parents = []
232
188
self._name_map = {}
233
189
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
245
191
def __repr__(self):
246
192
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
195
"""Return a deep copy of self.
275
214
def __ne__(self, other):
276
215
return not self.__eq__(other)
217
@deprecated_method(zero_eight)
218
def idx_to_name(self, index):
219
"""Old public interface, the public interface is all names now."""
278
222
def _idx_to_name(self, version):
279
223
return self._names[version]
225
@deprecated_method(zero_eight)
226
def lookup(self, name):
227
"""Backwards compatability thunk:
229
Return name, as name is valid in the api now, and spew deprecation
281
234
def _lookup(self, name):
282
235
"""Convert symbolic version name to index."""
283
if not self._allow_reserved:
284
self.check_not_reserved_id(name)
286
237
return self._name_map[name]
288
239
raise RevisionNotPresent(name, self._weave_name)
241
@deprecated_method(zero_eight)
242
def iter_names(self):
243
"""Deprecated convenience function, please see VersionedFile.names()."""
244
return iter(self.names())
246
@deprecated_method(zero_eight)
248
"""See Weave.versions for the current api."""
249
return self.versions()
290
251
def versions(self):
291
252
"""See VersionedFile.versions."""
292
253
return self._names[:]
294
255
def has_version(self, version_id):
295
256
"""See VersionedFile.has_version."""
296
return (version_id in self._name_map)
257
return self._name_map.has_key(version_id)
298
259
__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:
261
def get_parents(self, version_id):
262
"""See VersionedFile.get_parent."""
263
return map(self._idx_to_name, self._parents[self._lookup(version_id)])
376
265
def _check_repeated_add(self, name, parents, text, sha1):
377
266
"""Check that a duplicated add is OK.
384
273
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):
276
@deprecated_method(zero_eight)
277
def add_identical(self, old_rev_id, new_rev_id, parents):
278
"""Please use Weave.clone_text now."""
279
return self.clone_text(new_rev_id, old_rev_id, parents)
281
def add_lines(self, version_id, parents, lines):
389
282
"""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):
283
return self._add(version_id, lines, map(self._lookup, parents))
285
@deprecated_method(zero_eight)
286
def add(self, name, parents, text, sha1=None):
287
"""See VersionedFile.add_lines for the non deprecated api."""
288
return self._add(name, text, map(self._maybe_lookup, parents), sha1)
290
def _add(self, version_id, lines, parents, sha1=None):
395
291
"""Add a single text on top of the weave.
397
293
Returns the index number of the newly added version.
521
422
## except IndexError:
522
423
## raise ValueError("version %d not present in weave" % v)
524
def get_ancestry(self, version_ids, topo_sorted=True):
425
@deprecated_method(zero_eight)
426
def inclusions(self, version_ids):
427
"""Deprecated - see VersionedFile.get_ancestry for the replacement."""
430
if isinstance(version_ids[0], int):
431
return [self._idx_to_name(v) for v in self._inclusions(version_ids)]
433
return self.get_ancestry(version_ids)
435
def get_ancestry(self, version_ids):
525
436
"""See VersionedFile.get_ancestry."""
526
437
if isinstance(version_ids, basestring):
527
438
version_ids = [version_ids]
556
467
return len(other_parents.difference(my_parents)) == 0
558
469
def annotate(self, version_id):
559
"""Return a list of (version-id, line) tuples for version_id.
470
if isinstance(version_id, int):
471
warn('Weave.annotate(int) is deprecated. Please use version names'
472
' in all circumstances as of 0.8',
477
for origin, lineno, text in self._extract([version_id]):
478
result.append((origin, text))
481
return super(Weave, self).annotate(version_id)
483
def annotate_iter(self, version_id):
484
"""Yield list of (version-id, line) pairs for the specified version.
561
486
The index indicates when the line originated in the weave."""
562
487
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."""
488
for origin, lineno, text in self._extract(incls):
489
yield self._idx_to_name(origin), text
491
@deprecated_method(zero_eight)
493
"""_walk has become walk, a supported api."""
496
def walk(self, version_ids=None):
497
"""See VersionedFile.walk."""
612
529
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
532
def _extract(self, versions):
660
533
"""Yield annotation of lines in included set.
684
556
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
558
for l in self._weave:
714
if l.__class__ == tuple:
559
if isinstance(l, tuple):
563
assert v not in istack
721
iset.remove(istack.pop())
723
568
if v in included:
726
573
if v in included:
729
raise AssertionError()
577
assert isinstance(l, basestring)
731
578
if isactive is None:
732
579
isactive = (not dset) and istack and (istack[-1] in included)
752
612
return self._lookup(name_or_index)
614
def _get_iter(self, version_id):
615
"""Yield lines for the specified version."""
616
incls = [self._maybe_lookup(version_id)]
621
# We don't have sha1 sums for multiple entries
623
for origin, lineno, line in self._extract(incls):
628
expected_sha1 = self._sha1s[index]
629
measured_sha1 = cur_sha.hexdigest()
630
if measured_sha1 != expected_sha1:
631
raise errors.WeaveInvalidChecksum(
632
'file %s, revision %s, expected: %s, measured %s'
633
% (self._weave_name, self._names[index],
634
expected_sha1, measured_sha1))
636
@deprecated_method(zero_eight)
637
def get(self, version_id):
638
"""Please use either Weave.get_text or Weave.get_lines as desired."""
639
return self.get_lines(version_id)
754
641
def get_lines(self, version_id):
755
642
"""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()."""
770
for v in version_ids:
771
result[v] = self._sha1s[self._lookup(v)]
643
return list(self._get_iter(version_id))
645
def get_sha1(self, name):
646
"""Get the stored sha1 sum for the given revision.
648
:param name: The name of the version to lookup
650
return self._sha1s[self._lookup(name)]
652
@deprecated_method(zero_eight)
653
def numversions(self):
654
"""How many versions are in this weave?
656
Deprecated in favour of num_versions.
658
return self.num_versions()
774
660
def num_versions(self):
775
661
"""How many versions are in this weave?"""
776
662
l = len(self._parents)
663
assert l == len(self._sha1s)
779
666
__len__ = num_versions
781
668
def check(self, progress_bar=None):
782
669
# TODO evaluate performance hit of using string sets in this routine.
783
# TODO: check no circular inclusions
784
# TODO: create a nested progress bar
670
# check no circular inclusions
785
671
for version in range(self.num_versions()):
786
672
inclusions = list(self._parents[version])
844
728
# no lines outside of insertion blocks, that deletions are
845
729
# properly paired, etc.
731
def _join(self, other, pb, msg, version_ids):
732
"""Worker routine for join()."""
733
if not other.versions():
734
return # nothing to update, easy
737
for version_id in version_ids:
738
if not self.has_version(version_id):
739
raise RevisionNotPresent(version_id, self._weave_name)
740
assert version_ids == None
742
# two loops so that we do not change ourselves before verifying it
744
# work through in index order to make sure we get all dependencies
747
for other_idx, name in enumerate(other._names):
748
self._check_version_consistent(other, other_idx, name)
749
sha1 = other._sha1s[other_idx]
753
if name in self._name_map:
754
idx = self._lookup(name)
755
n1 = set(map(other._idx_to_name, other._parents[other_idx]))
756
n2 = set(map(self._idx_to_name, self._parents[idx]))
757
if sha1 == self._sha1s[idx] and n1 == n2:
760
names_to_join.append((other_idx, name))
767
for other_idx, name in names_to_join:
768
# TODO: If all the parents of the other version are already
769
# present then we can avoid some work by just taking the delta
770
# and adjusting the offsets.
771
new_parents = self._imported_parents(other, other_idx)
772
sha1 = other._sha1s[other_idx]
777
pb.update(msg, merged, len(names_to_join))
779
lines = other.get_lines(other_idx)
780
self._add(name, lines, new_parents, sha1)
782
mutter("merged = %d, processed = %d, file_id=%s; deltat=%d"%(
783
merged, processed, self._weave_name, time.time()-time0))
847
785
def _imported_parents(self, other, other_idx):
848
786
"""Return list of parents in self corresponding to indexes in other."""
850
788
for parent_idx in other._parents[other_idx]:
851
789
parent_name = other._names[parent_idx]
852
if parent_name not in self._name_map:
790
if parent_name not in self._names:
853
791
# should not be possible
854
792
raise WeaveError("missing parent {%s} of {%s} in %r"
855
793
% (parent_name, other._name_map[other_idx], self))
907
846
WEAVE_SUFFIX = '.weave'
909
def __init__(self, name, transport, filemode=None, create=False, access_mode='w', get_scope=None):
848
def __init__(self, name, transport, mode=None, create=False):
910
849
"""Create a WeaveFile.
912
851
:param create: If not True, only open an existing knit.
914
super(WeaveFile, self).__init__(name, access_mode, get_scope=get_scope,
915
allow_reserved=False)
853
super(WeaveFile, self).__init__(name)
916
854
self._transport = transport
917
self._filemode = filemode
919
857
_read_weave_v5(self._transport.get(name + WeaveFile.WEAVE_SUFFIX), self)
920
858
except errors.NoSuchFile:
923
861
# new file, save it
926
def _add_lines(self, version_id, parents, lines, parent_texts,
927
left_matching_blocks, nostore_sha, random_id, check_content):
864
def add_lines(self, version_id, parents, lines):
928
865
"""Add a version and save the weave."""
929
self.check_not_reserved_id(version_id)
930
result = super(WeaveFile, self)._add_lines(version_id, parents, lines,
931
parent_texts, left_matching_blocks, nostore_sha, random_id,
866
super(WeaveFile, self).add_lines(version_id, parents, lines)
936
869
def copy_to(self, name, transport):
937
870
"""See VersionedFile.copy_to()."""
940
873
write_weave_v5(self, sio)
942
transport.put_file(name + WeaveFile.WEAVE_SUFFIX, sio, self._filemode)
875
transport.put(name + WeaveFile.WEAVE_SUFFIX, sio, self._mode)
877
def create_empty(self, name, transport, mode=None):
878
return WeaveFile(name, transport, mode, create=True)
945
881
"""Save the weave."""
946
self._check_write_ok()
948
883
write_weave_v5(self, sio)
950
bytes = sio.getvalue()
951
path = self._weave_name + WeaveFile.WEAVE_SUFFIX
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)
885
self._transport.put(self._weave_name + WeaveFile.WEAVE_SUFFIX,
959
890
def get_suffixes():
960
891
"""See VersionedFile.get_suffixes()."""
961
892
return [WeaveFile.WEAVE_SUFFIX]
963
def insert_record_stream(self, stream):
964
super(WeaveFile, self).insert_record_stream(stream)
967
@deprecated_method(one_five)
968
def join(self, other, pb=None, msg=None, version_ids=None,
969
ignore_missing=False):
894
def join(self, other, pb=None, msg=None, version_ids=None):
970
895
"""Join other into self and save."""
971
super(WeaveFile, self).join(other, pb, msg, version_ids, ignore_missing)
896
super(WeaveFile, self).join(other, pb, msg, version_ids)
900
@deprecated_function(zero_eight)
901
def reweave(wa, wb, pb=None, msg=None):
902
"""reweaving is deprecation, please just use weave.join()."""
903
_reweave(wa, wb, pb, msg)
975
905
def _reweave(wa, wb, pb=None, msg=None):
976
906
"""Combine two weaves and return the result.
1217
1148
print ' '.join(map(str, w._parents[int(argv[3])]))
1219
1150
elif cmd == 'plan-merge':
1220
# replaced by 'bzr weave-plan-merge'
1222
1152
for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
1224
1154
print '%14s | %s' % (state, line),
1225
1156
elif cmd == 'merge':
1226
# replaced by 'bzr weave-merge-text'
1228
1158
p = w.plan_merge(int(argv[3]), int(argv[4]))
1229
1159
sys.stdout.writelines(w.weave_merge(p))
1231
1162
raise ValueError('unknown command %r' % cmd)
1166
def profile_main(argv):
1167
import tempfile, hotshot, hotshot.stats
1169
prof_f = tempfile.NamedTemporaryFile()
1171
prof = hotshot.Profile(prof_f.name)
1173
ret = prof.runcall(main, argv)
1176
stats = hotshot.stats.load(prof_f.name)
1178
stats.sort_stats('cumulative')
1179
## XXX: Might like to write to stderr or the trace file instead but
1180
## print_stats seems hardcoded to stdout
1181
stats.print_stats(20)
1186
def lsprofile_main(argv):
1187
from bzrlib.lsprof import profile
1188
ret,stats = profile(main, argv)
1234
1194
if __name__ == '__main__':
1236
sys.exit(main(sys.argv))
1196
if '--profile' in sys.argv:
1198
args.remove('--profile')
1199
sys.exit(profile_main(args))
1200
elif '--lsprof' in sys.argv:
1202
args.remove('--lsprof')
1203
sys.exit(lsprofile_main(args))
1205
sys.exit(main(sys.argv))
1208
class InterWeave(InterVersionedFile):
1209
"""Optimised code paths for weave to weave operations."""
1211
_matching_file_factory = staticmethod(WeaveFile)
1214
def is_compatible(source, target):
1215
"""Be compatible with weaves."""
1217
return (isinstance(source, Weave) and
1218
isinstance(target, Weave))
1219
except AttributeError:
1222
def join(self, pb=None, msg=None, version_ids=None):
1223
"""See InterVersionedFile.join."""
1225
self.target._join(self.source, pb, msg, version_ids)
1226
except errors.WeaveParentMismatch:
1227
self.target._reweave(self.source, pb, msg)
1230
InterVersionedFile.register_optimiser(InterWeave)