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