/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
162
            List or set of parent version numbers.
163
164
        text
165
            Sequence of lines to be added in the new version."""
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
166
        self._check_versions(parents)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
167
        self._check_lines(text)
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
168
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
169
        idx = len(self._v)
0.1.5 by Martin Pool
Add test for storing two text versions.
170
0.1.26 by Martin Pool
Refactor parameters to add command
171
        if parents:
172
            parents = frozenset(parents)
173
            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
174
0.1.31 by Martin Pool
Fix insertion of multiple regions, calculating the right line offset as we go.
175
            # offset gives the number of lines that have been inserted
176
            # into the weave up to the current point; if the original edit instruction
177
            # says to change line A then we actually change (A+offset)
178
            offset = 0
179
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
180
            for i1, i2, newlines in delta:
0.1.29 by Martin Pool
Better internal error
181
                assert 0 <= i1
182
                assert i1 <= i2
183
                assert i2 <= len(self._l)
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
184
185
                # the deletion and insertion are handled separately.
186
                # first delete the region.
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
187
                if i1 != i2:
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
188
                    self._l.insert(i1+offset, ('[', idx))
189
                    self._l.insert(i2+offset+1, (']', idx))
190
                    offset += 2
191
                    # is this OK???
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
192
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
193
                if newlines:
0.1.57 by Martin Pool
Fix bug in an update edit that both deletes and inserts -- previously
194
                    # there may have been a deletion spanning up to
195
                    # i2; we want to insert after this region to make sure
196
                    # we don't destroy ourselves
197
                    i = i2 + offset
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
198
                    self._l[i:i] = [('{', idx)] \
199
                                   + newlines \
200
                                   + [('}', idx)]
201
                    offset += 2 + len(newlines)
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
202
0.1.26 by Martin Pool
Refactor parameters to add command
203
            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
204
        else:
0.1.26 by Martin Pool
Refactor parameters to add command
205
            # 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
206
            # more quickly by just appending unconditionally
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
207
            self._l.append(('{', idx))
208
            self._l += text
209
            self._l.append(('}', idx))
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
210
211
            self._v.append(VerInfo())
212
            
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
213
        return idx
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
214
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
215
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
216
    def _check_lines(self, text):
217
        if not isinstance(text, list):
218
            raise ValueError("text should be a list, not %s" % type(text))
219
220
        for l in text:
221
            if not isinstance(l, basestring):
222
                raise ValueError("text line should be a string or unicode, not %s" % type(l))
223
        
224
225
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
226
    def _check_versions(self, indexes):
227
        """Check everything in the sequence of indexes is valid"""
228
        for i in indexes:
229
            try:
230
                self._v[i]
231
            except IndexError:
232
                raise IndexError("invalid version number %r" % i)
233
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
234
    
0.1.7 by Martin Pool
Add trivial annotate text
235
    def annotate(self, index):
236
        return list(self.annotate_iter(index))
237
238
239
    def annotate_iter(self, index):
240
        """Yield list of (index-id, line) pairs for the specified version.
241
242
        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
243
        try:
244
            vi = self._v[index]
245
        except IndexError:
246
            raise IndexError('version index %d out of range' % index)
0.1.20 by Martin Pool
Factor out Knit.extract() method
247
        included = set(vi.included)
248
        included.add(index)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
249
        for origin, lineno, text in self._extract(included):
250
            yield origin, text
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
251
252
253
    def _extract(self, included):
0.1.20 by Martin Pool
Factor out Knit.extract() method
254
        """Yield annotation of lines in included set.
255
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
256
        Yields a sequence of tuples (origin, lineno, text), where
257
        origin is the origin version, lineno the index in the weave,
258
        and text the text of the line.
259
0.1.20 by Martin Pool
Factor out Knit.extract() method
260
        The set typically but not necessarily corresponds to a version.
261
        """
0.1.48 by Martin Pool
Basic parsing of delete instructions.
262
        istack = []          # versions for which an insertion block is current
263
264
        dset = set()         # versions for which a deletion block is current
265
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
266
        isactive = False
0.1.48 by Martin Pool
Basic parsing of delete instructions.
267
268
        lineno = 0         # line of weave, 0-based
0.1.53 by Martin Pool
doc
269
270
        # TODO: Probably only need to put included revisions in the istack
271
272
        # TODO: Could split this into two functions, one that updates
273
        # the stack and the other that processes the results -- but
274
        # I'm not sure it's really needed.
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
275
276
        WFE = WeaveFormatError
0.1.20 by Martin Pool
Factor out Knit.extract() method
277
        
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
278
        for l in self._l:
279
            if isinstance(l, tuple):
280
                c, v = l
281
                if c == '{':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
282
                    if istack and (istack[-1] >= v):
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
283
                        raise WFE("improperly nested insertions %d>=%d on line %d" 
284
                                  % (istack[-1], v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
285
                    istack.append(v)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
286
                elif c == '}':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
287
                    try:
288
                        oldv = istack.pop()
289
                    except IndexError:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
290
                        raise WFE("unmatched close of insertion %d on line %d"
291
                                  % (v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
292
                    if oldv != v:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
293
                        raise WFE("mismatched close of insertion %d!=%d on line %d"
294
                                  % (oldv, v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
295
                elif c == '[':
296
                    # block deleted in v
297
                    if v in dset:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
298
                        raise WFE("repeated deletion marker for version %d on line %d"
299
                                  % (v, lineno))
0.1.49 by Martin Pool
Add another constraint: revisions should not delete text that they
300
                    if istack:
301
                        if istack[-1] == v:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
302
                            raise WFE("version %d deletes own text on line %d"
303
                                      % (v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
304
                        dset.add(v)
305
                elif c == ']':
306
                    if v in dset:
307
                        dset.remove(v)
308
                    else:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
309
                        raise WFE("unmatched close of deletion %d on line %d"
310
                                  % (v, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
311
                else:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
312
                    raise WFE("invalid processing instruction %r on line %d"
313
                              % (l, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
314
            else:
315
                assert isinstance(l, basestring)
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
316
                if not istack:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
317
                    raise WFE("literal at top level on line %d"
318
                              % lineno)
0.1.50 by Martin Pool
Basic implementation of deletion markers
319
                isactive = (istack[-1] in included) \
320
                           and not included.intersection(dset)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
321
                if isactive:
0.1.48 by Martin Pool
Basic parsing of delete instructions.
322
                    origin = istack[-1]
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
323
                    yield origin, lineno, l
324
            lineno += 1
0.1.7 by Martin Pool
Add trivial annotate text
325
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
326
        if istack:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
327
            raise WFE("unclosed insertion blocks at end of weave",
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
328
                                   istack)
0.1.48 by Martin Pool
Basic parsing of delete instructions.
329
        if dset:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
330
            raise WFE("unclosed deletion blocks at end of weave",
0.1.48 by Martin Pool
Basic parsing of delete instructions.
331
                                   dset)
0.1.40 by Martin Pool
Add test for extracting from weave with nested insertions
332
0.1.7 by Martin Pool
Add trivial annotate text
333
0.1.5 by Martin Pool
Add test for storing two text versions.
334
    def getiter(self, index):
335
        """Yield lines for the specified version."""
0.1.8 by Martin Pool
Unify get/annotate code
336
        for origin, line in self.annotate_iter(index):
337
            yield line
0.1.5 by Martin Pool
Add test for storing two text versions.
338
339
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
340
    def get(self, index):
0.1.5 by Martin Pool
Add test for storing two text versions.
341
        return list(self.getiter(index))
0.1.1 by Martin Pool
Check in old existing knit code.
342
343
0.1.11 by Martin Pool
Add Knit.dump method
344
    def dump(self, to_file):
345
        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.)
346
        print >>to_file, "Weave._l = ",
0.1.11 by Martin Pool
Add Knit.dump method
347
        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.)
348
        print >>to_file, "Weave._v = ",
0.1.18 by Martin Pool
Better Knit.dump method
349
        pprint(self._v, to_file)
0.1.11 by Martin Pool
Add Knit.dump method
350
351
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
352
    def check(self):
353
        for vers_info in self._v:
354
            included = set()
355
            for vi in vers_info[0]:
356
                if vi < 0 or vi >= index:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
357
                    raise WeaveFormatError("invalid included version %d for index %d"
358
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
359
                if vi in included:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
360
                    raise WeaveFormatError("repeated included version %d for index %d"
361
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
362
                included.add(vi)
0.1.18 by Martin Pool
Better Knit.dump method
363
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
364
365
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
366
    def _delta(self, included, lines):
367
        """Return changes from basis to new revision.
368
369
        The old text for comparison is the union of included revisions.
370
371
        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.
372
0.1.55 by Martin Pool
doc
373
        Delta is returned as a sequence of
374
        (weave1, weave2, newlines).
375
376
        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.
377
        replaced by the sequence of lines in newlines.  Note that
378
        these line numbers are positions in the total weave and don't
379
        correspond to the lines in any extracted version, or even the
380
        extracted union of included versions.
381
382
        If line1=line2, this is a pure insert; if newlines=[] this is a
383
        pure delete.  (Similar to difflib.)
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
384
        """
385
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
386
        self._check_versions(included)
387
0.1.23 by Martin Pool
tidy up
388
        ##from pprint import pprint
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
389
390
        # first get basis for comparison
391
        # basis holds (lineno, origin, line)
392
        basis = []
393
0.1.23 by Martin Pool
tidy up
394
        ##print 'my lines:'
395
        ##pprint(self._l)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
396
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
397
        # 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
398
        basis = list(self._extract(included))
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
399
400
        # 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
401
        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.
402
403
        # 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
404
        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.
405
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
406
        # XXX: which line of the weave should we really consider
407
        # matches the end of the file?  the current code says it's the
408
        # last line of the weave?
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
409
410
        from difflib import SequenceMatcher
411
        s = SequenceMatcher(None, basis_lines, lines)
412
0.1.23 by Martin Pool
tidy up
413
        ##print 'basis sequence:'
414
        ##pprint(basis)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
415
0.1.55 by Martin Pool
doc
416
        # TODO: Perhaps return line numbers from composed weave as well?
417
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
418
        for tag, i1, i2, j1, j2 in s.get_opcodes():
0.1.23 by Martin Pool
tidy up
419
            ##print tag, i1, i2, j1, j2
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
420
421
            if tag == 'equal':
422
                continue
423
424
            # i1,i2 are given in offsets within basis_lines; we need to map them
425
            # back to offsets within the entire weave
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
426
            real_i1 = basis[i1][1]
427
            real_i2 = basis[i2][1]
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
428
0.1.35 by Martin Pool
Clean up Knit._delta method
429
            assert 0 <= j1
430
            assert j1 <= j2
431
            assert j2 <= len(lines)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
432
0.1.35 by Martin Pool
Clean up Knit._delta method
433
            yield real_i1, real_i2, lines[j1:j2]
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
434
0.1.1 by Martin Pool
Check in old existing knit code.
435
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
436
437
438
def main(argv):
439
    import sys
440
    import os
441
    from cPickle import dump, load
442
    cmd = argv[1]
443
    if cmd == 'add':
444
        w = load(file(argv[2], 'rb'))
445
        # at the moment, based on everything in the file
446
        parents = set(range(len(w._v)))
447
        ver = w.add(parents, sys.stdin.readlines())
448
        dump(w, file(argv[2], 'wb'))
449
        print 'added %d' % ver
450
    elif cmd == 'init':
451
        fn = argv[2]
452
        if os.path.exists(fn):
453
            raise IOError("file exists")
454
        w = Weave()
455
        dump(w, file(fn, 'wb'))
456
    elif cmd == 'get':
457
        w = load(file(argv[2], 'rb'))
458
        sys.stdout.writelines(w.get(int(argv[3])))
459
    elif cmd == 'annotate':
460
        w = load(file(argv[2], 'rb'))
461
        # assumes lines are ended
462
        lasto = None
463
        for origin, text in w.annotate(int(argv[3])):
464
            if text[-1] == '\n':
465
                text = text[:-1]
466
            if origin == lasto:
467
                print '      | %s' % (text)
468
            else:
469
                print '%5d | %s' % (origin, text)
470
                lasto = origin
471
    else:
472
        raise ValueError('unknown command %r' % cmd)
473
    
474
475
if __name__ == '__main__':
476
    import sys
477
    sys.exit(main(sys.argv))