/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
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
157
                i = i1 + offset
158
                self._l[i:i] = [('{', idx)] \
159
                               + newlines \
160
                               + [('}', idx)]
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
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.53 by Martin Pool
doc
229
230
        # TODO: Probably only need to put included revisions in the istack
231
232
        # TODO: Could split this into two functions, one that updates
233
        # the stack and the other that processes the results -- but
234
        # I'm not sure it's really needed.
0.1.20 by Martin Pool
Factor out Knit.extract() method
235
        
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
236
        for l in self._l:
237
            if isinstance(l, tuple):
238
                c, v = l
239
                if c == '{':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
240
                    if istack and (istack[-1] >= v):
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
241
                        raise WeaveFormatError("improperly nested insertions %d>=%d on line %d" 
0.1.48 by Martin Pool
Basic parsing of delete instructions.
242
                                               % (istack[-1], v, lineno))
243
                    istack.append(v)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
244
                elif c == '}':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
245
                    try:
246
                        oldv = istack.pop()
247
                    except IndexError:
248
                        raise WeaveFormatError("unmatched close of insertion %d on line %d"
249
                                               % (v, lineno))
250
                    if oldv != v:
251
                        raise WeaveFormatError("mismatched close of insertion %d!=%d on line %d"
252
                                               % (oldv, v, lineno))
253
                elif c == '[':
254
                    # block deleted in v
255
                    if v in dset:
256
                        raise WeaveFormatError("repeated deletion marker for version %d on line %d"
257
                                               % (v, lineno))
0.1.49 by Martin Pool
Add another constraint: revisions should not delete text that they
258
                    if istack:
259
                        if istack[-1] == v:
260
                            raise WeaveFormatError("version %d deletes own text on line %d"
261
                                                   % (v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
262
                        dset.add(v)
263
                elif c == ']':
264
                    if v in dset:
265
                        dset.remove(v)
266
                    else:
267
                        raise WeaveFormatError("unmatched close of deletion %d on line %d"
268
                                               % (v, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
269
                else:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
270
                    raise WeaveFormatError("invalid processing instruction %r on line %d"
271
                                           % (l, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
272
            else:
273
                assert isinstance(l, basestring)
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
274
                if not istack:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
275
                    raise WeaveFormatError("literal at top level on line %d"
276
                                           % lineno)
0.1.50 by Martin Pool
Basic implementation of deletion markers
277
                isactive = (istack[-1] in included) \
278
                           and not included.intersection(dset)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
279
                if isactive:
0.1.48 by Martin Pool
Basic parsing of delete instructions.
280
                    origin = istack[-1]
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
281
                    yield origin, lineno, l
282
            lineno += 1
0.1.7 by Martin Pool
Add trivial annotate text
283
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
284
        if istack:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
285
            raise WeaveFormatError("unclosed insertion blocks at end of weave",
286
                                   istack)
0.1.48 by Martin Pool
Basic parsing of delete instructions.
287
        if dset:
288
            raise WeaveFormatError("unclosed deletion blocks at end of weave",
289
                                   dset)
0.1.40 by Martin Pool
Add test for extracting from weave with nested insertions
290
0.1.7 by Martin Pool
Add trivial annotate text
291
0.1.5 by Martin Pool
Add test for storing two text versions.
292
    def getiter(self, index):
293
        """Yield lines for the specified version."""
0.1.8 by Martin Pool
Unify get/annotate code
294
        for origin, line in self.annotate_iter(index):
295
            yield line
0.1.5 by Martin Pool
Add test for storing two text versions.
296
297
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
298
    def get(self, index):
0.1.5 by Martin Pool
Add test for storing two text versions.
299
        return list(self.getiter(index))
0.1.1 by Martin Pool
Check in old existing knit code.
300
301
0.1.11 by Martin Pool
Add Knit.dump method
302
    def dump(self, to_file):
303
        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.)
304
        print >>to_file, "Weave._l = ",
0.1.11 by Martin Pool
Add Knit.dump method
305
        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.)
306
        print >>to_file, "Weave._v = ",
0.1.18 by Martin Pool
Better Knit.dump method
307
        pprint(self._v, to_file)
0.1.11 by Martin Pool
Add Knit.dump method
308
309
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
310
    def check(self):
311
        for vers_info in self._v:
312
            included = set()
313
            for vi in vers_info[0]:
314
                if vi < 0 or vi >= index:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
315
                    raise WeaveFormatError("invalid included version %d for index %d"
316
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
317
                if vi in included:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
318
                    raise WeaveFormatError("repeated included version %d for index %d"
319
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
320
                included.add(vi)
0.1.18 by Martin Pool
Better Knit.dump method
321
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
322
323
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
324
    def _delta(self, included, lines):
325
        """Return changes from basis to new revision.
326
327
        The old text for comparison is the union of included revisions.
328
329
        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.
330
0.1.55 by Martin Pool
doc
331
        Delta is returned as a sequence of
332
        (weave1, weave2, newlines).
333
334
        This indicates that weave1:weave2 of the old weave should be
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
335
        replaced by the sequence of lines in newlines.  Note that
336
        these line numbers are positions in the total weave and don't
337
        correspond to the lines in any extracted version, or even the
338
        extracted union of included versions.
339
340
        If line1=line2, this is a pure insert; if newlines=[] this is a
341
        pure delete.  (Similar to difflib.)
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
342
        """
343
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
344
        self._check_versions(included)
345
0.1.23 by Martin Pool
tidy up
346
        ##from pprint import pprint
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
347
348
        # first get basis for comparison
349
        # basis holds (lineno, origin, line)
350
        basis = []
351
0.1.23 by Martin Pool
tidy up
352
        ##print 'my lines:'
353
        ##pprint(self._l)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
354
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
355
        # basis a list of (origin, lineno, line)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
356
        basis = list(self._extract(included))
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
357
358
        # 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
359
        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.
360
361
        # add a sentinal, because we can also match against the final line
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
362
        basis.append((None, len(self._l), None))
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
363
364
        # XXX: which line of the weave should we really consider matches the end of the file?
365
        # the current code says it's the last line of the weave?
366
367
        from difflib import SequenceMatcher
368
        s = SequenceMatcher(None, basis_lines, lines)
369
0.1.23 by Martin Pool
tidy up
370
        ##print 'basis sequence:'
371
        ##pprint(basis)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
372
0.1.55 by Martin Pool
doc
373
        # TODO: Perhaps return line numbers from composed weave as well?
374
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
375
        for tag, i1, i2, j1, j2 in s.get_opcodes():
0.1.23 by Martin Pool
tidy up
376
            ##print tag, i1, i2, j1, j2
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
377
378
            if tag == 'equal':
379
                continue
380
381
            # i1,i2 are given in offsets within basis_lines; we need to map them
382
            # back to offsets within the entire weave
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
383
            real_i1 = basis[i1][1]
384
            real_i2 = basis[i2][1]
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
385
0.1.35 by Martin Pool
Clean up Knit._delta method
386
            assert 0 <= j1
387
            assert j1 <= j2
388
            assert j2 <= len(lines)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
389
0.1.35 by Martin Pool
Clean up Knit._delta method
390
            yield real_i1, real_i2, lines[j1:j2]
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
391
0.1.1 by Martin Pool
Check in old existing knit code.
392