/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.61 by Martin Pool
doc
24
# TODO: Perhaps have copy method for Weave instances?
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
25
0.1.58 by Martin Pool
doc
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
28
# property.
29
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
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
32
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.
37
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
40
# usefully so?
41
42
# TODO: Track version names as well as indexes. 
43
44
# TODO: Probably do transitive expansion when specifying parents?
0.1.58 by Martin Pool
doc
45
0.1.68 by Martin Pool
doc
46
# TODO: Separate out some code to read and write weaves.
47
0.1.34 by Martin Pool
remove dead code
48
0.1.66 by Martin Pool
Cope without set/frozenset classes
49
try:
50
    set
51
    frozenset
52
except NameError:
53
    from sets import Set, ImmutableSet
54
    set = Set
55
    frozenset = ImmutableSet
0.1.67 by Martin Pool
More fixes to try to run on python2.3
56
    del Set, ImmutableSet
0.1.66 by Martin Pool
Cope without set/frozenset classes
57
58
0.1.17 by Martin Pool
Use objects rather than tuples for tracking VerInfo for
59
class VerInfo(object):
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
60
    """Information about a version in a Weave."""
0.1.17 by Martin Pool
Use objects rather than tuples for tracking VerInfo for
61
    included = frozenset()
62
    def __init__(self, included=None):
63
        if included:
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
64
            self.included = frozenset(included)
0.1.17 by Martin Pool
Use objects rather than tuples for tracking VerInfo for
65
0.1.18 by Martin Pool
Better Knit.dump method
66
    def __repr__(self):
67
        s = self.__class__.__name__ + '('
68
        if self.included:
69
            s += 'included=%r' % (list(self.included))
70
        s += ')'
71
        return s
72
0.1.17 by Martin Pool
Use objects rather than tuples for tracking VerInfo for
73
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
74
class WeaveError(Exception):
75
    """Exception in processing weave"""
76
77
78
class WeaveFormatError(WeaveError):
79
    """Weave invariant violated"""
80
    
81
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
82
class Weave(object):
83
    """weave - versioned text file storage.
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
84
    
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
85
    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.
86
    originating version for each line.
87
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
88
    Texts can be identified in either of two ways:
89
90
    * a nonnegative index number.
91
92
    * a version-id string.
93
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
94
    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.
95
    the version-id is used to reference it in the larger world.
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
96
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
97
    The weave is represented as a list mixing edit instructions and
98
    literal text.  Each entry in _l can be either a string (or
99
    unicode), or a tuple.  If a string, it means that the given line
100
    should be output in the currently active revisions.
101
102
    If a tuple, it gives a processing instruction saying in which
103
    revisions the enclosed lines are active.  The tuple has the form
104
    (instruction, version).
105
106
    The instruction can be '{' or '}' for an insertion block, and '['
107
    and ']' for a deletion block respectively.  The version is the
0.1.45 by Martin Pool
doc
108
    integer version index.  There is no replace operator, only deletes
109
    and inserts.
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
110
0.1.41 by Martin Pool
Doc
111
    Constraints/notes:
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
112
113
    * A later version can delete lines that were introduced by any
114
      number of ancestor versions; this implies that deletion
115
      instructions can span insertion blocks without regard to the
116
      insertion block's nesting.
117
0.1.41 by Martin Pool
Doc
118
    * Similarly, deletions need not be properly nested with regard to
119
      each other, because they might have been generated by
120
      independent revisions.
121
0.1.45 by Martin Pool
doc
122
    * Insertions are always made by inserting a new bracketed block
123
      into a single point in the previous weave.  This implies they
124
      can nest but not overlap, and the nesting must always have later
125
      insertions on the inside.
126
0.1.41 by Martin Pool
Doc
127
    * It doesn't seem very useful to have an active insertion
128
      inside an inactive insertion, but it might happen.
0.1.45 by Martin Pool
doc
129
      
0.1.41 by Martin Pool
Doc
130
    * Therefore, all instructions are always"considered"; that
131
      is passed onto and off the stack.  An outer inactive block
132
      doesn't disable an inner block.
133
134
    * Lines are enabled if the most recent enclosing insertion is
135
      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
136
0.1.49 by Martin Pool
Add another constraint: revisions should not delete text that they
137
    * There is no point having a deletion directly inside its own
138
      insertion; you might as well just not write it.  And there
139
      should be no way to get an earlier version deleting a later
140
      version.
141
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
142
    _l
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
143
        Text of the weave. 
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
144
145
    _v
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
146
        List of versions, indexed by index number.
147
148
        For each version we store the tuple (included_versions), which
149
        lists the previous versions also considered active.
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
150
    """
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
151
    def __init__(self):
152
        self._l = []
153
        self._v = []
0.1.5 by Martin Pool
Add test for storing two text versions.
154
0.1.60 by Martin Pool
Weave eq and ne methods
155
156
157
    def __eq__(self, other):
158
        if not isinstance(other, Weave):
159
            return False
160
        return self._v == other._v \
161
               and self._l == other._l
162
    
163
164
    def __ne__(self, other):
165
        return not self.__eq__(other)
166
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
167
        
0.1.26 by Martin Pool
Refactor parameters to add command
168
    def add(self, parents, text):
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
169
        """Add a single text on top of the weave.
0.1.36 by Martin Pool
doc
170
  
0.1.26 by Martin Pool
Refactor parameters to add command
171
        Returns the index number of the newly added version.
172
173
        parents
0.1.64 by Martin Pool
Add test for merging versions
174
            List or set of parent version numbers.  This must normally include
175
            the parents and the parent's parents, or wierd things might happen.
0.1.26 by Martin Pool
Refactor parameters to add command
176
177
        text
178
            Sequence of lines to be added in the new version."""
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
179
        self._check_versions(parents)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
180
        self._check_lines(text)
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
181
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
182
        idx = len(self._v)
0.1.5 by Martin Pool
Add test for storing two text versions.
183
0.1.26 by Martin Pool
Refactor parameters to add command
184
        if parents:
185
            parents = frozenset(parents)
186
            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
187
0.1.31 by Martin Pool
Fix insertion of multiple regions, calculating the right line offset as we go.
188
            # offset gives the number of lines that have been inserted
189
            # into the weave up to the current point; if the original edit instruction
190
            # says to change line A then we actually change (A+offset)
191
            offset = 0
192
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
193
            for i1, i2, newlines in delta:
0.1.29 by Martin Pool
Better internal error
194
                assert 0 <= i1
195
                assert i1 <= i2
196
                assert i2 <= len(self._l)
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
197
198
                # the deletion and insertion are handled separately.
199
                # first delete the region.
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
200
                if i1 != i2:
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
201
                    self._l.insert(i1+offset, ('[', idx))
202
                    self._l.insert(i2+offset+1, (']', idx))
203
                    offset += 2
204
                    # is this OK???
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
205
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
206
                if newlines:
0.1.57 by Martin Pool
Fix bug in an update edit that both deletes and inserts -- previously
207
                    # there may have been a deletion spanning up to
208
                    # i2; we want to insert after this region to make sure
209
                    # we don't destroy ourselves
210
                    i = i2 + offset
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
211
                    self._l[i:i] = [('{', idx)] \
212
                                   + newlines \
213
                                   + [('}', idx)]
214
                    offset += 2 + len(newlines)
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
215
0.1.26 by Martin Pool
Refactor parameters to add command
216
            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
217
        else:
0.1.26 by Martin Pool
Refactor parameters to add command
218
            # 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
219
            # more quickly by just appending unconditionally
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
220
            self._l.append(('{', idx))
221
            self._l += text
222
            self._l.append(('}', idx))
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
223
224
            self._v.append(VerInfo())
225
            
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
226
        return idx
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
227
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
228
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
229
    def _check_lines(self, text):
230
        if not isinstance(text, list):
231
            raise ValueError("text should be a list, not %s" % type(text))
232
233
        for l in text:
234
            if not isinstance(l, basestring):
235
                raise ValueError("text line should be a string or unicode, not %s" % type(l))
236
        
237
238
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
239
    def _check_versions(self, indexes):
240
        """Check everything in the sequence of indexes is valid"""
241
        for i in indexes:
242
            try:
243
                self._v[i]
244
            except IndexError:
245
                raise IndexError("invalid version number %r" % i)
246
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
247
    
0.1.7 by Martin Pool
Add trivial annotate text
248
    def annotate(self, index):
249
        return list(self.annotate_iter(index))
250
251
252
    def annotate_iter(self, index):
253
        """Yield list of (index-id, line) pairs for the specified version.
254
255
        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
256
        try:
257
            vi = self._v[index]
258
        except IndexError:
259
            raise IndexError('version index %d out of range' % index)
0.1.20 by Martin Pool
Factor out Knit.extract() method
260
        included = set(vi.included)
261
        included.add(index)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
262
        for origin, lineno, text in self._extract(included):
263
            yield origin, text
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
264
265
266
    def _extract(self, included):
0.1.20 by Martin Pool
Factor out Knit.extract() method
267
        """Yield annotation of lines in included set.
268
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
269
        Yields a sequence of tuples (origin, lineno, text), where
270
        origin is the origin version, lineno the index in the weave,
271
        and text the text of the line.
272
0.1.20 by Martin Pool
Factor out Knit.extract() method
273
        The set typically but not necessarily corresponds to a version.
274
        """
0.1.48 by Martin Pool
Basic parsing of delete instructions.
275
        istack = []          # versions for which an insertion block is current
276
277
        dset = set()         # versions for which a deletion block is current
278
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
279
        isactive = False
0.1.48 by Martin Pool
Basic parsing of delete instructions.
280
281
        lineno = 0         # line of weave, 0-based
0.1.53 by Martin Pool
doc
282
283
        # TODO: Probably only need to put included revisions in the istack
284
285
        # TODO: Could split this into two functions, one that updates
286
        # the stack and the other that processes the results -- but
287
        # I'm not sure it's really needed.
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
288
289
        WFE = WeaveFormatError
0.1.20 by Martin Pool
Factor out Knit.extract() method
290
        
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
291
        for l in self._l:
292
            if isinstance(l, tuple):
293
                c, v = l
294
                if c == '{':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
295
                    if istack and (istack[-1] >= v):
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
296
                        raise WFE("improperly nested insertions %d>=%d on line %d" 
297
                                  % (istack[-1], v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
298
                    istack.append(v)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
299
                elif c == '}':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
300
                    try:
301
                        oldv = istack.pop()
302
                    except IndexError:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
303
                        raise WFE("unmatched close of insertion %d on line %d"
304
                                  % (v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
305
                    if oldv != v:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
306
                        raise WFE("mismatched close of insertion %d!=%d on line %d"
307
                                  % (oldv, v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
308
                elif c == '[':
309
                    # block deleted in v
310
                    if v in dset:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
311
                        raise WFE("repeated deletion marker for version %d on line %d"
312
                                  % (v, lineno))
0.1.49 by Martin Pool
Add another constraint: revisions should not delete text that they
313
                    if istack:
314
                        if istack[-1] == v:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
315
                            raise WFE("version %d deletes own text on line %d"
316
                                      % (v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
317
                        dset.add(v)
318
                elif c == ']':
319
                    if v in dset:
320
                        dset.remove(v)
321
                    else:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
322
                        raise WFE("unmatched close of deletion %d on line %d"
323
                                  % (v, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
324
                else:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
325
                    raise WFE("invalid processing instruction %r on line %d"
326
                              % (l, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
327
            else:
328
                assert isinstance(l, basestring)
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
329
                if not istack:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
330
                    raise WFE("literal at top level on line %d"
331
                              % lineno)
0.1.50 by Martin Pool
Basic implementation of deletion markers
332
                isactive = (istack[-1] in included) \
333
                           and not included.intersection(dset)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
334
                if isactive:
0.1.48 by Martin Pool
Basic parsing of delete instructions.
335
                    origin = istack[-1]
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
336
                    yield origin, lineno, l
337
            lineno += 1
0.1.7 by Martin Pool
Add trivial annotate text
338
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
339
        if istack:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
340
            raise WFE("unclosed insertion blocks at end of weave",
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
341
                                   istack)
0.1.48 by Martin Pool
Basic parsing of delete instructions.
342
        if dset:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
343
            raise WFE("unclosed deletion blocks at end of weave",
0.1.48 by Martin Pool
Basic parsing of delete instructions.
344
                                   dset)
0.1.40 by Martin Pool
Add test for extracting from weave with nested insertions
345
0.1.7 by Martin Pool
Add trivial annotate text
346
0.1.5 by Martin Pool
Add test for storing two text versions.
347
    def getiter(self, index):
348
        """Yield lines for the specified version."""
0.1.8 by Martin Pool
Unify get/annotate code
349
        for origin, line in self.annotate_iter(index):
350
            yield line
0.1.5 by Martin Pool
Add test for storing two text versions.
351
352
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
353
    def get(self, index):
0.1.5 by Martin Pool
Add test for storing two text versions.
354
        return list(self.getiter(index))
0.1.1 by Martin Pool
Check in old existing knit code.
355
356
0.1.65 by Martin Pool
Add Weave.merge_iter to get automerged lines
357
    def merge_iter(self, included):
358
        """Return composed version of multiple included versions."""
359
        included = frozenset(included)
360
        for origin, lineno, text in self._extract(included):
361
            yield text
362
363
0.1.11 by Martin Pool
Add Knit.dump method
364
    def dump(self, to_file):
365
        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.)
366
        print >>to_file, "Weave._l = ",
0.1.11 by Martin Pool
Add Knit.dump method
367
        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.)
368
        print >>to_file, "Weave._v = ",
0.1.18 by Martin Pool
Better Knit.dump method
369
        pprint(self._v, to_file)
0.1.11 by Martin Pool
Add Knit.dump method
370
371
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
372
    def check(self):
373
        for vers_info in self._v:
374
            included = set()
375
            for vi in vers_info[0]:
376
                if vi < 0 or vi >= index:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
377
                    raise WeaveFormatError("invalid included version %d for index %d"
378
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
379
                if vi in included:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
380
                    raise WeaveFormatError("repeated included version %d for index %d"
381
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
382
                included.add(vi)
0.1.18 by Martin Pool
Better Knit.dump method
383
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
384
385
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
386
    def _delta(self, included, lines):
387
        """Return changes from basis to new revision.
388
389
        The old text for comparison is the union of included revisions.
390
391
        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.
392
0.1.55 by Martin Pool
doc
393
        Delta is returned as a sequence of
394
        (weave1, weave2, newlines).
395
396
        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.
397
        replaced by the sequence of lines in newlines.  Note that
398
        these line numbers are positions in the total weave and don't
399
        correspond to the lines in any extracted version, or even the
400
        extracted union of included versions.
401
402
        If line1=line2, this is a pure insert; if newlines=[] this is a
403
        pure delete.  (Similar to difflib.)
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
404
        """
405
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
406
        self._check_versions(included)
407
0.1.23 by Martin Pool
tidy up
408
        ##from pprint import pprint
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
409
410
        # first get basis for comparison
411
        # basis holds (lineno, origin, line)
412
        basis = []
413
0.1.23 by Martin Pool
tidy up
414
        ##print 'my lines:'
415
        ##pprint(self._l)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
416
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
417
        # 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
418
        basis = list(self._extract(included))
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
419
420
        # 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
421
        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.
422
423
        # 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
424
        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.
425
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
426
        # XXX: which line of the weave should we really consider
427
        # matches the end of the file?  the current code says it's the
428
        # last line of the weave?
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
429
430
        from difflib import SequenceMatcher
431
        s = SequenceMatcher(None, basis_lines, lines)
432
0.1.23 by Martin Pool
tidy up
433
        ##print 'basis sequence:'
434
        ##pprint(basis)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
435
0.1.55 by Martin Pool
doc
436
        # TODO: Perhaps return line numbers from composed weave as well?
437
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
438
        for tag, i1, i2, j1, j2 in s.get_opcodes():
0.1.23 by Martin Pool
tidy up
439
            ##print tag, i1, i2, j1, j2
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
440
441
            if tag == 'equal':
442
                continue
443
444
            # i1,i2 are given in offsets within basis_lines; we need to map them
445
            # back to offsets within the entire weave
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
446
            real_i1 = basis[i1][1]
447
            real_i2 = basis[i2][1]
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
448
0.1.35 by Martin Pool
Clean up Knit._delta method
449
            assert 0 <= j1
450
            assert j1 <= j2
451
            assert j2 <= len(lines)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
452
0.1.35 by Martin Pool
Clean up Knit._delta method
453
            yield real_i1, real_i2, lines[j1:j2]
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
454
0.1.1 by Martin Pool
Check in old existing knit code.
455
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
456
457
458
def main(argv):
459
    import sys
460
    import os
461
    from cPickle import dump, load
462
    cmd = argv[1]
463
    if cmd == 'add':
464
        w = load(file(argv[2], 'rb'))
465
        # at the moment, based on everything in the file
466
        parents = set(range(len(w._v)))
467
        ver = w.add(parents, sys.stdin.readlines())
468
        dump(w, file(argv[2], 'wb'))
469
        print 'added %d' % ver
470
    elif cmd == 'init':
471
        fn = argv[2]
472
        if os.path.exists(fn):
473
            raise IOError("file exists")
474
        w = Weave()
475
        dump(w, file(fn, 'wb'))
476
    elif cmd == 'get':
477
        w = load(file(argv[2], 'rb'))
478
        sys.stdout.writelines(w.get(int(argv[3])))
479
    elif cmd == 'annotate':
480
        w = load(file(argv[2], 'rb'))
481
        # assumes lines are ended
482
        lasto = None
483
        for origin, text in w.annotate(int(argv[3])):
484
            if text[-1] == '\n':
485
                text = text[:-1]
486
            if origin == lasto:
487
                print '      | %s' % (text)
488
            else:
489
                print '%5d | %s' % (origin, text)
490
                lasto = origin
491
    else:
492
        raise ValueError('unknown command %r' % cmd)
493
    
494
495
if __name__ == '__main__':
496
    import sys
497
    sys.exit(main(sys.argv))