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"""
24
# TODO: Perhaps have copy method for Weave instances?
26
# XXX: If we do weaves this way, will a merge still behave the same
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
33
# TODO: Nothing here so far assumes the lines are really \n newlines,
34
# rather than being split up in some other way. We could accomodate
35
# binaries, perhaps by naively splitting on \n or perhaps using
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.
48
# TODO: End marker for each version?
50
# TODO: Check that no insertion occurs inside a deletion that was
51
# active in the version of the insertion.
58
from sets import Set, ImmutableSet
60
frozenset = ImmutableSet
64
class WeaveError(Exception):
65
"""Exception in processing weave"""
68
class WeaveFormatError(WeaveError):
69
"""Weave invariant violated"""
73
"""weave - versioned text file storage.
75
A Weave manages versions of line-based text files, keeping track
76
of the originating version for each line.
78
To clients the "lines" of the file are represented as a list of strings.
79
These strings will typically have terminal newline characters, but
80
this is not required. In particular files commonly do not have a newline
81
at the end of the file.
83
Texts can be identified in either of two ways:
85
* a nonnegative index number.
87
* a version-id string.
89
Typically the index number will be valid only inside this weave and
90
the version-id is used to reference it in the larger world.
92
The weave is represented as a list mixing edit instructions and
93
literal text. Each entry in _l can be either a string (or
94
unicode), or a tuple. If a string, it means that the given line
95
should be output in the currently active revisions.
97
If a tuple, it gives a processing instruction saying in which
98
revisions the enclosed lines are active. The tuple has the form
99
(instruction, version).
101
The instruction can be '{' or '}' for an insertion block, and '['
102
and ']' for a deletion block respectively. The version is the
103
integer version index. There is no replace operator, only deletes
108
* A later version can delete lines that were introduced by any
109
number of ancestor versions; this implies that deletion
110
instructions can span insertion blocks without regard to the
111
insertion block's nesting.
113
* Similarly, deletions need not be properly nested with regard to
114
each other, because they might have been generated by
115
independent revisions.
117
* Insertions are always made by inserting a new bracketed block
118
into a single point in the previous weave. This implies they
119
can nest but not overlap, and the nesting must always have later
120
insertions on the inside.
122
* It doesn't seem very useful to have an active insertion
123
inside an inactive insertion, but it might happen.
125
* Therefore, all instructions are always"considered"; that
126
is passed onto and off the stack. An outer inactive block
127
doesn't disable an inner block.
129
* Lines are enabled if the most recent enclosing insertion is
130
active and none of the enclosing deletions are active.
132
* There is no point having a deletion directly inside its own
133
insertion; you might as well just not write it. And there
134
should be no way to get an earlier version deleting a later
141
List of versions, indexed by index number.
143
For each version we store the set (included_versions), which
144
lists the previous versions also considered active; the
145
versions included in those versions are included transitively.
146
So new versions created from nothing list []; most versions
147
have a single entry; some have more.
155
def __eq__(self, other):
156
if not isinstance(other, Weave):
158
return self._v == other._v \
159
and self._l == other._l
162
def __ne__(self, other):
163
return not self.__eq__(other)
166
def add(self, parents, text):
167
"""Add a single text on top of the weave.
169
Returns the index number of the newly added version.
172
List or set of parent version numbers. This must normally include
173
the parents and the parent's parents, or wierd things might happen.
176
Sequence of lines to be added in the new version."""
177
self._check_versions(parents)
178
self._check_lines(text)
183
delta = self._delta(self.inclusions(parents), text)
185
# offset gives the number of lines that have been inserted
186
# into the weave up to the current point; if the original edit instruction
187
# says to change line A then we actually change (A+offset)
190
for i1, i2, newlines in delta:
193
assert i2 <= len(self._l)
195
# the deletion and insertion are handled separately.
196
# first delete the region.
198
self._l.insert(i1+offset, ('[', idx))
199
self._l.insert(i2+offset+1, (']', idx))
204
# there may have been a deletion spanning up to
205
# i2; we want to insert after this region to make sure
206
# we don't destroy ourselves
208
self._l[i:i] = [('{', idx)] \
211
offset += 2 + len(newlines)
213
# TODO: Could eliminate any parents that are implied by
216
self._addversion(parents)
218
# special case; adding with no parents revision; can do this
219
# more quickly by just appending unconditionally
220
self._l.append(('{', idx))
222
self._l.append(('}', idx))
224
self._addversion(None)
229
def inclusions(self, versions):
230
"""Expand out everything included by versions."""
237
def _addversion(self, parents):
239
self._v.append(frozenset(parents))
241
self._v.append(frozenset())
244
def _check_lines(self, text):
245
if not isinstance(text, list):
246
raise ValueError("text should be a list, not %s" % type(text))
249
if not isinstance(l, basestring):
250
raise ValueError("text line should be a string or unicode, not %s" % type(l))
254
def _check_versions(self, indexes):
255
"""Check everything in the sequence of indexes is valid"""
260
raise IndexError("invalid version number %r" % i)
263
def annotate(self, index):
264
return list(self.annotate_iter(index))
267
def annotate_iter(self, version):
268
"""Yield list of (index-id, line) pairs for the specified version.
270
The index indicates when the line originated in the weave."""
271
included = self.inclusions([version])
272
for origin, lineno, text in self._extract(included):
276
def _extract(self, included):
277
"""Yield annotation of lines in included set.
279
Yields a sequence of tuples (origin, lineno, text), where
280
origin is the origin version, lineno the index in the weave,
281
and text the text of the line.
283
The set typically but not necessarily corresponds to a version.
285
istack = [] # versions for which an insertion block is current
287
dset = set() # versions for which a deletion block is current
291
lineno = 0 # line of weave, 0-based
293
# TODO: Probably only need to put included revisions in the istack
295
# TODO: Could split this into two functions, one that updates
296
# the stack and the other that processes the results -- but
297
# I'm not sure it's really needed.
299
WFE = WeaveFormatError
302
if isinstance(l, tuple):
305
if istack and (istack[-1] >= v):
306
raise WFE("improperly nested insertions %d>=%d on line %d"
307
% (istack[-1], v, lineno))
313
raise WFE("unmatched close of insertion %d on line %d"
316
raise WFE("mismatched close of insertion %d!=%d on line %d"
321
raise WFE("repeated deletion marker for version %d on line %d"
325
raise WFE("version %d deletes own text on line %d"
332
raise WFE("unmatched close of deletion %d on line %d"
335
raise WFE("invalid processing instruction %r on line %d"
338
assert isinstance(l, basestring)
340
raise WFE("literal at top level on line %d"
342
isactive = (istack[-1] in included) \
343
and not included.intersection(dset)
346
yield origin, lineno, l
350
raise WFE("unclosed insertion blocks at end of weave",
353
raise WFE("unclosed deletion blocks at end of weave",
357
def get_iter(self, version):
358
"""Yield lines for the specified version."""
359
for origin, lineno, line in self._extract(self.inclusions([version])):
363
def get(self, index):
364
return list(self.get_iter(index))
367
def merge_iter(self, included):
368
"""Return composed version of multiple included versions."""
369
included = frozenset(included)
370
for origin, lineno, text in self._extract(included):
374
def dump(self, to_file):
375
from pprint import pprint
376
print >>to_file, "Weave._l = ",
377
pprint(self._l, to_file)
378
print >>to_file, "Weave._v = ",
379
pprint(self._v, to_file)
383
for vers_info in self._v:
385
for vi in vers_info[0]:
386
if vi < 0 or vi >= index:
387
raise WeaveFormatError("invalid included version %d for index %d"
390
raise WeaveFormatError("repeated included version %d for index %d"
396
def _delta(self, included, lines):
397
"""Return changes from basis to new revision.
399
The old text for comparison is the union of included revisions.
401
This is used in inserting a new text.
403
Delta is returned as a sequence of
404
(weave1, weave2, newlines).
406
This indicates that weave1:weave2 of the old weave should be
407
replaced by the sequence of lines in newlines. Note that
408
these line numbers are positions in the total weave and don't
409
correspond to the lines in any extracted version, or even the
410
extracted union of included versions.
412
If line1=line2, this is a pure insert; if newlines=[] this is a
413
pure delete. (Similar to difflib.)
416
self._check_versions(included)
418
##from pprint import pprint
420
# first get basis for comparison
421
# basis holds (lineno, origin, line)
427
# basis a list of (origin, lineno, line)
428
basis = list(self._extract(included))
430
# now make a parallel list with only the text, to pass to the differ
431
basis_lines = [line for (origin, lineno, line) in basis]
433
# add a sentinal, because we can also match against the final line
434
basis.append((None, len(self._l), None))
436
# XXX: which line of the weave should we really consider
437
# matches the end of the file? the current code says it's the
438
# last line of the weave?
440
from difflib import SequenceMatcher
441
s = SequenceMatcher(None, basis_lines, lines)
443
##print 'basis sequence:'
446
# TODO: Perhaps return line numbers from composed weave as well?
448
for tag, i1, i2, j1, j2 in s.get_opcodes():
449
##print tag, i1, i2, j1, j2
454
# i1,i2 are given in offsets within basis_lines; we need to map them
455
# back to offsets within the entire weave
456
real_i1 = basis[i1][1]
457
real_i2 = basis[i2][1]
461
assert j2 <= len(lines)
463
yield real_i1, real_i2, lines[j1:j2]
471
from weavefile import write_weave_v1, read_weave_v1
474
w = read_weave_v1(file(argv[2], 'rb'))
475
# at the moment, based on everything in the file
476
parents = set(range(len(w._v)))
477
lines = sys.stdin.readlines()
478
ver = w.add(parents, lines)
479
write_weave_v1(w, file(argv[2], 'wb'))
480
print 'added %d' % ver
483
if os.path.exists(fn):
484
raise IOError("file exists")
486
write_weave_v1(w, file(fn, 'wb'))
488
w = read_weave_v1(file(argv[2], 'rb'))
489
sys.stdout.writelines(w.getiter(int(argv[3])))
490
elif cmd == 'annotate':
491
w = read_weave_v1(file(argv[2], 'rb'))
492
# newline is added to all lines regardless; too hard to get
493
# reasonable formatting otherwise
495
for origin, text in w.annotate(int(argv[3])):
496
text = text.rstrip('\r\n')
498
print ' | %s' % (text)
500
print '%5d | %s' % (origin, text)
503
raise ValueError('unknown command %r' % cmd)
506
if __name__ == '__main__':
508
sys.exit(main(sys.argv))