/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: Nothing here so far assumes the lines are really \n newlines,
31
# rather than being split up in some other way.  We could accomodate
32
# binaries, perhaps by naively splitting on \n or perhaps using
33
# something like a rolling checksum.
34
35
# TODO: Track version names as well as indexes. 
36
0.1.85 by Martin Pool
doc
37
# TODO: End marker for each version so we can stop reading?
0.1.69 by Martin Pool
Simple text-based format for storing weaves, cleaner than
38
39
# TODO: Check that no insertion occurs inside a deletion that was
40
# active in the version of the insertion.
41
912 by Martin Pool
- update todos for weave
42
# TODO: In addition to the SHA-1 check, perhaps have some code that
43
# checks structural constraints of the weave: ie that insertions are
44
# properly nested, that there is no text outside of an insertion, that
45
# insertions or deletions are not repeated, etc.
0.1.85 by Martin Pool
doc
46
47
0.1.34 by Martin Pool
remove dead code
48
0.1.66 by Martin Pool
Cope without set/frozenset classes
49
try:
50
    set
51
    frozenset
52
except NameError:
53
    from sets import Set, ImmutableSet
54
    set = Set
55
    frozenset = ImmutableSet
0.1.67 by Martin Pool
More fixes to try to run on python2.3
56
    del Set, ImmutableSet
0.1.66 by Martin Pool
Cope without set/frozenset classes
57
58
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
59
class WeaveError(Exception):
60
    """Exception in processing weave"""
61
62
63
class WeaveFormatError(WeaveError):
64
    """Weave invariant violated"""
65
    
66
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
67
class Weave(object):
68
    """weave - versioned text file storage.
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
69
    
0.1.72 by Martin Pool
Go back to weave lines normally having newlines at the end.
70
    A Weave manages versions of line-based text files, keeping track
71
    of the originating version for each line.
72
73
    To clients the "lines" of the file are represented as a list of strings.
74
    These strings  will typically have terminal newline characters, but
75
    this is not required.  In particular files commonly do not have a newline
76
    at the end of the file.
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
77
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
78
    Texts can be identified in either of two ways:
79
80
    * a nonnegative index number.
81
82
    * a version-id string.
83
0.1.38 by Martin Pool
Rename knit to weave. (I don't think there's an existing module called weave.)
84
    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.
85
    the version-id is used to reference it in the larger world.
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
86
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
87
    The weave is represented as a list mixing edit instructions and
88
    literal text.  Each entry in _l can be either a string (or
89
    unicode), or a tuple.  If a string, it means that the given line
90
    should be output in the currently active revisions.
91
92
    If a tuple, it gives a processing instruction saying in which
93
    revisions the enclosed lines are active.  The tuple has the form
94
    (instruction, version).
95
96
    The instruction can be '{' or '}' for an insertion block, and '['
97
    and ']' for a deletion block respectively.  The version is the
0.1.45 by Martin Pool
doc
98
    integer version index.  There is no replace operator, only deletes
99
    and inserts.
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
100
0.1.41 by Martin Pool
Doc
101
    Constraints/notes:
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
102
103
    * A later version can delete lines that were introduced by any
104
      number of ancestor versions; this implies that deletion
105
      instructions can span insertion blocks without regard to the
106
      insertion block's nesting.
107
0.1.41 by Martin Pool
Doc
108
    * Similarly, deletions need not be properly nested with regard to
109
      each other, because they might have been generated by
110
      independent revisions.
111
0.1.45 by Martin Pool
doc
112
    * Insertions are always made by inserting a new bracketed block
113
      into a single point in the previous weave.  This implies they
114
      can nest but not overlap, and the nesting must always have later
115
      insertions on the inside.
116
0.1.41 by Martin Pool
Doc
117
    * It doesn't seem very useful to have an active insertion
118
      inside an inactive insertion, but it might happen.
0.1.45 by Martin Pool
doc
119
      
0.1.41 by Martin Pool
Doc
120
    * Therefore, all instructions are always"considered"; that
121
      is passed onto and off the stack.  An outer inactive block
122
      doesn't disable an inner block.
123
124
    * Lines are enabled if the most recent enclosing insertion is
125
      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
126
0.1.49 by Martin Pool
Add another constraint: revisions should not delete text that they
127
    * There is no point having a deletion directly inside its own
128
      insertion; you might as well just not write it.  And there
129
      should be no way to get an earlier version deleting a later
130
      version.
131
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
132
    _l
892 by Martin Pool
- weave stores only direct parents, and calculates and memoizes expansion as needed
133
        Text of the weave.
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
134
135
    _v
892 by Martin Pool
- weave stores only direct parents, and calculates and memoizes expansion as needed
136
        List of parents, indexed by version number.
137
        It is only necessary to store the minimal set of parents for
138
        each version; the parent's parents are implied.
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
139
0.1.89 by Martin Pool
Store SHA1 in weave file for later verification
140
    _sha1s
141
        List of hex SHA-1 of each version, or None if not recorded.
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
142
    """
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
143
    def __init__(self):
144
        self._l = []
145
        self._v = []
0.1.89 by Martin Pool
Store SHA1 in weave file for later verification
146
        self._sha1s = []
0.1.60 by Martin Pool
Weave eq and ne methods
147
148
149
    def __eq__(self, other):
150
        if not isinstance(other, Weave):
151
            return False
152
        return self._v == other._v \
153
               and self._l == other._l
154
    
155
156
    def __ne__(self, other):
157
        return not self.__eq__(other)
158
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
159
        
0.1.26 by Martin Pool
Refactor parameters to add command
160
    def add(self, parents, text):
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
161
        """Add a single text on top of the weave.
0.1.36 by Martin Pool
doc
162
  
0.1.26 by Martin Pool
Refactor parameters to add command
163
        Returns the index number of the newly added version.
164
165
        parents
892 by Martin Pool
- weave stores only direct parents, and calculates and memoizes expansion as needed
166
            List or set of direct parent version numbers.
167
            
0.1.26 by Martin Pool
Refactor parameters to add command
168
        text
169
            Sequence of lines to be added in the new version."""
0.1.82 by Martin Pool
Small weave optimizations
170
        ## self._check_versions(parents)
171
        ## self._check_lines(text)
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
172
        idx = len(self._v)
0.1.5 by Martin Pool
Add test for storing two text versions.
173
0.1.89 by Martin Pool
Store SHA1 in weave file for later verification
174
        import sha
175
        s = sha.new()
176
        for l in text:
177
            s.update(l)
178
        sha1 = s.hexdigest()
179
        del s
180
0.1.26 by Martin Pool
Refactor parameters to add command
181
        if parents:
892 by Martin Pool
- weave stores only direct parents, and calculates and memoizes expansion as needed
182
            ancestors = self.inclusions(parents)
183
            delta = self._delta(ancestors, text)
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
184
0.1.31 by Martin Pool
Fix insertion of multiple regions, calculating the right line offset as we go.
185
            # offset gives the number of lines that have been inserted
186
            # into the weave up to the current point; if the original edit instruction
187
            # says to change line A then we actually change (A+offset)
188
            offset = 0
189
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
190
            for i1, i2, newlines in delta:
0.1.29 by Martin Pool
Better internal error
191
                assert 0 <= i1
192
                assert i1 <= i2
193
                assert i2 <= len(self._l)
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
194
195
                # the deletion and insertion are handled separately.
196
                # first delete the region.
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
197
                if i1 != i2:
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
198
                    self._l.insert(i1+offset, ('[', idx))
199
                    self._l.insert(i2+offset+1, (']', idx))
200
                    offset += 2
201
                    # is this OK???
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
202
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
203
                if newlines:
0.1.57 by Martin Pool
Fix bug in an update edit that both deletes and inserts -- previously
204
                    # there may have been a deletion spanning up to
205
                    # i2; we want to insert after this region to make sure
206
                    # we don't destroy ourselves
207
                    i = i2 + offset
0.1.56 by Martin Pool
Handle deletion of lines by marking the region with a deletion
208
                    self._l[i:i] = [('{', idx)] \
209
                                   + newlines \
210
                                   + [('}', idx)]
211
                    offset += 2 + len(newlines)
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
212
0.1.75 by Martin Pool
Remove VerInfo class; just store sets directly in the list of
213
            self._addversion(parents)
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
214
        else:
0.1.26 by Martin Pool
Refactor parameters to add command
215
            # 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
216
            # more quickly by just appending unconditionally
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
217
            self._l.append(('{', idx))
218
            self._l += text
219
            self._l.append(('}', idx))
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
220
0.1.75 by Martin Pool
Remove VerInfo class; just store sets directly in the list of
221
            self._addversion(None)
0.1.89 by Martin Pool
Store SHA1 in weave file for later verification
222
223
        self._sha1s.append(sha1)
0.1.25 by Martin Pool
Handle insertion of new weave layers that insert text on top of the basis
224
            
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
225
        return idx
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
226
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
227
0.1.78 by Martin Pool
Rename Weave.get_included to inclusions and getiter to get_iter
228
    def inclusions(self, versions):
893 by Martin Pool
- Refactor weave calculation of inclusions
229
        """Return set of all ancestors of given version(s)."""
0.1.78 by Martin Pool
Rename Weave.get_included to inclusions and getiter to get_iter
230
        i = set(versions)
893 by Martin Pool
- Refactor weave calculation of inclusions
231
        v = max(versions)
892 by Martin Pool
- weave stores only direct parents, and calculates and memoizes expansion as needed
232
        try:
893 by Martin Pool
- Refactor weave calculation of inclusions
233
            while v >= 0:
234
                if v in i:
235
                    # include all its parents
236
                    i.update(self._v[v])
237
                v -= 1
238
            return i
892 by Martin Pool
- weave stores only direct parents, and calculates and memoizes expansion as needed
239
        except IndexError:
240
            raise ValueError("version %d not present in weave" % v)
0.1.77 by Martin Pool
New Weave.get_included() does transitive expansion
241
242
890 by Martin Pool
- weave info should show minimal expression of parents
243
    def minimal_parents(self, version):
244
        """Find the minimal set of parents for the version."""
245
        included = self._v[version]
246
        if not included:
247
            return []
248
        
249
        li = list(included)
893 by Martin Pool
- Refactor weave calculation of inclusions
250
        li.sort(reverse=True)
890 by Martin Pool
- weave info should show minimal expression of parents
251
252
        mininc = []
253
        gotit = set()
254
255
        for pv in li:
256
            if pv not in gotit:
257
                mininc.append(pv)
893 by Martin Pool
- Refactor weave calculation of inclusions
258
                gotit.update(self.inclusions(pv))
890 by Martin Pool
- weave info should show minimal expression of parents
259
260
        assert mininc[0] >= 0
261
        assert mininc[-1] < version
262
        return mininc
263
264
0.1.75 by Martin Pool
Remove VerInfo class; just store sets directly in the list of
265
    def _addversion(self, parents):
266
        if parents:
892 by Martin Pool
- weave stores only direct parents, and calculates and memoizes expansion as needed
267
            self._v.append(parents)
0.1.75 by Martin Pool
Remove VerInfo class; just store sets directly in the list of
268
        else:
269
            self._v.append(frozenset())
270
271
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
272
    def _check_lines(self, text):
273
        if not isinstance(text, list):
274
            raise ValueError("text should be a list, not %s" % type(text))
275
276
        for l in text:
277
            if not isinstance(l, basestring):
869 by Martin Pool
- more weave.py command line options
278
                raise ValueError("text line should be a string or unicode, not %s"
279
                                 % type(l))
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
280
        
281
282
0.1.27 by Martin Pool
Check that version numbers passed in are reasonable
283
    def _check_versions(self, indexes):
284
        """Check everything in the sequence of indexes is valid"""
285
        for i in indexes:
286
            try:
287
                self._v[i]
288
            except IndexError:
289
                raise IndexError("invalid version number %r" % i)
290
0.1.2 by Martin Pool
Import testsweet module adapted from bzr.
291
    
0.1.7 by Martin Pool
Add trivial annotate text
292
    def annotate(self, index):
293
        return list(self.annotate_iter(index))
294
295
0.1.78 by Martin Pool
Rename Weave.get_included to inclusions and getiter to get_iter
296
    def annotate_iter(self, version):
0.1.7 by Martin Pool
Add trivial annotate text
297
        """Yield list of (index-id, line) pairs for the specified version.
298
299
        The index indicates when the line originated in the weave."""
893 by Martin Pool
- Refactor weave calculation of inclusions
300
        for origin, lineno, text in self._extract([version]):
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
301
            yield origin, text
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
302
303
893 by Martin Pool
- Refactor weave calculation of inclusions
304
    def _extract(self, versions):
0.1.20 by Martin Pool
Factor out Knit.extract() method
305
        """Yield annotation of lines in included set.
306
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
307
        Yields a sequence of tuples (origin, lineno, text), where
308
        origin is the origin version, lineno the index in the weave,
309
        and text the text of the line.
310
0.1.20 by Martin Pool
Factor out Knit.extract() method
311
        The set typically but not necessarily corresponds to a version.
312
        """
893 by Martin Pool
- Refactor weave calculation of inclusions
313
        included = self.inclusions(versions)
881 by Martin Pool
- faster weave extraction
314
315
        istack = []
316
        dset = set()
0.1.48 by Martin Pool
Basic parsing of delete instructions.
317
318
        lineno = 0         # line of weave, 0-based
891 by Martin Pool
- fix up refactoring of weave
319
894 by Martin Pool
- small optimization for weave extract
320
        isactive = None
0.1.85 by Martin Pool
doc
321
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
322
        WFE = WeaveFormatError
0.1.95 by Martin Pool
- preliminary merge conflict detection
323
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
324
        for l in self._l:
325
            if isinstance(l, tuple):
326
                c, v = l
894 by Martin Pool
- small optimization for weave extract
327
                isactive = None
891 by Martin Pool
- fix up refactoring of weave
328
                if c == '{':
329
                    assert v not in istack
330
                    istack.append(v)
331
                elif c == '}':
332
                    oldv = istack.pop()
333
                    assert oldv == v
334
                elif c == '[':
335
                    if v in included:
881 by Martin Pool
- faster weave extraction
336
                        assert v not in dset
0.1.48 by Martin Pool
Basic parsing of delete instructions.
337
                        dset.add(v)
891 by Martin Pool
- fix up refactoring of weave
338
                else:
339
                    assert c == ']'
340
                    if v in included:
881 by Martin Pool
- faster weave extraction
341
                        assert v in dset
0.1.48 by Martin Pool
Basic parsing of delete instructions.
342
                        dset.remove(v)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
343
            else:
344
                assert isinstance(l, basestring)
894 by Martin Pool
- small optimization for weave extract
345
                if isactive is None:
346
                    isactive = (not dset) and istack and (istack[-1] in included)
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
347
                if isactive:
888 by Martin Pool
- fix refactoring breakage
348
                    yield istack[-1], lineno, l
0.1.39 by Martin Pool
Change to a more realistic weave structure which can represent insertions and
349
            lineno += 1
0.1.7 by Martin Pool
Add trivial annotate text
350
0.1.46 by Martin Pool
More constraints on structure of weave, and checks that they work
351
        if istack:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
352
            raise WFE("unclosed insertion blocks at end of weave",
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
353
                                   istack)
0.1.48 by Martin Pool
Basic parsing of delete instructions.
354
        if dset:
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
355
            raise WFE("unclosed deletion blocks at end of weave",
0.1.48 by Martin Pool
Basic parsing of delete instructions.
356
                                   dset)
0.1.40 by Martin Pool
Add test for extracting from weave with nested insertions
357
0.1.7 by Martin Pool
Add trivial annotate text
358
0.1.78 by Martin Pool
Rename Weave.get_included to inclusions and getiter to get_iter
359
    def get_iter(self, version):
0.1.5 by Martin Pool
Add test for storing two text versions.
360
        """Yield lines for the specified version."""
893 by Martin Pool
- Refactor weave calculation of inclusions
361
        for origin, lineno, line in self._extract([version]):
0.1.8 by Martin Pool
Unify get/annotate code
362
            yield line
0.1.5 by Martin Pool
Add test for storing two text versions.
363
364
0.1.4 by Martin Pool
Start indexing knits by both integer and version string.
365
    def get(self, index):
0.1.78 by Martin Pool
Rename Weave.get_included to inclusions and getiter to get_iter
366
        return list(self.get_iter(index))
0.1.1 by Martin Pool
Check in old existing knit code.
367
368
0.1.95 by Martin Pool
- preliminary merge conflict detection
369
    def mash_iter(self, included):
0.1.65 by Martin Pool
Add Weave.merge_iter to get automerged lines
370
        """Return composed version of multiple included versions."""
371
        included = frozenset(included)
893 by Martin Pool
- Refactor weave calculation of inclusions
372
        for origin, lineno, text in self._extract(included):
0.1.65 by Martin Pool
Add Weave.merge_iter to get automerged lines
373
            yield text
374
375
0.1.11 by Martin Pool
Add Knit.dump method
376
    def dump(self, to_file):
377
        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.)
378
        print >>to_file, "Weave._l = ",
0.1.11 by Martin Pool
Add Knit.dump method
379
        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.)
380
        print >>to_file, "Weave._v = ",
0.1.18 by Martin Pool
Better Knit.dump method
381
        pprint(self._v, to_file)
0.1.11 by Martin Pool
Add Knit.dump method
382
383
0.1.91 by Martin Pool
Update Weave.check
384
385
    def numversions(self):
386
        l = len(self._v)
387
        assert l == len(self._sha1s)
388
        return l
389
390
894 by Martin Pool
- small optimization for weave extract
391
    def check(self, progress_bar=None):
0.1.91 by Martin Pool
Update Weave.check
392
        # check no circular inclusions
393
        for version in range(self.numversions()):
394
            inclusions = list(self._v[version])
395
            if inclusions:
396
                inclusions.sort()
397
                if inclusions[-1] >= version:
0.1.47 by Martin Pool
New WeaveError and WeaveFormatError rather than assertions.
398
                    raise WeaveFormatError("invalid included version %d for index %d"
0.1.91 by Martin Pool
Update Weave.check
399
                                           % (inclusions[-1], version))
400
401
        # try extracting all versions; this is a bit slow and parallel
402
        # extraction could be used
403
        import sha
894 by Martin Pool
- small optimization for weave extract
404
        nv = self.numversions()
405
        for version in range(nv):
406
            if progress_bar:
407
                progress_bar.update('checking text', version, nv)
0.1.91 by Martin Pool
Update Weave.check
408
            s = sha.new()
409
            for l in self.get_iter(version):
410
                s.update(l)
411
            hd = s.hexdigest()
412
            expected = self._sha1s[version]
413
            if hd != expected:
414
                raise WeaveError("mismatched sha1 for version %d; "
415
                                 "got %s, expected %s"
416
                                 % (version, hd, expected))
0.1.18 by Martin Pool
Better Knit.dump method
417
881 by Martin Pool
- faster weave extraction
418
        # TODO: check insertions are properly nested, that there are
419
        # no lines outside of insertion blocks, that deletions are
420
        # properly paired, etc.
421
0.1.13 by Martin Pool
Knit structure now allows for versions to include the lines present in other
422
423
0.1.95 by Martin Pool
- preliminary merge conflict detection
424
    def merge(self, merge_versions):
425
        """Automerge and mark conflicts between versions.
426
427
        This returns a sequence, each entry describing alternatives
428
        for a chunk of the file.  Each of the alternatives is given as
429
        a list of lines.
430
431
        If there is a chunk of the file where there's no diagreement,
432
        only one alternative is given.
433
        """
434
435
        # approach: find the included versions common to all the
436
        # merged versions
437
        raise NotImplementedError()
438
439
440
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
441
    def _delta(self, included, lines):
442
        """Return changes from basis to new revision.
443
444
        The old text for comparison is the union of included revisions.
445
446
        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.
447
0.1.55 by Martin Pool
doc
448
        Delta is returned as a sequence of
449
        (weave1, weave2, newlines).
450
451
        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.
452
        replaced by the sequence of lines in newlines.  Note that
453
        these line numbers are positions in the total weave and don't
454
        correspond to the lines in any extracted version, or even the
455
        extracted union of included versions.
456
457
        If line1=line2, this is a pure insert; if newlines=[] this is a
458
        pure delete.  (Similar to difflib.)
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
459
        """
0.1.54 by Martin Pool
Fix weave line calculation when making deltas
460
        # basis a list of (origin, lineno, line)
0.1.84 by Martin Pool
Refactor Weave._delta to calculate less unused information
461
        basis_lineno = []
0.1.83 by Martin Pool
Better delta basis calculation
462
        basis_lines = []
893 by Martin Pool
- Refactor weave calculation of inclusions
463
        for origin, lineno, line in self._extract(included):
0.1.84 by Martin Pool
Refactor Weave._delta to calculate less unused information
464
            basis_lineno.append(lineno)
465
            basis_lines.append(line)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
466
467
        # add a sentinal, because we can also match against the final line
0.1.84 by Martin Pool
Refactor Weave._delta to calculate less unused information
468
        basis_lineno.append(len(self._l))
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
469
0.1.63 by Martin Pool
Abbreviate WeaveFormatError in some code
470
        # XXX: which line of the weave should we really consider
471
        # matches the end of the file?  the current code says it's the
472
        # last line of the weave?
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
473
474
        from difflib import SequenceMatcher
475
        s = SequenceMatcher(None, basis_lines, lines)
476
0.1.55 by Martin Pool
doc
477
        # TODO: Perhaps return line numbers from composed weave as well?
478
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
479
        for tag, i1, i2, j1, j2 in s.get_opcodes():
0.1.23 by Martin Pool
tidy up
480
            ##print tag, i1, i2, j1, j2
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
481
482
            if tag == 'equal':
483
                continue
484
485
            # i1,i2 are given in offsets within basis_lines; we need to map them
486
            # back to offsets within the entire weave
0.1.84 by Martin Pool
Refactor Weave._delta to calculate less unused information
487
            real_i1 = basis_lineno[i1]
488
            real_i2 = basis_lineno[i2]
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
489
0.1.35 by Martin Pool
Clean up Knit._delta method
490
            assert 0 <= j1
491
            assert j1 <= j2
492
            assert j2 <= len(lines)
0.1.22 by Martin Pool
Calculate delta for new versions relative to a set of parent versions.
493
0.1.35 by Martin Pool
Clean up Knit._delta method
494
            yield real_i1, real_i2, lines[j1:j2]
0.1.21 by Martin Pool
Start computing a delta to insert a new revision
495
0.1.1 by Martin Pool
Check in old existing knit code.
496
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
497
0.1.88 by Martin Pool
Add weave info command.
498
def weave_info(filename, out):
499
    """Show some text information about the weave."""
500
    from weavefile import read_weave
501
    wf = file(filename, 'rb')
502
    w = read_weave(wf)
503
    # FIXME: doesn't work on pipes
504
    weave_size = wf.tell()
505
    print >>out, "weave file size %d bytes" % weave_size
506
    print >>out, "weave contains %d versions" % len(w._v)
507
508
    total = 0
870 by Martin Pool
- better weave info display
509
    print '%6s %6s %8s %40s %20s' % ('ver', 'lines', 'bytes', 'sha1', 'parents')
510
    for i in (6, 6, 8, 40, 20):
511
        print '-' * i,
512
    print
0.1.88 by Martin Pool
Add weave info command.
513
    for i in range(len(w._v)):
514
        text = w.get(i)
515
        lines = len(text)
516
        bytes = sum((len(a) for a in text))
0.1.91 by Martin Pool
Update Weave.check
517
        sha1 = w._sha1s[i]
870 by Martin Pool
- better weave info display
518
        print '%6d %6d %8d %40s' % (i, lines, bytes, sha1),
892 by Martin Pool
- weave stores only direct parents, and calculates and memoizes expansion as needed
519
        for pv in w._v[i]:
520
            print pv,
521
        print
0.1.88 by Martin Pool
Add weave info command.
522
        total += bytes
523
524
    print >>out, "versions total %d bytes" % total
525
    print >>out, "compression ratio %.3f" % (float(total)/float(weave_size))
869 by Martin Pool
- more weave.py command line options
526
527
528
def usage():
871 by Martin Pool
- add command for merge-based weave
529
    print """bzr weave tool
530
531
Experimental tool for weave algorithm.
532
869 by Martin Pool
- more weave.py command line options
533
usage:
534
    weave init WEAVEFILE
535
        Create an empty weave file
536
    weave get WEAVEFILE VERSION
537
        Write out specified version.
538
    weave check WEAVEFILE
539
        Check consistency of all versions.
540
    weave info WEAVEFILE
541
        Display table of contents.
542
    weave add WEAVEFILE [BASE...] < NEWTEXT
543
        Add NEWTEXT, with specified parent versions.
544
    weave annotate WEAVEFILE VERSION
545
        Display origin of each line.
546
    weave mash WEAVEFILE VERSION...
547
        Display composite of all selected versions.
548
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
549
        Auto-merge two versions and display conflicts.
871 by Martin Pool
- add command for merge-based weave
550
551
example:
552
553
    % weave init foo.weave
554
    % vi foo.txt
555
    % weave add foo.weave < foo.txt
556
    added version 0
557
558
    (create updated version)
559
    % vi foo.txt
560
    % weave get foo.weave 0 | diff -u - foo.txt
561
    % weave add foo.weave 0 < foo.txt
562
    added version 1
563
564
    % weave get foo.weave 0 > foo.txt       (create forked version)
565
    % vi foo.txt
566
    % weave add foo.weave 0 < foo.txt
567
    added version 2
568
569
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
570
    % vi foo.txt                            (resolve conflicts)
571
    % weave add foo.weave 1 2 < foo.txt     (commit merged version)     
572
    
869 by Martin Pool
- more weave.py command line options
573
"""
0.1.88 by Martin Pool
Add weave info command.
574
    
575
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
576
577
def main(argv):
578
    import sys
579
    import os
869 by Martin Pool
- more weave.py command line options
580
    from weavefile import write_weave, read_weave
894 by Martin Pool
- small optimization for weave extract
581
    from bzrlib.progress import ProgressBar
582
583
    #import psyco
584
    #psyco.full()
585
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
586
    cmd = argv[1]
869 by Martin Pool
- more weave.py command line options
587
588
    def readit():
589
        return read_weave(file(argv[2], 'rb'))
590
    
591
    if cmd == 'help':
592
        usage()
593
    elif cmd == 'add':
594
        w = readit()
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
595
        # at the moment, based on everything in the file
869 by Martin Pool
- more weave.py command line options
596
        parents = map(int, argv[3:])
0.1.72 by Martin Pool
Go back to weave lines normally having newlines at the end.
597
        lines = sys.stdin.readlines()
0.1.69 by Martin Pool
Simple text-based format for storing weaves, cleaner than
598
        ver = w.add(parents, lines)
869 by Martin Pool
- more weave.py command line options
599
        write_weave(w, file(argv[2], 'wb'))
600
        print 'added version %d' % ver
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
601
    elif cmd == 'init':
602
        fn = argv[2]
603
        if os.path.exists(fn):
604
            raise IOError("file exists")
605
        w = Weave()
869 by Martin Pool
- more weave.py command line options
606
        write_weave(w, file(fn, 'wb'))
607
    elif cmd == 'get': # get one version
608
        w = readit()
0.1.94 by Martin Pool
Fix get_iter call
609
        sys.stdout.writelines(w.get_iter(int(argv[3])))
869 by Martin Pool
- more weave.py command line options
610
        
611
    elif cmd == 'mash': # get composite
612
        w = readit()
613
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
614
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
615
    elif cmd == 'annotate':
869 by Martin Pool
- more weave.py command line options
616
        w = readit()
0.1.72 by Martin Pool
Go back to weave lines normally having newlines at the end.
617
        # newline is added to all lines regardless; too hard to get
618
        # reasonable formatting otherwise
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
619
        lasto = None
620
        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.
621
            text = text.rstrip('\r\n')
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
622
            if origin == lasto:
623
                print '      | %s' % (text)
624
            else:
625
                print '%5d | %s' % (origin, text)
626
                lasto = origin
871 by Martin Pool
- add command for merge-based weave
627
                
0.1.88 by Martin Pool
Add weave info command.
628
    elif cmd == 'info':
629
        weave_info(argv[2], sys.stdout)
871 by Martin Pool
- add command for merge-based weave
630
        
0.1.91 by Martin Pool
Update Weave.check
631
    elif cmd == 'check':
869 by Martin Pool
- more weave.py command line options
632
        w = readit()
894 by Martin Pool
- small optimization for weave extract
633
        pb = ProgressBar()
634
        w.check(pb)
635
        pb.clear()
871 by Martin Pool
- add command for merge-based weave
636
892 by Martin Pool
- weave stores only direct parents, and calculates and memoizes expansion as needed
637
    elif cmd == 'inclusions':
638
        w = readit()
639
        print ' '.join(map(str, w.inclusions([int(argv[3])])))
640
641
    elif cmd == 'parents':
642
        w = readit()
643
        print ' '.join(map(str, w._v[int(argv[3])]))
644
871 by Martin Pool
- add command for merge-based weave
645
    elif cmd == 'merge':
646
        if len(argv) != 5:
647
            usage()
648
            return 1
649
650
        w = readit()
651
        v1, v2 = map(int, argv[3:5])
652
653
        basis = w.inclusions([v1]).intersection(w.inclusions([v2]))
654
655
        base_lines = list(w.mash_iter(basis))
656
        a_lines = list(w.get(v1))
657
        b_lines = list(w.get(v2))
658
659
        from bzrlib.merge3 import Merge3
660
        m3 = Merge3(base_lines, a_lines, b_lines)
661
662
        name_a = 'version %d' % v1
663
        name_b = 'version %d' % v2
664
        sys.stdout.writelines(m3.merge_lines(name_a=name_a, name_b=name_b))
0.1.62 by Martin Pool
Lame command-line client for reading and writing weaves.
665
    else:
666
        raise ValueError('unknown command %r' % cmd)
667
    
668
669
if __name__ == '__main__':
670
    import sys
671
    sys.exit(main(sys.argv))