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