/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.20 by Martin Pool
Factor out Knit.extract() method
275
        
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
276
        for l in self._l:
277
            if isinstance(l, tuple):
278
                c, v = l
279
                if c == '{':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
280
                    if istack and (istack[-1] >= v):
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
281
                        raise WeaveFormatError("improperly nested insertions %d>=%d on line %d" 
0.1.48 by Martin Pool
Basic parsing of delete instructions.
282
                                               % (istack[-1], v, lineno))
283
                    istack.append(v)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
284
                elif c == '}':
0.1.48 by Martin Pool
Basic parsing of delete instructions.
285
                    try:
286
                        oldv = istack.pop()
287
                    except IndexError:
288
                        raise WeaveFormatError("unmatched close of insertion %d on line %d"
289
                                               % (v, lineno))
290
                    if oldv != v:
291
                        raise WeaveFormatError("mismatched close of insertion %d!=%d on line %d"
292
                                               % (oldv, v, lineno))
293
                elif c == '[':
294
                    # block deleted in v
295
                    if v in dset:
296
                        raise WeaveFormatError("repeated deletion marker for version %d on line %d"
297
                                               % (v, lineno))
0.1.49 by Martin Pool
Add another constraint: revisions should not delete text that they
298
                    if istack:
299
                        if istack[-1] == v:
300
                            raise WeaveFormatError("version %d deletes own text on line %d"
301
                                                   % (v, lineno))
0.1.48 by Martin Pool
Basic parsing of delete instructions.
302
                        dset.add(v)
303
                elif c == ']':
304
                    if v in dset:
305
                        dset.remove(v)
306
                    else:
307
                        raise WeaveFormatError("unmatched close of deletion %d on line %d"
308
                                               % (v, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
309
                else:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
310
                    raise WeaveFormatError("invalid processing instruction %r on line %d"
311
                                           % (l, lineno))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
312
            else:
313
                assert isinstance(l, basestring)
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
314
                if not istack:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
315
                    raise WeaveFormatError("literal at top level on line %d"
316
                                           % lineno)
0.1.50 by Martin Pool
Basic implementation of deletion markers
317
                isactive = (istack[-1] in included) \
318
                           and not included.intersection(dset)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
319
                if isactive:
0.1.48 by Martin Pool
Basic parsing of delete instructions.
320
                    origin = istack[-1]
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
321
                    yield origin, lineno, l
322
            lineno += 1
0.1.7 by Martin Pool
Add trivial annotate text
323
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
324
        if istack:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
325
            raise WeaveFormatError("unclosed insertion blocks at end of weave",
326
                                   istack)
0.1.48 by Martin Pool
Basic parsing of delete instructions.
327
        if dset:
328
            raise WeaveFormatError("unclosed deletion blocks at end of weave",
329
                                   dset)
0.1.40 by Martin Pool
Add test for extracting from weave with nested insertions
330
0.1.7 by Martin Pool
Add trivial annotate text
331
0.1.5 by Martin Pool
Add test for storing two text versions.
332
    def getiter(self, index):
333
        """Yield lines for the specified version."""
0.1.8 by Martin Pool
Unify get/annotate code
334
        for origin, line in self.annotate_iter(index):
335
            yield line
0.1.5 by Martin Pool
Add test for storing two text versions.
336
337
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
338
    def get(self, index):
0.1.5 by Martin Pool
Add test for storing two text versions.
339
        return list(self.getiter(index))
0.1.1 by Martin Pool
Check in old existing knit code.
340
341
0.1.11 by Martin Pool
Add Knit.dump method
342
    def dump(self, to_file):
343
        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.)
344
        print >>to_file, "Weave._l = ",
0.1.11 by Martin Pool
Add Knit.dump method
345
        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.)
346
        print >>to_file, "Weave._v = ",
0.1.18 by Martin Pool
Better Knit.dump method
347
        pprint(self._v, to_file)
0.1.11 by Martin Pool
Add Knit.dump method
348
349
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
350
    def check(self):
351
        for vers_info in self._v:
352
            included = set()
353
            for vi in vers_info[0]:
354
                if vi < 0 or vi >= index:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
355
                    raise WeaveFormatError("invalid included version %d for index %d"
356
                                               % (vi, index))
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
357
                if vi in included:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
358
                    raise WeaveFormatError("repeated 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
                included.add(vi)
0.1.18 by Martin Pool
Better Knit.dump method
361
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
362
363
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
364
    def _delta(self, included, lines):
365
        """Return changes from basis to new revision.
366
367
        The old text for comparison is the union of included revisions.
368
369
        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.
370
0.1.55 by Martin Pool
doc
371
        Delta is returned as a sequence of
372
        (weave1, weave2, newlines).
373
374
        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.
375
        replaced by the sequence of lines in newlines.  Note that
376
        these line numbers are positions in the total weave and don't
377
        correspond to the lines in any extracted version, or even the
378
        extracted union of included versions.
379
380
        If line1=line2, this is a pure insert; if newlines=[] this is a
381
        pure delete.  (Similar to difflib.)
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
382
        """
383
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
384
        self._check_versions(included)
385
0.1.23 by Martin Pool
tidy up
386
        ##from pprint import pprint
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
387
388
        # first get basis for comparison
389
        # basis holds (lineno, origin, line)
390
        basis = []
391
0.1.23 by Martin Pool
tidy up
392
        ##print 'my lines:'
393
        ##pprint(self._l)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
394
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
395
        # 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
396
        basis = list(self._extract(included))
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
397
398
        # 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
399
        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.
400
401
        # 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
402
        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.
403
404
        # XXX: which line of the weave should we really consider matches the end of the file?
405
        # the current code says it's the last line of the weave?
406
407
        from difflib import SequenceMatcher
408
        s = SequenceMatcher(None, basis_lines, lines)
409
0.1.23 by Martin Pool
tidy up
410
        ##print 'basis sequence:'
411
        ##pprint(basis)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
412
0.1.55 by Martin Pool
doc
413
        # TODO: Perhaps return line numbers from composed weave as well?
414
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
415
        for tag, i1, i2, j1, j2 in s.get_opcodes():
0.1.23 by Martin Pool
tidy up
416
            ##print tag, i1, i2, j1, j2
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
417
418
            if tag == 'equal':
419
                continue
420
421
            # i1,i2 are given in offsets within basis_lines; we need to map them
422
            # back to offsets within the entire weave
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
423
            real_i1 = basis[i1][1]
424
            real_i2 = basis[i2][1]
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
425
0.1.35 by Martin Pool
Clean up Knit._delta method
426
            assert 0 <= j1
427
            assert j1 <= j2
428
            assert j2 <= len(lines)
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
            yield real_i1, real_i2, lines[j1:j2]
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
431
0.1.1 by Martin Pool
Check in old existing knit code.
432
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
433
434
435
def main(argv):
436
    import sys
437
    import os
438
    from cPickle import dump, load
439
    cmd = argv[1]
440
    if cmd == 'add':
441
        w = load(file(argv[2], 'rb'))
442
        # at the moment, based on everything in the file
443
        parents = set(range(len(w._v)))
444
        ver = w.add(parents, sys.stdin.readlines())
445
        dump(w, file(argv[2], 'wb'))
446
        print 'added %d' % ver
447
    elif cmd == 'init':
448
        fn = argv[2]
449
        if os.path.exists(fn):
450
            raise IOError("file exists")
451
        w = Weave()
452
        dump(w, file(fn, 'wb'))
453
    elif cmd == 'get':
454
        w = load(file(argv[2], 'rb'))
455
        sys.stdout.writelines(w.get(int(argv[3])))
456
    elif cmd == 'annotate':
457
        w = load(file(argv[2], 'rb'))
458
        # assumes lines are ended
459
        lasto = None
460
        for origin, text in w.annotate(int(argv[3])):
461
            if text[-1] == '\n':
462
                text = text[:-1]
463
            if origin == lasto:
464
                print '      | %s' % (text)
465
            else:
466
                print '%5d | %s' % (origin, text)
467
                lasto = origin
468
    else:
469
        raise ValueError('unknown command %r' % cmd)
470
    
471
472
if __name__ == '__main__':
473
    import sys
474
    sys.exit(main(sys.argv))