/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.1.1 by Martin Pool
Check in old existing knit code.
1
#! /usr/bin/python
2
3
# Copyright (C) 2005 Canonical Ltd
4
0.1.33 by Martin Pool
add gpl text
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.
9
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.
14
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
0.1.1 by Martin Pool
Check in old existing knit code.
18
19
# Author: Martin Pool <mbp@canonical.com>
20
21
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
22
"""Weave - storage of related text file versions"""
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
23
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
24
# TODO: Perhaps have copy and comparison methods of Weave instances?
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
25
0.1.34 by Martin Pool
remove dead code
26
0.1.17 by Martin Pool
Use objects rather than tuples for tracking VerInfo for
27
class VerInfo(object):
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
28
    """Information about a version in a Weave."""
0.1.17 by Martin Pool
Use objects rather than tuples for tracking VerInfo for
29
    included = frozenset()
30
    def __init__(self, included=None):
31
        if included:
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
32
            self.included = frozenset(included)
0.1.17 by Martin Pool
Use objects rather than tuples for tracking VerInfo for
33
0.1.18 by Martin Pool
Better Knit.dump method
34
    def __repr__(self):
35
        s = self.__class__.__name__ + '('
36
        if self.included:
37
            s += 'included=%r' % (list(self.included))
38
        s += ')'
39
        return s
40
0.1.17 by Martin Pool
Use objects rather than tuples for tracking VerInfo for
41
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
42
class WeaveError(Exception):
43
    """Exception in processing weave"""
44
45
46
class WeaveFormatError(WeaveError):
47
    """Weave invariant violated"""
48
    
49
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
50
class Weave(object):
51
    """weave - versioned text file storage.
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
52
    
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
53
    A Weave manages versions of line-based text files, keeping track of the
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
54
    originating version for each line.
55
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
56
    Texts can be identified in either of two ways:
57
58
    * a nonnegative index number.
59
60
    * a version-id string.
61
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
62
    Typically the index number will be valid only inside this weave and
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
63
    the version-id is used to reference it in the larger world.
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
64
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
65
    The weave is represented as a list mixing edit instructions and
66
    literal text.  Each entry in _l can be either a string (or
67
    unicode), or a tuple.  If a string, it means that the given line
68
    should be output in the currently active revisions.
69
70
    If a tuple, it gives a processing instruction saying in which
71
    revisions the enclosed lines are active.  The tuple has the form
72
    (instruction, version).
73
74
    The instruction can be '{' or '}' for an insertion block, and '['
75
    and ']' for a deletion block respectively.  The version is the
0.1.45 by Martin Pool
doc
76
    integer version index.  There is no replace operator, only deletes
77
    and inserts.
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
78
0.1.41 by Martin Pool
Doc
79
    Constraints/notes:
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
80
81
    * A later version can delete lines that were introduced by any
82
      number of ancestor versions; this implies that deletion
83
      instructions can span insertion blocks without regard to the
84
      insertion block's nesting.
85
0.1.41 by Martin Pool
Doc
86
    * Similarly, deletions need not be properly nested with regard to
87
      each other, because they might have been generated by
88
      independent revisions.
89
0.1.45 by Martin Pool
doc
90
    * Insertions are always made by inserting a new bracketed block
91
      into a single point in the previous weave.  This implies they
92
      can nest but not overlap, and the nesting must always have later
93
      insertions on the inside.
94
0.1.41 by Martin Pool
Doc
95
    * It doesn't seem very useful to have an active insertion
96
      inside an inactive insertion, but it might happen.
0.1.45 by Martin Pool
doc
97
      
0.1.41 by Martin Pool
Doc
98
    * Therefore, all instructions are always"considered"; that
99
      is passed onto and off the stack.  An outer inactive block
100
      doesn't disable an inner block.
101
102
    * Lines are enabled if the most recent enclosing insertion is
103
      active and none of the enclosing deletions are active.
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
104
0.1.49 by Martin Pool
Add another constraint: revisions should not delete text that they
105
    * There is no point having a deletion directly inside its own
106
      insertion; you might as well just not write it.  And there
107
      should be no way to get an earlier version deleting a later
108
      version.
109
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
110
    _l
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
111
        Text of the weave. 
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
112
113
    _v
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
114
        List of versions, indexed by index number.
115
116
        For each version we store the tuple (included_versions), which
117
        lists the previous versions also considered active.
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
118
    """
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
119
    def __init__(self):
120
        self._l = []
121
        self._v = []
0.1.5 by Martin Pool
Add test for storing two text versions.
122
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
123
        
0.1.26 by Martin Pool
Refactor parameters to add command
124
    def add(self, parents, text):
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
125
        """Add a single text on top of the weave.
0.1.36 by Martin Pool
doc
126
  
0.1.26 by Martin Pool
Refactor parameters to add command
127
        Returns the index number of the newly added version.
128
129
        parents
130
            List or set of parent version numbers.
131
132
        text
133
            Sequence of lines to be added in the new version."""
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
134
        self._check_versions(parents)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
135
        self._check_lines(text)
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
136
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
137
        idx = len(self._v)
0.1.5 by Martin Pool
Add test for storing two text versions.
138
0.1.26 by Martin Pool
Refactor parameters to add command
139
        if parents:
140
            parents = frozenset(parents)
141
            delta = self._delta(parents, text)
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
142
0.1.31 by Martin Pool
Fix insertion of multiple regions, calculating the right line offset as we go.
143
            # offset gives the number of lines that have been inserted
144
            # into the weave up to the current point; if the original edit instruction
145
            # says to change line A then we actually change (A+offset)
146
            offset = 0
147
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
148
            for i1, i2, newlines in delta:
0.1.29 by Martin Pool
Better internal error
149
                assert 0 <= i1
150
                assert i1 <= i2
151
                assert i2 <= len(self._l)
152
                
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
153
                if i1 != i2:
0.1.29 by Martin Pool
Better internal error
154
                    raise NotImplementedError("can't handle replacing weave [%d:%d] yet"
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
155
                                              % (i1, i2))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
156
157
                self._l.insert(i1 + offset, ('{', idx))
158
                i = i1 + offset + 1
159
                self._l[i:i] = newlines
160
                self._l.insert(i + 1, ('}', idx))
161
                offset += 2 + len(newlines)
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
162
0.1.26 by Martin Pool
Refactor parameters to add command
163
            self._v.append(VerInfo(parents))
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
164
        else:
0.1.26 by Martin Pool
Refactor parameters to add command
165
            # special case; adding with no parents revision; can do this
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
166
            # more quickly by just appending unconditionally
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
167
            self._l.append(('{', idx))
168
            self._l += text
169
            self._l.append(('}', idx))
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
170
171
            self._v.append(VerInfo())
172
            
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
173
        return idx
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
174
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
175
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
176
    def _check_lines(self, text):
177
        if not isinstance(text, list):
178
            raise ValueError("text should be a list, not %s" % type(text))
179
180
        for l in text:
181
            if not isinstance(l, basestring):
182
                raise ValueError("text line should be a string or unicode, not %s" % type(l))
183
        
184
185
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
186
    def _check_versions(self, indexes):
187
        """Check everything in the sequence of indexes is valid"""
188
        for i in indexes:
189
            try:
190
                self._v[i]
191
            except IndexError:
192
                raise IndexError("invalid version number %r" % i)
193
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
194
    
0.1.7 by Martin Pool
Add trivial annotate text
195
    def annotate(self, index):
196
        return list(self.annotate_iter(index))
197
198
199
    def annotate_iter(self, index):
200
        """Yield list of (index-id, line) pairs for the specified version.
201
202
        The index indicates when the line originated in the weave."""
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
203
        try:
204
            vi = self._v[index]
205
        except IndexError:
206
            raise IndexError('version index %d out of range' % index)
0.1.20 by Martin Pool
Factor out Knit.extract() method
207
        included = set(vi.included)
208
        included.add(index)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
209
        for origin, lineno, text in self._extract(included):
210
            yield origin, text
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
211
212
213
    def _extract(self, included):
0.1.20 by Martin Pool
Factor out Knit.extract() method
214
        """Yield annotation of lines in included set.
215
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
216
        Yields a sequence of tuples (origin, lineno, text), where
217
        origin is the origin version, lineno the index in the weave,
218
        and text the text of the line.
219
0.1.20 by Martin Pool
Factor out Knit.extract() method
220
        The set typically but not necessarily corresponds to a version.
221
        """
0.1.48 by Martin Pool
Basic parsing of delete instructions.
222
        istack = []          # versions for which an insertion block is current
223
224
        dset = set()         # versions for which a deletion block is current
225
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
226
        isactive = False
0.1.48 by Martin Pool
Basic parsing of delete instructions.
227
228
        lineno = 0         # line of weave, 0-based
0.1.20 by Martin Pool
Factor out Knit.extract() method
229
        
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
230
        for l in self._l:
231
            if isinstance(l, tuple):
232
                c, v = l
233
                if c == '{':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
234
                    if istack and (istack[-1] >= v):
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
235
                        raise WeaveFormatError("improperly nested insertions %d>=%d on line %d" 
0.1.48 by Martin Pool
Basic parsing of delete instructions.
236
                                               % (istack[-1], v, lineno))
237
                    istack.append(v)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
238
                elif c == '}':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
239
                    try:
240
                        oldv = istack.pop()
241
                    except IndexError:
242
                        raise WeaveFormatError("unmatched close of insertion %d on line %d"
243
                                               % (v, lineno))
244
                    if oldv != v:
245
                        raise WeaveFormatError("mismatched close of insertion %d!=%d on line %d"
246
                                               % (oldv, v, lineno))
247
                elif c == '[':
248
                    # block deleted in v
249
                    if v in dset:
250
                        raise WeaveFormatError("repeated deletion marker for version %d on line %d"
251
                                               % (v, lineno))
0.1.49 by Martin Pool
Add another constraint: revisions should not delete text that they
252
                    if istack:
253
                        if istack[-1] == v:
254
                            raise WeaveFormatError("version %d deletes own text on line %d"
255
                                                   % (v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
256
                        dset.add(v)
257
                elif c == ']':
258
                    if v in dset:
259
                        dset.remove(v)
260
                    else:
261
                        raise WeaveFormatError("unmatched close of deletion %d on line %d"
262
                                               % (v, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
263
                else:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
264
                    raise WeaveFormatError("invalid processing instruction %r on line %d"
265
                                           % (l, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
266
            else:
267
                assert isinstance(l, basestring)
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
268
                if not istack:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
269
                    raise WeaveFormatError("literal at top level on line %d"
270
                                           % lineno)
0.1.50 by Martin Pool
Basic implementation of deletion markers
271
                isactive = (istack[-1] in included) \
272
                           and not included.intersection(dset)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
273
                if isactive:
0.1.48 by Martin Pool
Basic parsing of delete instructions.
274
                    origin = istack[-1]
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
275
                    yield origin, lineno, l
276
            lineno += 1
0.1.7 by Martin Pool
Add trivial annotate text
277
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
278
        if istack:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
279
            raise WeaveFormatError("unclosed insertion blocks at end of weave",
280
                                   istack)
0.1.48 by Martin Pool
Basic parsing of delete instructions.
281
        if dset:
282
            raise WeaveFormatError("unclosed deletion blocks at end of weave",
283
                                   dset)
0.1.40 by Martin Pool
Add test for extracting from weave with nested insertions
284
0.1.7 by Martin Pool
Add trivial annotate text
285
0.1.5 by Martin Pool
Add test for storing two text versions.
286
    def getiter(self, index):
287
        """Yield lines for the specified version."""
0.1.8 by Martin Pool
Unify get/annotate code
288
        for origin, line in self.annotate_iter(index):
289
            yield line
0.1.5 by Martin Pool
Add test for storing two text versions.
290
291
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
292
    def get(self, index):
0.1.5 by Martin Pool
Add test for storing two text versions.
293
        return list(self.getiter(index))
0.1.1 by Martin Pool
Check in old existing knit code.
294
295
0.1.11 by Martin Pool
Add Knit.dump method
296
    def dump(self, to_file):
297
        from pprint import pprint
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
298
        print >>to_file, "Weave._l = ",
0.1.11 by Martin Pool
Add Knit.dump method
299
        pprint(self._l, to_file)
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
300
        print >>to_file, "Weave._v = ",
0.1.18 by Martin Pool
Better Knit.dump method
301
        pprint(self._v, to_file)
0.1.11 by Martin Pool
Add Knit.dump method
302
303
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
304
    def check(self):
305
        for vers_info in self._v:
306
            included = set()
307
            for vi in vers_info[0]:
308
                if vi < 0 or vi >= index:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
309
                    raise WeaveFormatError("invalid included version %d for index %d"
310
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
311
                if vi in included:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
312
                    raise WeaveFormatError("repeated included version %d for index %d"
313
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
314
                included.add(vi)
0.1.18 by Martin Pool
Better Knit.dump method
315
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
316
317
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
318
    def _delta(self, included, lines):
319
        """Return changes from basis to new revision.
320
321
        The old text for comparison is the union of included revisions.
322
323
        This is used in inserting a new text.
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
324
325
        Delta is returned as a sequence of (line1, line2, newlines),
326
        indicating that line1 through line2 of the old weave should be
327
        replaced by the sequence of lines in newlines.  Note that
328
        these line numbers are positions in the total weave and don't
329
        correspond to the lines in any extracted version, or even the
330
        extracted union of included versions.
331
332
        If line1=line2, this is a pure insert; if newlines=[] this is a
333
        pure delete.  (Similar to difflib.)
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
334
        """
335
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
336
        self._check_versions(included)
337
0.1.23 by Martin Pool
tidy up
338
        ##from pprint import pprint
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
339
340
        # first get basis for comparison
341
        # basis holds (lineno, origin, line)
342
        basis = []
343
0.1.23 by Martin Pool
tidy up
344
        ##print 'my lines:'
345
        ##pprint(self._l)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
346
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
347
        basis = list(self._extract(included))
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
348
349
        # now make a parallel list with only the text, to pass to the differ
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
350
        basis_lines = [line for (origin, lineno, line) in basis]
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
351
352
        # add a sentinal, because we can also match against the final line
353
        basis.append((len(self._l), None))
354
355
        # XXX: which line of the weave should we really consider matches the end of the file?
356
        # the current code says it's the last line of the weave?
357
358
        from difflib import SequenceMatcher
359
        s = SequenceMatcher(None, basis_lines, lines)
360
0.1.23 by Martin Pool
tidy up
361
        ##print 'basis sequence:'
362
        ##pprint(basis)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
363
364
        for tag, i1, i2, j1, j2 in s.get_opcodes():
0.1.23 by Martin Pool
tidy up
365
            ##print tag, i1, i2, j1, j2
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
366
367
            if tag == 'equal':
368
                continue
369
370
            # i1,i2 are given in offsets within basis_lines; we need to map them
371
            # back to offsets within the entire weave
372
            real_i1 = basis[i1][0]
373
            real_i2 = basis[i2][0]
374
0.1.35 by Martin Pool
Clean up Knit._delta method
375
            assert 0 <= j1
376
            assert j1 <= j2
377
            assert j2 <= len(lines)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
378
0.1.35 by Martin Pool
Clean up Knit._delta method
379
            yield real_i1, real_i2, lines[j1:j2]
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
380
0.1.1 by Martin Pool
Check in old existing knit code.
381