/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)
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
152
153
                # the deletion and insertion are handled separately.
154
                # first delete the region.
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
155
                if i1 != i2:
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
156
                    self._l.insert(i1+offset, ('[', idx))
157
                    self._l.insert(i2+offset+1, (']', idx))
158
                    offset += 2
159
                    # is this OK???
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
160
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
161
                if newlines:
162
                    i = i1 + offset
163
                    self._l[i:i] = [('{', idx)] \
164
                                   + newlines \
165
                                   + [('}', idx)]
166
                    offset += 2 + len(newlines)
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
167
0.1.26 by Martin Pool
Refactor parameters to add command
168
            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
169
        else:
0.1.26 by Martin Pool
Refactor parameters to add command
170
            # 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
171
            # more quickly by just appending unconditionally
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
172
            self._l.append(('{', idx))
173
            self._l += text
174
            self._l.append(('}', idx))
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
175
176
            self._v.append(VerInfo())
177
            
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
178
        return idx
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
179
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
180
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
181
    def _check_lines(self, text):
182
        if not isinstance(text, list):
183
            raise ValueError("text should be a list, not %s" % type(text))
184
185
        for l in text:
186
            if not isinstance(l, basestring):
187
                raise ValueError("text line should be a string or unicode, not %s" % type(l))
188
        
189
190
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
191
    def _check_versions(self, indexes):
192
        """Check everything in the sequence of indexes is valid"""
193
        for i in indexes:
194
            try:
195
                self._v[i]
196
            except IndexError:
197
                raise IndexError("invalid version number %r" % i)
198
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
199
    
0.1.7 by Martin Pool
Add trivial annotate text
200
    def annotate(self, index):
201
        return list(self.annotate_iter(index))
202
203
204
    def annotate_iter(self, index):
205
        """Yield list of (index-id, line) pairs for the specified version.
206
207
        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
208
        try:
209
            vi = self._v[index]
210
        except IndexError:
211
            raise IndexError('version index %d out of range' % index)
0.1.20 by Martin Pool
Factor out Knit.extract() method
212
        included = set(vi.included)
213
        included.add(index)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
214
        for origin, lineno, text in self._extract(included):
215
            yield origin, text
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
216
217
218
    def _extract(self, included):
0.1.20 by Martin Pool
Factor out Knit.extract() method
219
        """Yield annotation of lines in included set.
220
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
221
        Yields a sequence of tuples (origin, lineno, text), where
222
        origin is the origin version, lineno the index in the weave,
223
        and text the text of the line.
224
0.1.20 by Martin Pool
Factor out Knit.extract() method
225
        The set typically but not necessarily corresponds to a version.
226
        """
0.1.48 by Martin Pool
Basic parsing of delete instructions.
227
        istack = []          # versions for which an insertion block is current
228
229
        dset = set()         # versions for which a deletion block is current
230
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
231
        isactive = False
0.1.48 by Martin Pool
Basic parsing of delete instructions.
232
233
        lineno = 0         # line of weave, 0-based
0.1.53 by Martin Pool
doc
234
235
        # TODO: Probably only need to put included revisions in the istack
236
237
        # TODO: Could split this into two functions, one that updates
238
        # the stack and the other that processes the results -- but
239
        # I'm not sure it's really needed.
0.1.20 by Martin Pool
Factor out Knit.extract() method
240
        
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
241
        for l in self._l:
242
            if isinstance(l, tuple):
243
                c, v = l
244
                if c == '{':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
245
                    if istack and (istack[-1] >= v):
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
246
                        raise WeaveFormatError("improperly nested insertions %d>=%d on line %d" 
0.1.48 by Martin Pool
Basic parsing of delete instructions.
247
                                               % (istack[-1], v, lineno))
248
                    istack.append(v)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
249
                elif c == '}':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
250
                    try:
251
                        oldv = istack.pop()
252
                    except IndexError:
253
                        raise WeaveFormatError("unmatched close of insertion %d on line %d"
254
                                               % (v, lineno))
255
                    if oldv != v:
256
                        raise WeaveFormatError("mismatched close of insertion %d!=%d on line %d"
257
                                               % (oldv, v, lineno))
258
                elif c == '[':
259
                    # block deleted in v
260
                    if v in dset:
261
                        raise WeaveFormatError("repeated deletion marker for version %d on line %d"
262
                                               % (v, lineno))
0.1.49 by Martin Pool
Add another constraint: revisions should not delete text that they
263
                    if istack:
264
                        if istack[-1] == v:
265
                            raise WeaveFormatError("version %d deletes own text on line %d"
266
                                                   % (v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
267
                        dset.add(v)
268
                elif c == ']':
269
                    if v in dset:
270
                        dset.remove(v)
271
                    else:
272
                        raise WeaveFormatError("unmatched close of deletion %d on line %d"
273
                                               % (v, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
274
                else:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
275
                    raise WeaveFormatError("invalid processing instruction %r on line %d"
276
                                           % (l, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
277
            else:
278
                assert isinstance(l, basestring)
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
279
                if not istack:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
280
                    raise WeaveFormatError("literal at top level on line %d"
281
                                           % lineno)
0.1.50 by Martin Pool
Basic implementation of deletion markers
282
                isactive = (istack[-1] in included) \
283
                           and not included.intersection(dset)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
284
                if isactive:
0.1.48 by Martin Pool
Basic parsing of delete instructions.
285
                    origin = istack[-1]
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
286
                    yield origin, lineno, l
287
            lineno += 1
0.1.7 by Martin Pool
Add trivial annotate text
288
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
289
        if istack:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
290
            raise WeaveFormatError("unclosed insertion blocks at end of weave",
291
                                   istack)
0.1.48 by Martin Pool
Basic parsing of delete instructions.
292
        if dset:
293
            raise WeaveFormatError("unclosed deletion blocks at end of weave",
294
                                   dset)
0.1.40 by Martin Pool
Add test for extracting from weave with nested insertions
295
0.1.7 by Martin Pool
Add trivial annotate text
296
0.1.5 by Martin Pool
Add test for storing two text versions.
297
    def getiter(self, index):
298
        """Yield lines for the specified version."""
0.1.8 by Martin Pool
Unify get/annotate code
299
        for origin, line in self.annotate_iter(index):
300
            yield line
0.1.5 by Martin Pool
Add test for storing two text versions.
301
302
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
303
    def get(self, index):
0.1.5 by Martin Pool
Add test for storing two text versions.
304
        return list(self.getiter(index))
0.1.1 by Martin Pool
Check in old existing knit code.
305
306
0.1.11 by Martin Pool
Add Knit.dump method
307
    def dump(self, to_file):
308
        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.)
309
        print >>to_file, "Weave._l = ",
0.1.11 by Martin Pool
Add Knit.dump method
310
        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.)
311
        print >>to_file, "Weave._v = ",
0.1.18 by Martin Pool
Better Knit.dump method
312
        pprint(self._v, to_file)
0.1.11 by Martin Pool
Add Knit.dump method
313
314
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
315
    def check(self):
316
        for vers_info in self._v:
317
            included = set()
318
            for vi in vers_info[0]:
319
                if vi < 0 or vi >= index:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
320
                    raise WeaveFormatError("invalid included version %d for index %d"
321
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
322
                if vi in included:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
323
                    raise WeaveFormatError("repeated included version %d for index %d"
324
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
325
                included.add(vi)
0.1.18 by Martin Pool
Better Knit.dump method
326
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
327
328
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
329
    def _delta(self, included, lines):
330
        """Return changes from basis to new revision.
331
332
        The old text for comparison is the union of included revisions.
333
334
        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.
335
0.1.55 by Martin Pool
doc
336
        Delta is returned as a sequence of
337
        (weave1, weave2, newlines).
338
339
        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.
340
        replaced by the sequence of lines in newlines.  Note that
341
        these line numbers are positions in the total weave and don't
342
        correspond to the lines in any extracted version, or even the
343
        extracted union of included versions.
344
345
        If line1=line2, this is a pure insert; if newlines=[] this is a
346
        pure delete.  (Similar to difflib.)
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
347
        """
348
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
349
        self._check_versions(included)
350
0.1.23 by Martin Pool
tidy up
351
        ##from pprint import pprint
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
352
353
        # first get basis for comparison
354
        # basis holds (lineno, origin, line)
355
        basis = []
356
0.1.23 by Martin Pool
tidy up
357
        ##print 'my lines:'
358
        ##pprint(self._l)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
359
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
360
        # 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
361
        basis = list(self._extract(included))
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
362
363
        # 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
364
        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.
365
366
        # 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
367
        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.
368
369
        # XXX: which line of the weave should we really consider matches the end of the file?
370
        # the current code says it's the last line of the weave?
371
372
        from difflib import SequenceMatcher
373
        s = SequenceMatcher(None, basis_lines, lines)
374
0.1.23 by Martin Pool
tidy up
375
        ##print 'basis sequence:'
376
        ##pprint(basis)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
377
0.1.55 by Martin Pool
doc
378
        # TODO: Perhaps return line numbers from composed weave as well?
379
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
380
        for tag, i1, i2, j1, j2 in s.get_opcodes():
0.1.23 by Martin Pool
tidy up
381
            ##print tag, i1, i2, j1, j2
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
382
383
            if tag == 'equal':
384
                continue
385
386
            # i1,i2 are given in offsets within basis_lines; we need to map them
387
            # back to offsets within the entire weave
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
388
            real_i1 = basis[i1][1]
389
            real_i2 = basis[i2][1]
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
390
0.1.35 by Martin Pool
Clean up Knit._delta method
391
            assert 0 <= j1
392
            assert j1 <= j2
393
            assert j2 <= len(lines)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
394
0.1.35 by Martin Pool
Clean up Knit._delta method
395
            yield real_i1, real_i2, lines[j1:j2]
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
396
0.1.1 by Martin Pool
Check in old existing knit code.
397