22
22
"""Weave - storage of related text file versions"""
24
# before intset (r923) 2000 versions in 41.5s
25
# with intset (r926) 2000 versions in 93s !!!
26
# better to just use plain sets.
28
# making _extract build and return a list, rather than being a generator
31
# with python -O, r923 does 2000 versions in 36.87s
33
# with optimizations to avoid mutating lists - 35.75! I guess copying
34
# all the elements every time costs more than the small manipulations.
35
# a surprisingly small change.
37
# r931, which avoids using a generator for extract, does 36.98s
39
# with memoized inclusions, takes 41.49s; not very good
41
# with slots, takes 37.35s; without takes 39.16, a bit surprising
43
# with the delta calculation mixed in with the add method, rather than
44
# separated, takes 36.78s
46
# with delta folded in and mutation of the list, 36.13s
48
# with all this and simplification of add code, 33s
54
24
# TODO: Perhaps have copy method for Weave instances?
56
26
# XXX: If we do weaves this way, will a merge still behave the same
57
27
# way if it's done in a different order? That's a pretty desirable
30
# TODO: How to write these to disk? One option is cPickle, which
31
# would be fast but less friendly to C, and perhaps not portable. Another is
60
33
# TODO: Nothing here so far assumes the lines are really \n newlines,
61
34
# rather than being split up in some other way. We could accomodate
62
35
# binaries, perhaps by naively splitting on \n or perhaps using
63
36
# something like a rolling checksum.
38
# TODO: Perhaps track SHA-1 in the header for protection? This would
39
# be redundant with it being stored in the inventory, but perhaps
42
# TODO: Track version names as well as indexes.
44
# TODO: Probably do transitive expansion when specifying parents?
46
# TODO: Separate out some code to read and write weaves.
65
48
# TODO: End marker for each version so we can stop reading?
67
50
# TODO: Check that no insertion occurs inside a deletion that was
68
51
# active in the version of the insertion.
70
# TODO: In addition to the SHA-1 check, perhaps have some code that
71
# checks structural constraints of the weave: ie that insertions are
72
# properly nested, that there is no text outside of an insertion, that
73
# insertions or deletions are not repeated, etc.
75
# TODO: Parallel-extract that passes back each line along with a
76
# description of which revisions include it. Nice for checking all
79
# TODO: Using a single _extract routine and then processing the output
80
# is probably inefficient. It's simple enough that we can afford to
81
# have slight specializations for different ways its used: annotate,
82
# basis for add, get, etc.
84
# TODO: Perhaps the API should work only in names to hide the integer
85
# indexes from the user?
91
from cStringIO import StringIO
93
from bzrlib.osutils import sha_strings
53
# TODO: Perhaps a special slower check() method that verifies more
54
# nesting constraints and the MD5 of each version?
62
from sets import Set, ImmutableSet
64
frozenset = ImmutableSet
96
68
class WeaveError(Exception):
168
138
should be no way to get an earlier version deleting a later
172
Text of the weave; list of control instruction tuples and strings.
175
List of parents, indexed by version number.
176
It is only necessary to store the minimal set of parents for
177
each version; the parent's parents are implied.
180
List of hex SHA-1 of each version.
183
List of symbolic names for each version. Each should be unique.
186
For each name, the version number.
189
Descriptive name of this weave; typically the filename if known.
145
List of versions, indexed by index number.
147
For each version we store the set (included_versions), which
148
lists the previous versions also considered active; the
149
versions included in those versions are included transitively.
150
So new versions created from nothing list []; most versions
151
have a single entry; some have more.
193
__slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
196
def __init__(self, weave_name=None):
202
self._weave_name = weave_name
205
159
def __eq__(self, other):
206
160
if not isinstance(other, Weave):
208
return self._parents == other._parents \
209
and self._weave == other._weave \
210
and self._sha1s == other._sha1s
162
return self._v == other._v \
163
and self._l == other._l
213
166
def __ne__(self, other):
214
167
return not self.__eq__(other)
217
def maybe_lookup(self, name_or_index):
218
"""Convert possible symbolic name to index, or pass through indexes."""
219
if isinstance(name_or_index, (int, long)):
222
return self.lookup(name_or_index)
225
def lookup(self, name):
226
"""Convert symbolic version name to index."""
228
return self._name_map[name]
230
raise WeaveError("name %r not present in weave %r" %
231
(name, self._weave_name))
234
def idx_to_name(self, version):
235
return self._names[version]
238
def _check_repeated_add(self, name, parents, text):
239
"""Check that a duplicated add is OK.
241
If it is, return the (old) index; otherwise raise an exception.
243
idx = self.lookup(name)
244
if sorted(self._parents[idx]) != sorted(parents):
245
raise WeaveError("name \"%s\" already present in weave "
246
"with different parents" % name)
247
new_sha1 = sha_strings(text)
248
if new_sha1 != self._sha1s[idx]:
249
raise WeaveError("name \"%s\" already present in weave "
250
"with different text" % name)
255
def add(self, name, parents, text):
170
def add(self, parents, text):
256
171
"""Add a single text on top of the weave.
258
173
Returns the index number of the newly added version.
261
Symbolic name for this version.
262
(Typically the revision-id of the revision that added it.)
265
List or set of direct parent version numbers.
176
List or set of parent version numbers. This must normally include
177
the parents and the parent's parents, or wierd things might happen.
268
180
Sequence of lines to be added in the new version."""
270
assert isinstance(name, basestring)
271
if name in self._name_map:
272
return self._check_repeated_add(name, parents, text)
274
parents = map(self.maybe_lookup, parents)
275
self._check_versions(parents)
181
## self._check_versions(parents)
276
182
## self._check_lines(text)
277
new_version = len(self._parents)
279
sha1 = sha_strings(text)
281
# if we abort after here the (in-memory) weave will be corrupt because only
282
# some fields are updated
283
self._parents.append(parents[:])
284
self._sha1s.append(sha1)
285
self._names.append(name)
286
self._name_map[name] = new_version
290
# special case; adding with no parents revision; can do
291
# this more quickly by just appending unconditionally.
292
# even more specially, if we're adding an empty text we
293
# need do nothing at all.
295
self._weave.append(('{', new_version))
296
self._weave.extend(text)
297
self._weave.append(('}', None))
301
if len(parents) == 1:
302
pv = list(parents)[0]
303
if sha1 == self._sha1s[pv]:
304
# special case: same as the single parent
308
ancestors = self.inclusions(parents)
312
# basis a list of (origin, lineno, line)
315
for origin, lineno, line in self._extract(ancestors):
316
basis_lineno.append(lineno)
317
basis_lines.append(line)
319
# another small special case: a merge, producing the same text
321
if text == basis_lines:
324
# add a sentinal, because we can also match against the final line
325
basis_lineno.append(len(self._weave))
327
# XXX: which line of the weave should we really consider
328
# matches the end of the file? the current code says it's the
329
# last line of the weave?
331
#print 'basis_lines:', basis_lines
332
#print 'new_lines: ', lines
334
from difflib import SequenceMatcher
335
s = SequenceMatcher(None, basis_lines, text)
337
# offset gives the number of lines that have been inserted
338
# into the weave up to the current point; if the original edit instruction
339
# says to change line A then we actually change (A+offset)
342
for tag, i1, i2, j1, j2 in s.get_opcodes():
343
# i1,i2 are given in offsets within basis_lines; we need to map them
344
# back to offsets within the entire weave
345
#print 'raw match', tag, i1, i2, j1, j2
349
i1 = basis_lineno[i1]
350
i2 = basis_lineno[i2]
352
assert 0 <= j1 <= j2 <= len(text)
354
#print tag, i1, i2, j1, j2
356
# the deletion and insertion are handled separately.
357
# first delete the region.
359
self._weave.insert(i1+offset, ('[', new_version))
360
self._weave.insert(i2+offset+1, (']', new_version))
364
# there may have been a deletion spanning up to
365
# i2; we want to insert after this region to make sure
366
# we don't destroy ourselves
368
self._weave[i:i] = ([('{', new_version)]
371
offset += 2 + (j2 - j1)
187
delta = self._delta(self.inclusions(parents), text)
189
# offset gives the number of lines that have been inserted
190
# into the weave up to the current point; if the original edit instruction
191
# says to change line A then we actually change (A+offset)
194
for i1, i2, newlines in delta:
197
assert i2 <= len(self._l)
199
# the deletion and insertion are handled separately.
200
# first delete the region.
202
self._l.insert(i1+offset, ('[', idx))
203
self._l.insert(i2+offset+1, (']', idx))
208
# there may have been a deletion spanning up to
209
# i2; we want to insert after this region to make sure
210
# we don't destroy ourselves
212
self._l[i:i] = [('{', idx)] \
215
offset += 2 + len(newlines)
217
self._addversion(parents)
219
# special case; adding with no parents revision; can do this
220
# more quickly by just appending unconditionally
221
self._l.append(('{', idx))
223
self._l.append(('}', idx))
225
self._addversion(None)
376
230
def inclusions(self, versions):
377
"""Return set of all ancestors of given version(s)."""
231
"""Expand out everything included by versions."""
378
232
i = set(versions)
383
# include all its parents
384
i.update(self._parents[v])
388
raise ValueError("version %d not present in weave" % v)
391
def parents(self, version):
392
return self._parents[version]
395
def minimal_parents(self, version):
396
"""Find the minimal set of parents for the version."""
397
included = self._parents[version]
402
li.sort(reverse=True)
410
gotit.update(self.inclusions(pv))
412
assert mininc[0] >= 0
413
assert mininc[-1] < version
238
def _addversion(self, parents):
240
self._v.append(frozenset(parents))
242
self._v.append(frozenset())
418
245
def _check_lines(self, text):
430
256
"""Check everything in the sequence of indexes is valid"""
431
257
for i in indexes:
434
260
except IndexError:
435
261
raise IndexError("invalid version number %r" % i)
438
def annotate(self, name_or_index):
439
return list(self.annotate_iter(name_or_index))
442
def annotate_iter(self, name_or_index):
264
def annotate(self, index):
265
return list(self.annotate_iter(index))
268
def annotate_iter(self, version):
443
269
"""Yield list of (index-id, line) pairs for the specified version.
445
271
The index indicates when the line originated in the weave."""
446
incls = [self.maybe_lookup(name_or_index)]
447
for origin, lineno, text in self._extract(incls):
272
included = self.inclusions([version])
273
for origin, lineno, text in self._extract(included):
448
274
yield origin, text
455
(lineno, insert, deletes, text)
456
for each literal line.
462
lineno = 0 # line of weave, 0-based
464
for l in self._weave:
465
if isinstance(l, tuple):
478
raise WeaveFormatError('unexpected instruction %r'
481
assert isinstance(l, basestring)
483
yield lineno, istack[-1], dset, l
488
def _extract(self, versions):
277
def _extract(self, included):
489
278
"""Yield annotation of lines in included set.
491
280
Yields a sequence of tuples (origin, lineno, text), where
495
284
The set typically but not necessarily corresponds to a version.
498
if not isinstance(i, int):
501
included = self.inclusions(versions)
506
lineno = 0 # line of weave, 0-based
286
istack = [] # versions for which an insertion block is current
288
dset = set() # versions for which a deletion block is current
292
lineno = 0 # line of weave, 0-based
294
# TODO: Probably only need to put included revisions in the istack
296
# TODO: Could split this into two functions, one that updates
297
# the stack and the other that processes the results -- but
298
# I'm not sure it's really needed.
300
# TODO: In fact, I think we only need to store the *count* of
301
# active insertions and deletions, and we can maintain that by
302
# just by just counting as we go along.
512
304
WFE = WeaveFormatError
514
for l in self._weave:
515
307
if isinstance(l, tuple):
308
isactive = None # recalculate
519
assert v not in istack
311
if istack and (istack[-1] >= v):
312
raise WFE("improperly nested insertions %d>=%d on line %d"
313
% (istack[-1], v, lineno))
319
raise WFE("unmatched close of insertion %d on line %d"
322
raise WFE("mismatched close of insertion %d!=%d on line %d"
327
raise WFE("repeated deletion marker for version %d on line %d"
331
raise WFE("version %d deletes own text on line %d"
338
raise WFE("unmatched close of deletion %d on line %d"
341
raise WFE("invalid processing instruction %r on line %d"
533
344
assert isinstance(l, basestring)
535
isactive = (not dset) and istack and (istack[-1] in included)
346
raise WFE("literal at top level on line %d"
349
isactive = (istack[-1] in included) \
350
and not included.intersection(dset)
537
result.append((istack[-1], lineno, l))
353
yield origin, lineno, l
544
360
raise WFE("unclosed deletion blocks at end of weave",
551
def get_iter(self, name_or_index):
364
def get_iter(self, version):
552
365
"""Yield lines for the specified version."""
553
incls = [self.maybe_lookup(name_or_index)]
554
for origin, lineno, line in self._extract(incls):
366
for origin, lineno, line in self._extract(self.inclusions([version])):
558
def get_text(self, version):
559
assert isinstance(version, int)
561
s.writelines(self.get_iter(version))
565
def get(self, name_or_index):
566
return list(self.get_iter(name_or_index))
569
def mash_iter(self, included):
370
def get(self, index):
371
return list(self.get_iter(index))
374
def merge_iter(self, included):
570
375
"""Return composed version of multiple included versions."""
376
included = frozenset(included)
571
377
for origin, lineno, text in self._extract(included):
575
381
def dump(self, to_file):
576
382
from pprint import pprint
577
print >>to_file, "Weave._weave = ",
578
pprint(self._weave, to_file)
579
print >>to_file, "Weave._parents = ",
580
pprint(self._parents, to_file)
584
def numversions(self):
585
l = len(self._parents)
586
assert l == len(self._sha1s)
591
return self.numversions()
594
def check(self, progress_bar=None):
595
# check no circular inclusions
596
for version in range(self.numversions()):
597
inclusions = list(self._parents[version])
600
if inclusions[-1] >= version:
383
print >>to_file, "Weave._l = ",
384
pprint(self._l, to_file)
385
print >>to_file, "Weave._v = ",
386
pprint(self._v, to_file)
390
for vers_info in self._v:
392
for vi in vers_info[0]:
393
if vi < 0 or vi >= index:
601
394
raise WeaveFormatError("invalid included version %d for index %d"
602
% (inclusions[-1], version))
604
# try extracting all versions; this is a bit slow and parallel
605
# extraction could be used
606
nv = self.numversions()
607
for version in range(nv):
609
progress_bar.update('checking text', version, nv)
611
for l in self.get_iter(version):
614
expected = self._sha1s[version]
616
raise WeaveError("mismatched sha1 for version %d; "
617
"got %s, expected %s"
618
% (version, hd, expected))
620
# TODO: check insertions are properly nested, that there are
621
# no lines outside of insertion blocks, that deletions are
622
# properly paired, etc.
626
def merge(self, merge_versions):
627
"""Automerge and mark conflicts between versions.
629
This returns a sequence, each entry describing alternatives
630
for a chunk of the file. Each of the alternatives is given as
633
If there is a chunk of the file where there's no diagreement,
634
only one alternative is given.
637
# approach: find the included versions common to all the
639
raise NotImplementedError()
397
raise WeaveFormatError("repeated included version %d for index %d"
659
419
If line1=line2, this is a pure insert; if newlines=[] this is a
660
420
pure delete. (Similar to difflib.)
665
def plan_merge(self, ver_a, ver_b):
666
"""Return pseudo-annotation indicating how the two versions merge.
668
This is computed between versions a and b and their common
671
Weave lines present in none of them are skipped entirely.
673
inc_a = self.inclusions([ver_a])
674
inc_b = self.inclusions([ver_b])
675
inc_c = inc_a & inc_b
677
for lineno, insert, deleteset, line in self._walk():
678
if deleteset & inc_c:
679
# killed in parent; can't be in either a or b
680
# not relevant to our work
681
yield 'killed-base', line
682
elif insert in inc_c:
683
# was inserted in base
684
killed_a = bool(deleteset & inc_a)
685
killed_b = bool(deleteset & inc_b)
686
if killed_a and killed_b:
687
yield 'killed-both', line
689
yield 'killed-a', line
691
yield 'killed-b', line
693
yield 'unchanged', line
694
elif insert in inc_a:
695
if deleteset & inc_a:
696
yield 'ghost-a', line
700
elif insert in inc_b:
701
if deleteset & inc_b:
702
yield 'ghost-b', line
706
# not in either revision
707
yield 'irrelevant', line
709
yield 'unchanged', '' # terminator
713
def weave_merge(self, plan):
718
for state, line in plan:
719
if state == 'unchanged' or state == 'killed-both':
720
# resync and flush queued conflicts changes if any
721
if not lines_a and not lines_b:
723
elif ch_a and not ch_b:
725
for l in lines_a: yield l
726
elif ch_b and not ch_a:
727
for l in lines_b: yield l
728
elif lines_a == lines_b:
729
for l in lines_a: yield l
732
for l in lines_a: yield l
734
for l in lines_b: yield l
741
if state == 'unchanged':
744
elif state == 'killed-a':
747
elif state == 'killed-b':
750
elif state == 'new-a':
753
elif state == 'new-b':
757
assert state in ('irrelevant', 'ghost-a', 'ghost-b', 'killed-base',
768
"""Show the weave's table-of-contents"""
769
print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
770
for i in (6, 50, 10, 10):
773
for i in range(w.numversions()):
776
parent_str = ' '.join(map(str, w._parents[i]))
777
print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
781
def weave_stats(weave_file):
782
from bzrlib.progress import ProgressBar
783
from bzrlib.weavefile import read_weave
787
wf = file(weave_file, 'rb')
789
# FIXME: doesn't work on pipes
790
weave_size = wf.tell()
794
for i in range(vers):
795
pb.update('checking sizes', i, vers)
796
for line in w.get_iter(i):
801
print 'versions %9d' % vers
802
print 'weave file %9d bytes' % weave_size
803
print 'total contents %9d bytes' % total
804
print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
807
print 'average size %9d bytes' % avg
808
print 'relative size %9.2fx' % (float(weave_size) / float(avg))
812
print """bzr weave tool
814
Experimental tool for weave algorithm.
818
Create an empty weave file
819
weave get WEAVEFILE VERSION
820
Write out specified version.
821
weave check WEAVEFILE
822
Check consistency of all versions.
824
Display table of contents.
825
weave add WEAVEFILE NAME [BASE...] < NEWTEXT
826
Add NEWTEXT, with specified parent versions.
827
weave annotate WEAVEFILE VERSION
828
Display origin of each line.
829
weave mash WEAVEFILE VERSION...
830
Display composite of all selected versions.
831
weave merge WEAVEFILE VERSION1 VERSION2 > OUT
832
Auto-merge two versions and display conflicts.
836
% weave init foo.weave
838
% weave add foo.weave ver0 < foo.txt
841
(create updated version)
843
% weave get foo.weave 0 | diff -u - foo.txt
844
% weave add foo.weave ver1 0 < foo.txt
847
% weave get foo.weave 0 > foo.txt (create forked version)
849
% weave add foo.weave ver2 0 < foo.txt
852
% weave merge foo.weave 1 2 > foo.txt (merge them)
853
% vi foo.txt (resolve conflicts)
854
% weave add foo.weave merged 1 2 < foo.txt (commit merged version)
422
# basis a list of (origin, lineno, line)
425
for origin, lineno, line in self._extract(included):
426
basis_lineno.append(lineno)
427
basis_lines.append(line)
429
# add a sentinal, because we can also match against the final line
430
basis_lineno.append(len(self._l))
432
# XXX: which line of the weave should we really consider
433
# matches the end of the file? the current code says it's the
434
# last line of the weave?
436
from difflib import SequenceMatcher
437
s = SequenceMatcher(None, basis_lines, lines)
439
# TODO: Perhaps return line numbers from composed weave as well?
441
for tag, i1, i2, j1, j2 in s.get_opcodes():
442
##print tag, i1, i2, j1, j2
447
# i1,i2 are given in offsets within basis_lines; we need to map them
448
# back to offsets within the entire weave
449
real_i1 = basis_lineno[i1]
450
real_i2 = basis_lineno[i2]
454
assert j2 <= len(lines)
456
yield real_i1, real_i2, lines[j1:j2]
863
from weavefile import write_weave, read_weave
864
from bzrlib.progress import ProgressBar
464
from weavefile import write_weave_v1, read_weave_v1
879
return read_weave(file(argv[2], 'rb'))
467
w = read_weave_v1(file(argv[2], 'rb'))
885
468
# at the moment, based on everything in the file
887
parents = map(int, argv[4:])
469
parents = set(range(len(w._v)))
888
470
lines = sys.stdin.readlines()
889
ver = w.add(name, parents, lines)
890
write_weave(w, file(argv[2], 'wb'))
891
print 'added version %r %d' % (name, ver)
471
ver = w.add(parents, lines)
472
write_weave_v1(w, file(argv[2], 'wb'))
473
print 'added %d' % ver
892
474
elif cmd == 'init':
894
476
if os.path.exists(fn):
895
477
raise IOError("file exists")
897
write_weave(w, file(fn, 'wb'))
898
elif cmd == 'get': # get one version
900
sys.stdout.writelines(w.get_iter(int(argv[3])))
902
elif cmd == 'mash': # get composite
904
sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
479
write_weave_v1(w, file(fn, 'wb'))
481
w = read_weave_v1(file(argv[2], 'rb'))
482
sys.stdout.writelines(w.getiter(int(argv[3])))
906
483
elif cmd == 'annotate':
484
w = read_weave_v1(file(argv[2], 'rb'))
908
485
# newline is added to all lines regardless; too hard to get
909
486
# reasonable formatting otherwise
916
493
print '%5d | %s' % (origin, text)
930
print '%d versions ok' % w.numversions()
932
elif cmd == 'inclusions':
934
print ' '.join(map(str, w.inclusions([int(argv[3])])))
936
elif cmd == 'parents':
938
print ' '.join(map(str, w._parents[int(argv[3])]))
940
elif cmd == 'plan-merge':
942
for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
944
print '%14s | %s' % (state, line),
948
p = w.plan_merge(int(argv[3]), int(argv[4]))
949
sys.stdout.writelines(w.weave_merge(p))
951
elif cmd == 'mash-merge':
957
v1, v2 = map(int, argv[3:5])
959
basis = w.inclusions([v1]).intersection(w.inclusions([v2]))
961
base_lines = list(w.mash_iter(basis))
962
a_lines = list(w.get(v1))
963
b_lines = list(w.get(v2))
965
from bzrlib.merge3 import Merge3
966
m3 = Merge3(base_lines, a_lines, b_lines)
968
name_a = 'version %d' % v1
969
name_b = 'version %d' % v2
970
sys.stdout.writelines(m3.merge_lines(name_a=name_a, name_b=name_b))
972
496
raise ValueError('unknown command %r' % cmd)
976
def profile_main(argv):
977
import tempfile, hotshot, hotshot.stats
979
prof_f = tempfile.NamedTemporaryFile()
981
prof = hotshot.Profile(prof_f.name)
983
ret = prof.runcall(main, argv)
986
stats = hotshot.stats.load(prof_f.name)
988
stats.sort_stats('cumulative')
989
## XXX: Might like to write to stderr or the trace file instead but
990
## print_stats seems hardcoded to stdout
991
stats.print_stats(20)
996
499
if __name__ == '__main__':
998
if '--profile' in sys.argv:
1000
args.remove('--profile')
1001
sys.exit(profile_main(args))
1003
sys.exit(main(sys.argv))
501
sys.exit(main(sys.argv))