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