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
# TODO: Perhaps have copy method for Weave instances?
27
# XXX: If we do weaves this way, will a merge still behave the same
28
# way if it's done in a different order? That's a pretty desirable
31
# TODO: Nothing here so far assumes the lines are really \n newlines,
32
# rather than being split up in some other way. We could accomodate
33
# binaries, perhaps by naively splitting on \n or perhaps using
34
# something like a rolling checksum.
36
# TODO: End marker for each version so we can stop reading?
38
# TODO: Check that no insertion occurs inside a deletion that was
39
# active in the version of the insertion.
41
# TODO: In addition to the SHA-1 check, perhaps have some code that
42
# checks structural constraints of the weave: ie that insertions are
43
# properly nested, that there is no text outside of an insertion, that
44
# insertions or deletions are not repeated, etc.
46
# TODO: Parallel-extract that passes back each line along with a
47
# description of which revisions include it. Nice for checking all
48
# shas or calculating stats in parallel.
50
# TODO: Using a single _extract routine and then processing the output
51
# is probably inefficient. It's simple enough that we can afford to
52
# have slight specializations for different ways its used: annotate,
53
# basis for add, get, etc.
55
# TODO: Perhaps the API should work only in names to hide the integer
56
# indexes from the user?
58
# TODO: Is there any potential performance win by having an add()
59
# variant that is passed a pre-cooked version of the single basis
65
from difflib import SequenceMatcher
70
class WeaveError(Exception):
71
"""Exception in processing weave"""
74
class WeaveFormatError(WeaveError):
75
"""Weave invariant violated"""
79
"""weave - versioned text file storage.
81
A Weave manages versions of line-based text files, keeping track
82
of the originating version for each line.
84
To clients the "lines" of the file are represented as a list of strings.
85
These strings will typically have terminal newline characters, but
86
this is not required. In particular files commonly do not have a newline
87
at the end of the file.
89
Texts can be identified in either of two ways:
91
* a nonnegative index number.
93
* a version-id string.
95
Typically the index number will be valid only inside this weave and
96
the version-id is used to reference it in the larger world.
98
The weave is represented as a list mixing edit instructions and
99
literal text. Each entry in _weave can be either a string (or
100
unicode), or a tuple. If a string, it means that the given line
101
should be output in the currently active revisions.
103
If a tuple, it gives a processing instruction saying in which
104
revisions the enclosed lines are active. The tuple has the form
105
(instruction, version).
107
The instruction can be '{' or '}' for an insertion block, and '['
108
and ']' for a deletion block respectively. The version is the
109
integer version index. There is no replace operator, only deletes
110
and inserts. For '}', the end of an insertion, there is no
111
version parameter because it always closes the most recently
116
* A later version can delete lines that were introduced by any
117
number of ancestor versions; this implies that deletion
118
instructions can span insertion blocks without regard to the
119
insertion block's nesting.
121
* Similarly, deletions need not be properly nested with regard to
122
each other, because they might have been generated by
123
independent revisions.
125
* Insertions are always made by inserting a new bracketed block
126
into a single point in the previous weave. This implies they
127
can nest but not overlap, and the nesting must always have later
128
insertions on the inside.
130
* It doesn't seem very useful to have an active insertion
131
inside an inactive insertion, but it might happen.
133
* Therefore, all instructions are always"considered"; that
134
is passed onto and off the stack. An outer inactive block
135
doesn't disable an inner block.
137
* Lines are enabled if the most recent enclosing insertion is
138
active and none of the enclosing deletions are active.
140
* There is no point having a deletion directly inside its own
141
insertion; you might as well just not write it. And there
142
should be no way to get an earlier version deleting a later
146
Text of the weave; list of control instruction tuples and strings.
149
List of parents, indexed by version number.
150
It is only necessary to store the minimal set of parents for
151
each version; the parent's parents are implied.
154
List of hex SHA-1 of each version.
157
List of symbolic names for each version. Each should be unique.
160
For each name, the version number.
163
Descriptive name of this weave; typically the filename if known.
167
__slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
170
def __init__(self, weave_name=None):
176
self._weave_name = weave_name
179
def __eq__(self, other):
180
if not isinstance(other, Weave):
182
return self._parents == other._parents \
183
and self._weave == other._weave \
184
and self._sha1s == other._sha1s
187
def __ne__(self, other):
188
return not self.__eq__(other)
191
def maybe_lookup(self, name_or_index):
192
"""Convert possible symbolic name to index, or pass through indexes."""
193
if isinstance(name_or_index, (int, long)):
196
return self.lookup(name_or_index)
199
def lookup(self, name):
200
"""Convert symbolic version name to index."""
202
return self._name_map[name]
204
raise WeaveError("name %r not present in weave %r" %
205
(name, self._weave_name))
208
def idx_to_name(self, version):
209
return self._names[version]
212
def _check_repeated_add(self, name, parents, text, sha1):
213
"""Check that a duplicated add is OK.
215
If it is, return the (old) index; otherwise raise an exception.
217
idx = self.lookup(name)
218
if sorted(self._parents[idx]) != sorted(parents):
219
raise WeaveError("name \"%s\" already present in weave "
220
"with different parents" % name)
221
if sha1 != self._sha1s[idx]:
222
raise WeaveError("name \"%s\" already present in weave "
223
"with different text" % name)
228
def add(self, name, parents, text, sha1=None):
229
"""Add a single text on top of the weave.
231
Returns the index number of the newly added version.
234
Symbolic name for this version.
235
(Typically the revision-id of the revision that added it.)
238
List or set of direct parent version numbers.
241
Sequence of lines to be added in the new version.
243
sha -- SHA-1 of the file, if known. This is trusted to be
246
from bzrlib.osutils import sha_strings
248
assert isinstance(name, basestring)
250
sha1 = sha_strings(text)
251
if name in self._name_map:
252
return self._check_repeated_add(name, parents, text, sha1)
254
parents = map(self.maybe_lookup, parents)
255
self._check_versions(parents)
256
## self._check_lines(text)
257
new_version = len(self._parents)
260
# if we abort after here the (in-memory) weave will be corrupt because only
261
# some fields are updated
262
self._parents.append(parents[:])
263
self._sha1s.append(sha1)
264
self._names.append(name)
265
self._name_map[name] = new_version
269
# special case; adding with no parents revision; can do
270
# this more quickly by just appending unconditionally.
271
# even more specially, if we're adding an empty text we
272
# need do nothing at all.
274
self._weave.append(('{', new_version))
275
self._weave.extend(text)
276
self._weave.append(('}', None))
280
if len(parents) == 1:
281
pv = list(parents)[0]
282
if sha1 == self._sha1s[pv]:
283
# special case: same as the single parent
287
ancestors = self.inclusions(parents)
291
# basis a list of (origin, lineno, line)
294
for origin, lineno, line in self._extract(ancestors):
295
basis_lineno.append(lineno)
296
basis_lines.append(line)
298
# another small special case: a merge, producing the same text
300
if text == basis_lines:
303
# add a sentinal, because we can also match against the final line
304
basis_lineno.append(len(self._weave))
306
# XXX: which line of the weave should we really consider
307
# matches the end of the file? the current code says it's the
308
# last line of the weave?
310
#print 'basis_lines:', basis_lines
311
#print 'new_lines: ', lines
313
s = SequenceMatcher(None, basis_lines, text)
315
# offset gives the number of lines that have been inserted
316
# into the weave up to the current point; if the original edit instruction
317
# says to change line A then we actually change (A+offset)
320
for tag, i1, i2, j1, j2 in s.get_opcodes():
321
# i1,i2 are given in offsets within basis_lines; we need to map them
322
# back to offsets within the entire weave
323
#print 'raw match', tag, i1, i2, j1, j2
327
i1 = basis_lineno[i1]
328
i2 = basis_lineno[i2]
330
assert 0 <= j1 <= j2 <= len(text)
332
#print tag, i1, i2, j1, j2
334
# the deletion and insertion are handled separately.
335
# first delete the region.
337
self._weave.insert(i1+offset, ('[', new_version))
338
self._weave.insert(i2+offset+1, (']', new_version))
342
# there may have been a deletion spanning up to
343
# i2; we want to insert after this region to make sure
344
# we don't destroy ourselves
346
self._weave[i:i] = ([('{', new_version)]
349
offset += 2 + (j2 - j1)
353
def add_identical(self, old_rev_id, new_rev_id, parents):
354
"""Add an identical text to old_rev_id as new_rev_id."""
355
old_lines = self.get(self.lookup(old_rev_id))
356
self.add(new_rev_id, parents, old_lines)
358
def inclusions(self, versions):
359
"""Return set of all ancestors of given version(s)."""
361
for v in xrange(max(versions), 0, -1):
363
# include all its parents
364
i.update(self._parents[v])
366
## except IndexError:
367
## raise ValueError("version %d not present in weave" % v)
370
def parents(self, version):
371
return self._parents[version]
374
def minimal_parents(self, version):
375
"""Find the minimal set of parents for the version."""
376
included = self._parents[version]
381
li.sort(reverse=True)
389
gotit.update(self.inclusions(pv))
391
assert mininc[0] >= 0
392
assert mininc[-1] < version
397
def _check_lines(self, text):
398
if not isinstance(text, list):
399
raise ValueError("text should be a list, not %s" % type(text))
402
if not isinstance(l, basestring):
403
raise ValueError("text line should be a string or unicode, not %s"
408
def _check_versions(self, indexes):
409
"""Check everything in the sequence of indexes is valid"""
414
raise IndexError("invalid version number %r" % i)
417
def annotate(self, name_or_index):
418
return list(self.annotate_iter(name_or_index))
421
def annotate_iter(self, name_or_index):
422
"""Yield list of (index-id, line) pairs for the specified version.
424
The index indicates when the line originated in the weave."""
425
incls = [self.maybe_lookup(name_or_index)]
426
for origin, lineno, text in self._extract(incls):
434
(lineno, insert, deletes, text)
435
for each literal line.
441
lineno = 0 # line of weave, 0-based
443
for l in self._weave:
444
if isinstance(l, tuple):
457
raise WeaveFormatError('unexpected instruction %r'
460
assert isinstance(l, basestring)
462
yield lineno, istack[-1], dset, l
467
def _extract(self, versions):
468
"""Yield annotation of lines in included set.
470
Yields a sequence of tuples (origin, lineno, text), where
471
origin is the origin version, lineno the index in the weave,
472
and text the text of the line.
474
The set typically but not necessarily corresponds to a version.
477
if not isinstance(i, int):
480
included = self.inclusions(versions)
485
lineno = 0 # line of weave, 0-based
491
WFE = WeaveFormatError
493
for l in self._weave:
494
if isinstance(l, tuple):
498
assert v not in istack
512
assert isinstance(l, basestring)
514
isactive = (not dset) and istack and (istack[-1] in included)
516
result.append((istack[-1], lineno, l))
520
raise WFE("unclosed insertion blocks at end of weave",
523
raise WFE("unclosed deletion blocks at end of weave",
530
def get_iter(self, name_or_index):
531
"""Yield lines for the specified version."""
532
incls = [self.maybe_lookup(name_or_index)]
533
for origin, lineno, line in self._extract(incls):
537
def get_text(self, name_or_index):
538
return ''.join(self.get_iter(name_or_index))
539
assert isinstance(version, int)
542
def get_lines(self, name_or_index):
543
return list(self.get_iter(name_or_index))
549
def mash_iter(self, included):
550
"""Return composed version of multiple included versions."""
551
included = map(self.maybe_lookup, included)
552
for origin, lineno, text in self._extract(included):
556
def dump(self, to_file):
557
from pprint import pprint
558
print >>to_file, "Weave._weave = ",
559
pprint(self._weave, to_file)
560
print >>to_file, "Weave._parents = ",
561
pprint(self._parents, to_file)
565
def numversions(self):
566
l = len(self._parents)
567
assert l == len(self._sha1s)
572
return self.numversions()
575
def check(self, progress_bar=None):
576
# check no circular inclusions
577
for version in range(self.numversions()):
578
inclusions = list(self._parents[version])
581
if inclusions[-1] >= version:
582
raise WeaveFormatError("invalid included version %d for index %d"
583
% (inclusions[-1], version))
585
# try extracting all versions; this is a bit slow and parallel
586
# extraction could be used
587
nv = self.numversions()
588
for version in range(nv):
590
progress_bar.update('checking text', version, nv)
592
for l in self.get_iter(version):
595
expected = self._sha1s[version]
597
raise WeaveError("mismatched sha1 for version %d; "
598
"got %s, expected %s"
599
% (version, hd, expected))
601
# TODO: check insertions are properly nested, that there are
602
# no lines outside of insertion blocks, that deletions are
603
# properly paired, etc.
607
def merge(self, merge_versions):
608
"""Automerge and mark conflicts between versions.
610
This returns a sequence, each entry describing alternatives
611
for a chunk of the file. Each of the alternatives is given as
614
If there is a chunk of the file where there's no diagreement,
615
only one alternative is given.
618
# approach: find the included versions common to all the
620
raise NotImplementedError()
624
def _delta(self, included, lines):
625
"""Return changes from basis to new revision.
627
The old text for comparison is the union of included revisions.
629
This is used in inserting a new text.
631
Delta is returned as a sequence of
632
(weave1, weave2, newlines).
634
This indicates that weave1:weave2 of the old weave should be
635
replaced by the sequence of lines in newlines. Note that
636
these line numbers are positions in the total weave and don't
637
correspond to the lines in any extracted version, or even the
638
extracted union of included versions.
640
If line1=line2, this is a pure insert; if newlines=[] this is a
641
pure delete. (Similar to difflib.)
646
def plan_merge(self, ver_a, ver_b):
647
"""Return pseudo-annotation indicating how the two versions merge.
649
This is computed between versions a and b and their common
652
Weave lines present in none of them are skipped entirely.
654
inc_a = self.inclusions([ver_a])
655
inc_b = self.inclusions([ver_b])
656
inc_c = inc_a & inc_b
658
for lineno, insert, deleteset, line in self._walk():
659
if deleteset & inc_c:
660
# killed in parent; can't be in either a or b
661
# not relevant to our work
662
yield 'killed-base', line
663
elif insert in inc_c:
664
# was inserted in base
665
killed_a = bool(deleteset & inc_a)
666
killed_b = bool(deleteset & inc_b)
667
if killed_a and killed_b:
668
yield 'killed-both', line
670
yield 'killed-a', line
672
yield 'killed-b', line
674
yield 'unchanged', line
675
elif insert in inc_a:
676
if deleteset & inc_a:
677
yield 'ghost-a', line
681
elif insert in inc_b:
682
if deleteset & inc_b:
683
yield 'ghost-b', line
687
# not in either revision
688
yield 'irrelevant', line
690
yield 'unchanged', '' # terminator
694
def weave_merge(self, plan):
699
for state, line in plan:
700
if state == 'unchanged' or state == 'killed-both':
701
# resync and flush queued conflicts changes if any
702
if not lines_a and not lines_b:
704
elif ch_a and not ch_b:
706
for l in lines_a: yield l
707
elif ch_b and not ch_a:
708
for l in lines_b: yield l
709
elif lines_a == lines_b:
710
for l in lines_a: yield l
713
for l in lines_a: yield l
715
for l in lines_b: yield l
722
if state == 'unchanged':
725
elif state == 'killed-a':
728
elif state == 'killed-b':
731
elif state == 'new-a':
734
elif state == 'new-b':
738
assert state in ('irrelevant', 'ghost-a', 'ghost-b', 'killed-base',
749
"""Show the weave's table-of-contents"""
750
print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
751
for i in (6, 50, 10, 10):
754
for i in range(w.numversions()):
757
parent_str = ' '.join(map(str, w._parents[i]))
758
print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
762
def weave_stats(weave_file, pb):
763
from bzrlib.weavefile import read_weave
765
wf = file(weave_file, 'rb')
767
# FIXME: doesn't work on pipes
768
weave_size = wf.tell()
772
for i in range(vers):
773
pb.update('checking sizes', i, vers)
774
for origin, lineno, line in w._extract([i]):
779
print 'versions %9d' % vers
780
print 'weave file %9d bytes' % weave_size
781
print 'total contents %9d bytes' % total
782
print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
785
print 'average size %9d bytes' % avg
786
print 'relative size %9.2fx' % (float(weave_size) / float(avg))
790
print """bzr weave tool
792
Experimental tool for weave algorithm.
796
Create an empty weave file
797
weave get WEAVEFILE VERSION
798
Write out specified version.
799
weave check WEAVEFILE
800
Check consistency of all versions.
802
Display table of contents.
803
weave add WEAVEFILE NAME [BASE...] < NEWTEXT
804
Add NEWTEXT, with specified parent versions.
805
weave annotate WEAVEFILE VERSION
806
Display origin of each line.
807
weave mash WEAVEFILE VERSION...
808
Display composite of all selected versions.
809
weave merge WEAVEFILE VERSION1 VERSION2 > OUT
810
Auto-merge two versions and display conflicts.
811
weave diff WEAVEFILE VERSION1 VERSION2
812
Show differences between two versions.
816
% weave init foo.weave
818
% weave add foo.weave ver0 < foo.txt
821
(create updated version)
823
% weave get foo.weave 0 | diff -u - foo.txt
824
% weave add foo.weave ver1 0 < foo.txt
827
% weave get foo.weave 0 > foo.txt (create forked version)
829
% weave add foo.weave ver2 0 < foo.txt
832
% weave merge foo.weave 1 2 > foo.txt (merge them)
833
% vi foo.txt (resolve conflicts)
834
% weave add foo.weave merged 1 2 < foo.txt (commit merged version)
846
# in case we're run directly from the subdirectory
847
sys.path.append('..')
849
from bzrlib.weavefile import write_weave, read_weave
850
from bzrlib.progress import ProgressBar
865
return read_weave(file(argv[2], 'rb'))
871
# at the moment, based on everything in the file
873
parents = map(int, argv[4:])
874
lines = sys.stdin.readlines()
875
ver = w.add(name, parents, lines)
876
write_weave(w, file(argv[2], 'wb'))
877
print 'added version %r %d' % (name, ver)
880
if os.path.exists(fn):
881
raise IOError("file exists")
883
write_weave(w, file(fn, 'wb'))
884
elif cmd == 'get': # get one version
886
sys.stdout.writelines(w.get_iter(int(argv[3])))
888
elif cmd == 'mash': # get composite
890
sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
893
from difflib import unified_diff
896
v1, v2 = map(int, argv[3:5])
899
diff_gen = unified_diff(lines1, lines2,
900
'%s version %d' % (fn, v1),
901
'%s version %d' % (fn, v2))
902
sys.stdout.writelines(diff_gen)
904
elif cmd == 'annotate':
906
# newline is added to all lines regardless; too hard to get
907
# reasonable formatting otherwise
909
for origin, text in w.annotate(int(argv[3])):
910
text = text.rstrip('\r\n')
912
print ' | %s' % (text)
914
print '%5d | %s' % (origin, text)
921
weave_stats(argv[2], ProgressBar())
928
print '%d versions ok' % w.numversions()
930
elif cmd == 'inclusions':
932
print ' '.join(map(str, w.inclusions([int(argv[3])])))
934
elif cmd == 'parents':
936
print ' '.join(map(str, w._parents[int(argv[3])]))
938
elif cmd == 'plan-merge':
940
for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
942
print '%14s | %s' % (state, line),
946
p = w.plan_merge(int(argv[3]), int(argv[4]))
947
sys.stdout.writelines(w.weave_merge(p))
949
elif cmd == 'mash-merge':
955
v1, v2 = map(int, argv[3:5])
957
basis = w.inclusions([v1]).intersection(w.inclusions([v2]))
959
base_lines = list(w.mash_iter(basis))
960
a_lines = list(w.get(v1))
961
b_lines = list(w.get(v2))
963
from bzrlib.merge3 import Merge3
964
m3 = Merge3(base_lines, a_lines, b_lines)
966
name_a = 'version %d' % v1
967
name_b = 'version %d' % v2
968
sys.stdout.writelines(m3.merge_lines(name_a=name_a, name_b=name_b))
970
raise ValueError('unknown command %r' % cmd)
974
def profile_main(argv):
975
import tempfile, hotshot, hotshot.stats
977
prof_f = tempfile.NamedTemporaryFile()
979
prof = hotshot.Profile(prof_f.name)
981
ret = prof.runcall(main, argv)
984
stats = hotshot.stats.load(prof_f.name)
986
stats.sort_stats('cumulative')
987
## XXX: Might like to write to stderr or the trace file instead but
988
## print_stats seems hardcoded to stdout
989
stats.print_stats(20)
994
if __name__ == '__main__':
996
if '--profile' in sys.argv:
998
args.remove('--profile')
999
sys.exit(profile_main(args))
1001
sys.exit(main(sys.argv))