~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/weave.py

  • Committer: Martin Pool
  • Date: 2005-07-11 03:40:02 UTC
  • Revision ID: mbp@sourcefrog.net-20050711034002-575d84b4c7514542
- commit command refuses unless something is changed or --unchanged is given

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
 
22
22
"""Weave - storage of related text file versions"""
23
23
 
 
24
# TODO: Perhaps have copy method for Weave instances?
24
25
 
25
26
# XXX: If we do weaves this way, will a merge still behave the same
26
27
# way if it's done in a different order?  That's a pretty desirable
27
28
# property.
28
29
 
 
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
 
29
33
# TODO: Nothing here so far assumes the lines are really \n newlines,
30
34
# rather than being split up in some other way.  We could accomodate
31
35
# binaries, perhaps by naively splitting on \n or perhaps using
32
36
# something like a rolling checksum.
33
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?
 
45
 
 
46
# TODO: Separate out some code to read and write weaves.
 
47
 
34
48
# TODO: End marker for each version so we can stop reading?
35
49
 
36
50
# TODO: Check that no insertion occurs inside a deletion that was
37
51
# active in the version of the insertion.
38
52
 
39
 
# TODO: In addition to the SHA-1 check, perhaps have some code that
40
 
# checks structural constraints of the weave: ie that insertions are
41
 
# properly nested, that there is no text outside of an insertion, that
42
 
# insertions or deletions are not repeated, etc.
43
 
 
44
 
# TODO: Parallel-extract that passes back each line along with a
45
 
# description of which revisions include it.  Nice for checking all
46
 
# shas or calculating stats in parallel.
47
 
 
48
 
# TODO: Using a single _extract routine and then processing the output
49
 
# is probably inefficient.  It's simple enough that we can afford to
50
 
# have slight specializations for different ways its used: annotate,
51
 
# basis for add, get, etc.
52
 
 
53
 
# TODO: Perhaps the API should work only in names to hide the integer
54
 
# indexes from the user?
55
 
 
56
 
# TODO: Is there any potential performance win by having an add()
57
 
# variant that is passed a pre-cooked version of the single basis
58
 
# version?
59
 
 
60
 
# TODO: Have a way to go back and insert a revision V1 that is a parent 
61
 
# of an already-stored revision V2.  This means some lines previously 
62
 
# counted as new in V2 will be discovered to have actually come from V1.  
63
 
# It is probably necessary to insert V1, then compute a whole new diff 
64
 
# from the mashed ancestors to V2.  This must be repeated for every 
65
 
# direct child of V1.  The deltas from V2 to its descendents won't change,
66
 
# although their location within the weave may change.  It may be possible
67
 
# to just adjust the location of those instructions rather than 
68
 
# re-weaving the whole thing.  This is expected to be a fairly rare
69
 
# operation, only used when inserting data that was previously a ghost.
70
 
 
71
 
 
72
 
 
73
 
 
74
 
import sha
75
 
from difflib import SequenceMatcher
76
 
 
77
 
 
 
53
# TODO: Perhaps a special slower check() method that verifies more
 
54
# nesting constraints and the MD5 of each version?
 
55
 
 
56
 
 
57
 
 
58
try:
 
59
    set
 
60
    frozenset
 
61
except NameError:
 
62
    from sets import Set, ImmutableSet
 
63
    set = Set
 
64
    frozenset = ImmutableSet
 
65
    del Set, ImmutableSet
78
66
 
79
67
 
80
68
class WeaveError(Exception):
106
94
    the version-id is used to reference it in the larger world.
107
95
 
108
96
    The weave is represented as a list mixing edit instructions and
109
 
    literal text.  Each entry in _weave can be either a string (or
 
97
    literal text.  Each entry in _l can be either a string (or
110
98
    unicode), or a tuple.  If a string, it means that the given line
111
99
    should be output in the currently active revisions.
112
100
 
117
105
    The instruction can be '{' or '}' for an insertion block, and '['
118
106
    and ']' for a deletion block respectively.  The version is the
119
107
    integer version index.  There is no replace operator, only deletes
120
 
    and inserts.  For '}', the end of an insertion, there is no
121
 
    version parameter because it always closes the most recently
122
 
    opened insertion.
 
108
    and inserts.
123
109
 
124
110
    Constraints/notes:
125
111
 
152
138
      should be no way to get an earlier version deleting a later
153
139
      version.
154
140
 
155
 
    _weave
156
 
        Text of the weave; list of control instruction tuples and strings.
157
 
 
158
 
    _parents
159
 
        List of parents, indexed by version number.
160
 
        It is only necessary to store the minimal set of parents for
161
 
        each version; the parent's parents are implied.
 
141
    _l
 
142
        Text of the weave. 
 
143
 
 
144
    _v
 
145
        List of versions, indexed by index number.
 
146
 
 
147
        For each version we store the set (included_versions), which
 
148
        lists the previous versions also considered active; the
 
149
        versions included in those versions are included transitively.
 
150
        So new versions created from nothing list []; most versions
 
151
        have a single entry; some have more.
162
152
 
163
153
    _sha1s
164
 
        List of hex SHA-1 of each version.
165
 
 
166
 
    _names
167
 
        List of symbolic names for each version.  Each should be unique.
168
 
 
169
 
    _name_map
170
 
        For each name, the version number.
171
 
 
172
 
    _weave_name
173
 
        Descriptive name of this weave; typically the filename if known.
174
 
        Set by read_weave.
 
154
        List of hex SHA-1 of each version, or None if not recorded.
175
155
    """
176
 
 
177
 
    __slots__ = ['_weave', '_parents', '_sha1s', '_names', '_name_map',
178
 
                 '_weave_name']
179
 
    
180
 
    def __init__(self, weave_name=None):
181
 
        self._weave = []
182
 
        self._parents = []
 
156
    def __init__(self):
 
157
        self._l = []
 
158
        self._v = []
183
159
        self._sha1s = []
184
 
        self._names = []
185
 
        self._name_map = {}
186
 
        self._weave_name = weave_name
187
 
 
188
 
 
189
 
    def copy(self):
190
 
        """Return a deep copy of self.
191
 
        
192
 
        The copy can be modified without affecting the original weave."""
193
 
        other = Weave()
194
 
        other._weave = self._weave[:]
195
 
        other._parents = self._parents[:]
196
 
        other._sha1s = self._sha1s[:]
197
 
        other._names = self._names[:]
198
 
        other._name_map = self._name_map.copy()
199
 
        other._weave_name = self._weave_name
200
 
        return other
 
160
 
201
161
 
202
162
    def __eq__(self, other):
203
163
        if not isinstance(other, Weave):
204
164
            return False
205
 
        return self._parents == other._parents \
206
 
               and self._weave == other._weave \
207
 
               and self._sha1s == other._sha1s 
 
165
        return self._v == other._v \
 
166
               and self._l == other._l
 
167
    
208
168
 
209
 
    
210
169
    def __ne__(self, other):
211
170
        return not self.__eq__(other)
212
171
 
213
 
 
214
 
    def maybe_lookup(self, name_or_index):
215
 
        """Convert possible symbolic name to index, or pass through indexes."""
216
 
        if isinstance(name_or_index, (int, long)):
217
 
            return name_or_index
218
 
        else:
219
 
            return self.lookup(name_or_index)
220
 
 
221
 
        
222
 
    def lookup(self, name):
223
 
        """Convert symbolic version name to index."""
224
 
        try:
225
 
            return self._name_map[name]
226
 
        except KeyError:
227
 
            raise WeaveError("name %r not present in weave %r" %
228
 
                             (name, self._weave_name))
229
 
 
230
 
 
231
 
    def iter_names(self):
232
 
        """Yield a list of all names in this weave."""
233
 
        return iter(self._names)
234
 
 
235
 
    def idx_to_name(self, version):
236
 
        return self._names[version]
237
 
 
238
 
 
239
 
    def _check_repeated_add(self, name, parents, text, sha1):
240
 
        """Check that a duplicated add is OK.
241
 
 
242
 
        If it is, return the (old) index; otherwise raise an exception.
243
 
        """
244
 
        idx = self.lookup(name)
245
 
        if sorted(self._parents[idx]) != sorted(parents):
246
 
            raise WeaveError("name \"%s\" already present in weave "
247
 
                             "with different parents" % name)
248
 
        if sha1 != self._sha1s[idx]:
249
 
            raise WeaveError("name \"%s\" already present in weave "
250
 
                             "with different text" % name)            
251
 
        return idx
252
 
        
253
 
 
254
 
        
255
 
    def add(self, name, parents, text, sha1=None):
 
172
        
 
173
    def add(self, parents, text):
256
174
        """Add a single text on top of the weave.
257
175
  
258
176
        Returns the index number of the newly added version.
259
177
 
260
 
        name
261
 
            Symbolic name for this version.
262
 
            (Typically the revision-id of the revision that added it.)
263
 
 
264
178
        parents
265
 
            List or set of direct parent version numbers.
266
 
            
 
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.
 
181
 
267
182
        text
268
 
            Sequence of lines to be added in the new version.
269
 
 
270
 
        sha -- SHA-1 of the file, if known.  This is trusted to be
271
 
            correct if supplied.
272
 
        """
273
 
        from bzrlib.osutils import sha_strings
274
 
 
275
 
        assert isinstance(name, basestring)
276
 
        if sha1 is None:
277
 
            sha1 = sha_strings(text)
278
 
        if name in self._name_map:
279
 
            return self._check_repeated_add(name, parents, text, sha1)
280
 
 
281
 
        parents = map(self.maybe_lookup, parents)
282
 
        self._check_versions(parents)
 
183
            Sequence of lines to be added in the new version."""
 
184
        ## self._check_versions(parents)
283
185
        ## self._check_lines(text)
284
 
        new_version = len(self._parents)
285
 
 
286
 
 
287
 
        # if we abort after here the (in-memory) weave will be corrupt because only
288
 
        # some fields are updated
289
 
        self._parents.append(parents[:])
 
186
        idx = len(self._v)
 
187
 
 
188
        import sha
 
189
        s = sha.new()
 
190
        for l in text:
 
191
            s.update(l)
 
192
        sha1 = s.hexdigest()
 
193
        del s
 
194
 
 
195
        if parents:
 
196
            delta = self._delta(self.inclusions(parents), text)
 
197
 
 
198
            # offset gives the number of lines that have been inserted
 
199
            # into the weave up to the current point; if the original edit instruction
 
200
            # says to change line A then we actually change (A+offset)
 
201
            offset = 0
 
202
 
 
203
            for i1, i2, newlines in delta:
 
204
                assert 0 <= i1
 
205
                assert i1 <= i2
 
206
                assert i2 <= len(self._l)
 
207
 
 
208
                # the deletion and insertion are handled separately.
 
209
                # first delete the region.
 
210
                if i1 != i2:
 
211
                    self._l.insert(i1+offset, ('[', idx))
 
212
                    self._l.insert(i2+offset+1, (']', idx))
 
213
                    offset += 2
 
214
                    # is this OK???
 
215
 
 
216
                if newlines:
 
217
                    # there may have been a deletion spanning up to
 
218
                    # i2; we want to insert after this region to make sure
 
219
                    # we don't destroy ourselves
 
220
                    i = i2 + offset
 
221
                    self._l[i:i] = [('{', idx)] \
 
222
                                   + newlines \
 
223
                                   + [('}', idx)]
 
224
                    offset += 2 + len(newlines)
 
225
 
 
226
            self._addversion(parents)
 
227
        else:
 
228
            # special case; adding with no parents revision; can do this
 
229
            # more quickly by just appending unconditionally
 
230
            self._l.append(('{', idx))
 
231
            self._l += text
 
232
            self._l.append(('}', idx))
 
233
 
 
234
            self._addversion(None)
 
235
 
290
236
        self._sha1s.append(sha1)
291
 
        self._names.append(name)
292
 
        self._name_map[name] = new_version
293
 
 
294
 
            
295
 
        if not parents:
296
 
            # special case; adding with no parents revision; can do
297
 
            # this more quickly by just appending unconditionally.
298
 
            # even more specially, if we're adding an empty text we
299
 
            # need do nothing at all.
300
 
            if text:
301
 
                self._weave.append(('{', new_version))
302
 
                self._weave.extend(text)
303
 
                self._weave.append(('}', None))
304
 
        
305
 
            return new_version
306
 
 
307
 
        if len(parents) == 1:
308
 
            pv = list(parents)[0]
309
 
            if sha1 == self._sha1s[pv]:
310
 
                # special case: same as the single parent
311
 
                return new_version
312
 
            
313
 
 
314
 
        ancestors = self.inclusions(parents)
315
 
 
316
 
        l = self._weave
317
 
 
318
 
        # basis a list of (origin, lineno, line)
319
 
        basis_lineno = []
320
 
        basis_lines = []
321
 
        for origin, lineno, line in self._extract(ancestors):
322
 
            basis_lineno.append(lineno)
323
 
            basis_lines.append(line)
324
 
 
325
 
        # another small special case: a merge, producing the same text
326
 
        # as auto-merge
327
 
        if text == basis_lines:
328
 
            return new_version            
329
 
 
330
 
        # add a sentinal, because we can also match against the final line
331
 
        basis_lineno.append(len(self._weave))
332
 
 
333
 
        # XXX: which line of the weave should we really consider
334
 
        # matches the end of the file?  the current code says it's the
335
 
        # last line of the weave?
336
 
 
337
 
        #print 'basis_lines:', basis_lines
338
 
        #print 'new_lines:  ', lines
339
 
 
340
 
        s = SequenceMatcher(None, basis_lines, text)
341
 
 
342
 
        # offset gives the number of lines that have been inserted
343
 
        # into the weave up to the current point; if the original edit instruction
344
 
        # says to change line A then we actually change (A+offset)
345
 
        offset = 0
346
 
 
347
 
        for tag, i1, i2, j1, j2 in s.get_opcodes():
348
 
            # i1,i2 are given in offsets within basis_lines; we need to map them
349
 
            # back to offsets within the entire weave
350
 
            #print 'raw match', tag, i1, i2, j1, j2
351
 
            if tag == 'equal':
352
 
                continue
353
 
 
354
 
            i1 = basis_lineno[i1]
355
 
            i2 = basis_lineno[i2]
356
 
 
357
 
            assert 0 <= j1 <= j2 <= len(text)
358
 
 
359
 
            #print tag, i1, i2, j1, j2
360
 
 
361
 
            # the deletion and insertion are handled separately.
362
 
            # first delete the region.
363
 
            if i1 != i2:
364
 
                self._weave.insert(i1+offset, ('[', new_version))
365
 
                self._weave.insert(i2+offset+1, (']', new_version))
366
 
                offset += 2
367
 
 
368
 
            if j1 != j2:
369
 
                # there may have been a deletion spanning up to
370
 
                # i2; we want to insert after this region to make sure
371
 
                # we don't destroy ourselves
372
 
                i = i2 + offset
373
 
                self._weave[i:i] = ([('{', new_version)] 
374
 
                                    + text[j1:j2] 
375
 
                                    + [('}', None)])
376
 
                offset += 2 + (j2 - j1)
377
 
 
378
 
        return new_version
379
 
 
380
 
    def add_identical(self, old_rev_id, new_rev_id, parents):
381
 
        """Add an identical text to old_rev_id as new_rev_id."""
382
 
        old_lines = self.get(self.lookup(old_rev_id))
383
 
        self.add(new_rev_id, parents, old_lines)
 
237
            
 
238
        return idx
 
239
 
384
240
 
385
241
    def inclusions(self, versions):
386
 
        """Return set of all ancestors of given version(s)."""
 
242
        """Expand out everything included by versions."""
387
243
        i = set(versions)
388
 
        for v in xrange(max(versions), 0, -1):
389
 
            if v in i:
390
 
                # include all its parents
391
 
                i.update(self._parents[v])
 
244
        for v in versions:
 
245
            try:
 
246
                i.update(self._v[v])
 
247
            except IndexError:
 
248
                raise ValueError("version %d not present in weave" % v)
392
249
        return i
393
 
        ## except IndexError:
394
 
        ##     raise ValueError("version %d not present in weave" % v)
395
 
 
396
 
 
397
 
    def parents(self, version):
398
 
        return self._parents[version]
399
 
 
400
 
 
401
 
    def minimal_parents(self, version):
402
 
        """Find the minimal set of parents for the version."""
403
 
        included = self._parents[version]
404
 
        if not included:
405
 
            return []
406
 
        
407
 
        li = list(included)
408
 
        li.sort(reverse=True)
409
 
 
410
 
        mininc = []
411
 
        gotit = set()
412
 
 
413
 
        for pv in li:
414
 
            if pv not in gotit:
415
 
                mininc.append(pv)
416
 
                gotit.update(self.inclusions(pv))
417
 
 
418
 
        assert mininc[0] >= 0
419
 
        assert mininc[-1] < version
420
 
        return mininc
421
 
 
 
250
 
 
251
 
 
252
    def _addversion(self, parents):
 
253
        if parents:
 
254
            self._v.append(frozenset(parents))
 
255
        else:
 
256
            self._v.append(frozenset())
422
257
 
423
258
 
424
259
    def _check_lines(self, text):
436
271
        """Check everything in the sequence of indexes is valid"""
437
272
        for i in indexes:
438
273
            try:
439
 
                self._parents[i]
 
274
                self._v[i]
440
275
            except IndexError:
441
276
                raise IndexError("invalid version number %r" % i)
442
277
 
443
278
    
444
 
    def annotate(self, name_or_index):
445
 
        return list(self.annotate_iter(name_or_index))
446
 
 
447
 
 
448
 
    def annotate_iter(self, name_or_index):
 
279
    def annotate(self, index):
 
280
        return list(self.annotate_iter(index))
 
281
 
 
282
 
 
283
    def annotate_iter(self, version):
449
284
        """Yield list of (index-id, line) pairs for the specified version.
450
285
 
451
286
        The index indicates when the line originated in the weave."""
452
 
        incls = [self.maybe_lookup(name_or_index)]
453
 
        for origin, lineno, text in self._extract(incls):
 
287
        included = self.inclusions([version])
 
288
        for origin, lineno, text in self._extract(included):
454
289
            yield origin, text
455
290
 
456
291
 
457
 
    def _walk(self):
458
 
        """Walk the weave.
459
 
 
460
 
        Yields sequence of
461
 
        (lineno, insert, deletes, text)
462
 
        for each literal line.
463
 
        """
464
 
        
465
 
        istack = []
466
 
        dset = set()
467
 
 
468
 
        lineno = 0         # line of weave, 0-based
469
 
 
470
 
        for l in self._weave:
471
 
            if isinstance(l, tuple):
472
 
                c, v = l
473
 
                isactive = None
474
 
                if c == '{':
475
 
                    istack.append(v)
476
 
                elif c == '}':
477
 
                    istack.pop()
478
 
                elif c == '[':
479
 
                    assert v not in dset
480
 
                    dset.add(v)
481
 
                elif c == ']':
482
 
                    dset.remove(v)
483
 
                else:
484
 
                    raise WeaveFormatError('unexpected instruction %r'
485
 
                                           % v)
486
 
            else:
487
 
                assert isinstance(l, basestring)
488
 
                assert istack
489
 
                yield lineno, istack[-1], dset, l
490
 
            lineno += 1
491
 
 
492
 
 
493
 
 
494
 
    def _extract(self, versions):
 
292
    def _extract(self, included):
495
293
        """Yield annotation of lines in included set.
496
294
 
497
295
        Yields a sequence of tuples (origin, lineno, text), where
500
298
 
501
299
        The set typically but not necessarily corresponds to a version.
502
300
        """
503
 
        for i in versions:
504
 
            if not isinstance(i, int):
505
 
                raise ValueError(i)
506
 
            
507
 
        included = self.inclusions(versions)
508
301
 
509
302
        istack = []
510
303
        dset = set()
511
304
 
512
305
        lineno = 0         # line of weave, 0-based
513
 
 
514
 
        isactive = None
515
 
 
516
 
        result = []
 
306
        isactive = False
517
307
 
518
308
        WFE = WeaveFormatError
519
309
 
520
 
        for l in self._weave:
 
310
        for l in self._l:
521
311
            if isinstance(l, tuple):
522
312
                c, v = l
523
 
                isactive = None
524
 
                if c == '{':
525
 
                    assert v not in istack
526
 
                    istack.append(v)
527
 
                elif c == '}':
528
 
                    istack.pop()
529
 
                elif c == '[':
530
 
                    if v in included:
 
313
                if v in included:       # only active blocks are interesting
 
314
                    if c == '{':
 
315
                        assert v not in istack
 
316
                        istack.append(v)
 
317
                        isactive = not dset
 
318
                    elif c == '}':
 
319
                        oldv = istack.pop()
 
320
                        assert oldv == v
 
321
                        isactive = istack and not dset
 
322
                    elif c == '[':
531
323
                        assert v not in dset
532
324
                        dset.add(v)
533
 
                else:
534
 
                    assert c == ']'
535
 
                    if v in included:
 
325
                        isactive = False
 
326
                    else:
 
327
                        assert c == ']'
536
328
                        assert v in dset
537
329
                        dset.remove(v)
 
330
                        isactive = istack and not dset
538
331
            else:
539
332
                assert isinstance(l, basestring)
540
 
                if isactive is None:
541
 
                    isactive = (not dset) and istack and (istack[-1] in included)
542
333
                if isactive:
543
 
                    result.append((istack[-1], lineno, l))
 
334
                    yield origin, lineno, l
544
335
            lineno += 1
545
336
 
546
337
        if istack:
550
341
            raise WFE("unclosed deletion blocks at end of weave",
551
342
                                   dset)
552
343
 
553
 
        return result
554
 
    
555
 
 
556
 
 
557
 
    def get_iter(self, name_or_index):
 
344
 
 
345
    def get_iter(self, version):
558
346
        """Yield lines for the specified version."""
559
 
        incls = [self.maybe_lookup(name_or_index)]
560
 
        for origin, lineno, line in self._extract(incls):
 
347
        for origin, lineno, line in self._extract(self.inclusions([version])):
561
348
            yield line
562
349
 
563
350
 
564
 
    def get_text(self, name_or_index):
565
 
        return ''.join(self.get_iter(name_or_index))
566
 
        assert isinstance(version, int)
567
 
 
568
 
 
569
 
    def get_lines(self, name_or_index):
570
 
        return list(self.get_iter(name_or_index))
571
 
 
572
 
 
573
 
    get = get_lines
 
351
    def get(self, index):
 
352
        return list(self.get_iter(index))
574
353
 
575
354
 
576
355
    def mash_iter(self, included):
577
356
        """Return composed version of multiple included versions."""
578
 
        included = map(self.maybe_lookup, included)
 
357
        included = frozenset(included)
579
358
        for origin, lineno, text in self._extract(included):
580
359
            yield text
581
360
 
582
361
 
583
362
    def dump(self, to_file):
584
363
        from pprint import pprint
585
 
        print >>to_file, "Weave._weave = ",
586
 
        pprint(self._weave, to_file)
587
 
        print >>to_file, "Weave._parents = ",
588
 
        pprint(self._parents, to_file)
 
364
        print >>to_file, "Weave._l = ",
 
365
        pprint(self._l, to_file)
 
366
        print >>to_file, "Weave._v = ",
 
367
        pprint(self._v, to_file)
589
368
 
590
369
 
591
370
 
592
371
    def numversions(self):
593
 
        l = len(self._parents)
 
372
        l = len(self._v)
594
373
        assert l == len(self._sha1s)
595
374
        return l
596
375
 
597
376
 
598
 
    def __len__(self):
599
 
        return self.numversions()
600
 
 
601
 
 
602
 
    def check(self, progress_bar=None):
 
377
    def check(self):
603
378
        # check no circular inclusions
604
379
        for version in range(self.numversions()):
605
 
            inclusions = list(self._parents[version])
 
380
            inclusions = list(self._v[version])
606
381
            if inclusions:
607
382
                inclusions.sort()
608
383
                if inclusions[-1] >= version:
611
386
 
612
387
        # try extracting all versions; this is a bit slow and parallel
613
388
        # extraction could be used
614
 
        nv = self.numversions()
615
 
        for version in range(nv):
616
 
            if progress_bar:
617
 
                progress_bar.update('checking text', version, nv)
 
389
        import sha
 
390
        for version in range(self.numversions()):
618
391
            s = sha.new()
619
392
            for l in self.get_iter(version):
620
393
                s.update(l)
641
414
        If there is a chunk of the file where there's no diagreement,
642
415
        only one alternative is given.
643
416
        """
 
417
 
644
418
        # approach: find the included versions common to all the
645
419
        # merged versions
646
420
        raise NotImplementedError()
666
440
        If line1=line2, this is a pure insert; if newlines=[] this is a
667
441
        pure delete.  (Similar to difflib.)
668
442
        """
669
 
        raise NotImplementedError()
670
 
 
671
 
            
672
 
    def plan_merge(self, ver_a, ver_b):
673
 
        """Return pseudo-annotation indicating how the two versions merge.
674
 
 
675
 
        This is computed between versions a and b and their common
676
 
        base.
677
 
 
678
 
        Weave lines present in none of them are skipped entirely.
679
 
        """
680
 
        inc_a = self.inclusions([ver_a])
681
 
        inc_b = self.inclusions([ver_b])
682
 
        inc_c = inc_a & inc_b
683
 
 
684
 
        for lineno, insert, deleteset, line in self._walk():
685
 
            if deleteset & inc_c:
686
 
                # killed in parent; can't be in either a or b
687
 
                # not relevant to our work
688
 
                yield 'killed-base', line
689
 
            elif insert in inc_c:
690
 
                # was inserted in base
691
 
                killed_a = bool(deleteset & inc_a)
692
 
                killed_b = bool(deleteset & inc_b)
693
 
                if killed_a and killed_b:
694
 
                    yield 'killed-both', line
695
 
                elif killed_a:
696
 
                    yield 'killed-a', line
697
 
                elif killed_b:
698
 
                    yield 'killed-b', line
699
 
                else:
700
 
                    yield 'unchanged', line
701
 
            elif insert in inc_a:
702
 
                if deleteset & inc_a:
703
 
                    yield 'ghost-a', line
704
 
                else:
705
 
                    # new in A; not in B
706
 
                    yield 'new-a', line
707
 
            elif insert in inc_b:
708
 
                if deleteset & inc_b:
709
 
                    yield 'ghost-b', line
710
 
                else:
711
 
                    yield 'new-b', line
712
 
            else:
713
 
                # not in either revision
714
 
                yield 'irrelevant', line
715
 
 
716
 
        yield 'unchanged', ''           # terminator
717
 
 
718
 
 
719
 
 
720
 
    def weave_merge(self, plan):
721
 
        lines_a = []
722
 
        lines_b = []
723
 
        ch_a = ch_b = False
724
 
 
725
 
        for state, line in plan:
726
 
            if state == 'unchanged' or state == 'killed-both':
727
 
                # resync and flush queued conflicts changes if any
728
 
                if not lines_a and not lines_b:
729
 
                    pass
730
 
                elif ch_a and not ch_b:
731
 
                    # one-sided change:                    
732
 
                    for l in lines_a: yield l
733
 
                elif ch_b and not ch_a:
734
 
                    for l in lines_b: yield l
735
 
                elif lines_a == lines_b:
736
 
                    for l in lines_a: yield l
737
 
                else:
738
 
                    yield '<<<<\n'
739
 
                    for l in lines_a: yield l
740
 
                    yield '====\n'
741
 
                    for l in lines_b: yield l
742
 
                    yield '>>>>\n'
743
 
 
744
 
                del lines_a[:]
745
 
                del lines_b[:]
746
 
                ch_a = ch_b = False
747
 
                
748
 
            if state == 'unchanged':
749
 
                if line:
750
 
                    yield line
751
 
            elif state == 'killed-a':
752
 
                ch_a = True
753
 
                lines_b.append(line)
754
 
            elif state == 'killed-b':
755
 
                ch_b = True
756
 
                lines_a.append(line)
757
 
            elif state == 'new-a':
758
 
                ch_a = True
759
 
                lines_a.append(line)
760
 
            elif state == 'new-b':
761
 
                ch_b = True
762
 
                lines_b.append(line)
763
 
            else:
764
 
                assert state in ('irrelevant', 'ghost-a', 'ghost-b', 'killed-base',
765
 
                                 'killed-both'), \
766
 
                       state
767
 
 
768
 
                
769
 
    def join(self, other):
770
 
        """Integrate versions from other into this weave.
771
 
 
772
 
        The resulting weave contains all the history of both weaves; 
773
 
        any version you could retrieve from either self or other can be 
774
 
        retrieved from self after this call.
775
 
 
776
 
        It is illegal for the two weaves to contain different values 
777
 
        for any version.
778
 
        """
779
 
        if other.numversions() == 0:
780
 
            return          # nothing to update, easy
781
 
        # work through in index order to make sure we get all dependencies
782
 
        for other_idx, name in enumerate(other._names):
783
 
            # TODO: If all the parents of the other version are already 
784
 
            # present then we can avoid some work by just taking the delta
785
 
            # and adjusting the offsets.
786
 
            if self._check_version_consistent(other, other_idx, name):
 
443
        # basis a list of (origin, lineno, line)
 
444
        basis_lineno = []
 
445
        basis_lines = []
 
446
        for origin, lineno, line in self._extract(included):
 
447
            basis_lineno.append(lineno)
 
448
            basis_lines.append(line)
 
449
 
 
450
        # add a sentinal, because we can also match against the final line
 
451
        basis_lineno.append(len(self._l))
 
452
 
 
453
        # XXX: which line of the weave should we really consider
 
454
        # matches the end of the file?  the current code says it's the
 
455
        # last line of the weave?
 
456
 
 
457
        from difflib import SequenceMatcher
 
458
        s = SequenceMatcher(None, basis_lines, lines)
 
459
 
 
460
        # TODO: Perhaps return line numbers from composed weave as well?
 
461
 
 
462
        for tag, i1, i2, j1, j2 in s.get_opcodes():
 
463
            ##print tag, i1, i2, j1, j2
 
464
 
 
465
            if tag == 'equal':
787
466
                continue
788
 
            new_parents = self._imported_parents(other, other_idx)
789
 
            lines = other.get_lines(other_idx)
790
 
            sha1 = other._sha1s[other_idx]
791
 
            self.add(name, new_parents, lines, sha1)
792
 
 
793
 
 
794
 
    def _imported_parents(self, other, other_idx):
795
 
        """Return list of parents in self corresponding to indexes in other."""
796
 
        new_parents = []
797
 
        for parent_idx in other._parents[other_idx]:
798
 
            parent_name = other._names[parent_idx]
799
 
            if parent_name not in self._names:
800
 
                # should not be possible
801
 
                raise WeaveError("missing parent {%s} of {%s} in %r" 
802
 
                                 % (parent_name, other._name_map[other_idx], self))
803
 
            new_parents.append(self._name_map[parent_name])
804
 
        return new_parents
805
 
 
806
 
    def _check_version_consistent(self, other, other_idx, name):
807
 
        """Check if a version in consistent in this and other.
808
 
 
809
 
        To be consistent it must have:
810
 
 
811
 
         * the same text
812
 
         * the same direct parents (by name, not index, and disregarding
813
 
           order)
814
 
        
815
 
        If present & correct return True;
816
 
        if not present in self return False; 
817
 
        if inconsistent raise error."""
818
 
        this_idx = self._name_map.get(name, -1)
819
 
        if this_idx != -1:
820
 
            if self._sha1s[this_idx] != other._sha1s[other_idx]:
821
 
                raise WeaveError("inconsistent texts for version {%s} "
822
 
                                 "when joining weaves"
823
 
                                 % (name))
824
 
            self_parents = self._parents[this_idx]
825
 
            other_parents = other._parents[other_idx]
826
 
            n1 = [self._names[i] for i in self_parents]
827
 
            n2 = [other._names[i] for i in other_parents]
828
 
            n1.sort()
829
 
            n2.sort()
830
 
            if n1 != n2:
831
 
                raise WeaveError("inconsistent parents for version {%s}: "
832
 
                                 "%s vs %s"
833
 
                                 % (name, n1, n2))
834
 
            else:
835
 
                return True         # ok!
836
 
        else:
837
 
            return False
838
 
 
839
 
 
840
 
def weave_toc(w):
841
 
    """Show the weave's table-of-contents"""
842
 
    print '%6s %50s %10s %10s' % ('ver', 'name', 'sha1', 'parents')
843
 
    for i in (6, 50, 10, 10):
844
 
        print '-' * i,
845
 
    print
846
 
    for i in range(w.numversions()):
847
 
        sha1 = w._sha1s[i]
848
 
        name = w._names[i]
849
 
        parent_str = ' '.join(map(str, w._parents[i]))
850
 
        print '%6d %-50.50s %10.10s %s' % (i, name, sha1, parent_str)
851
 
 
852
 
 
853
 
 
854
 
def weave_stats(weave_file, pb):
855
 
    from bzrlib.weavefile import read_weave
856
 
 
857
 
    wf = file(weave_file, 'rb')
 
467
 
 
468
            # i1,i2 are given in offsets within basis_lines; we need to map them
 
469
            # back to offsets within the entire weave
 
470
            real_i1 = basis_lineno[i1]
 
471
            real_i2 = basis_lineno[i2]
 
472
 
 
473
            assert 0 <= j1
 
474
            assert j1 <= j2
 
475
            assert j2 <= len(lines)
 
476
 
 
477
            yield real_i1, real_i2, lines[j1:j2]
 
478
 
 
479
 
 
480
 
 
481
def weave_info(filename, out):
 
482
    """Show some text information about the weave."""
 
483
    from weavefile import read_weave
 
484
    wf = file(filename, 'rb')
858
485
    w = read_weave(wf)
859
486
    # FIXME: doesn't work on pipes
860
487
    weave_size = wf.tell()
 
488
    print >>out, "weave file size %d bytes" % weave_size
 
489
    print >>out, "weave contains %d versions" % len(w._v)
861
490
 
862
491
    total = 0
863
 
    vers = len(w)
864
 
    for i in range(vers):
865
 
        pb.update('checking sizes', i, vers)
866
 
        for origin, lineno, line in w._extract([i]):
867
 
            total += len(line)
868
 
 
869
 
    pb.clear()
870
 
 
871
 
    print 'versions          %9d' % vers
872
 
    print 'weave file        %9d bytes' % weave_size
873
 
    print 'total contents    %9d bytes' % total
874
 
    print 'compression ratio %9.2fx' % (float(total) / float(weave_size))
875
 
    if vers:
876
 
        avg = total/vers
877
 
        print 'average size      %9d bytes' % avg
878
 
        print 'relative size     %9.2fx' % (float(weave_size) / float(avg))
 
492
    print '%6s %6s %8s %40s %20s' % ('ver', 'lines', 'bytes', 'sha1', 'parents')
 
493
    for i in (6, 6, 8, 40, 20):
 
494
        print '-' * i,
 
495
    print
 
496
    for i in range(len(w._v)):
 
497
        text = w.get(i)
 
498
        lines = len(text)
 
499
        bytes = sum((len(a) for a in text))
 
500
        sha1 = w._sha1s[i]
 
501
        print '%6d %6d %8d %40s' % (i, lines, bytes, sha1),
 
502
        print ', '.join(map(str, w._v[i]))
 
503
        total += bytes
 
504
 
 
505
    print >>out, "versions total %d bytes" % total
 
506
    print >>out, "compression ratio %.3f" % (float(total)/float(weave_size))
879
507
 
880
508
 
881
509
def usage():
890
518
        Write out specified version.
891
519
    weave check WEAVEFILE
892
520
        Check consistency of all versions.
893
 
    weave toc WEAVEFILE
 
521
    weave info WEAVEFILE
894
522
        Display table of contents.
895
 
    weave add WEAVEFILE NAME [BASE...] < NEWTEXT
 
523
    weave add WEAVEFILE [BASE...] < NEWTEXT
896
524
        Add NEWTEXT, with specified parent versions.
897
525
    weave annotate WEAVEFILE VERSION
898
526
        Display origin of each line.
900
528
        Display composite of all selected versions.
901
529
    weave merge WEAVEFILE VERSION1 VERSION2 > OUT
902
530
        Auto-merge two versions and display conflicts.
903
 
    weave diff WEAVEFILE VERSION1 VERSION2 
904
 
        Show differences between two versions.
905
531
 
906
532
example:
907
533
 
908
534
    % weave init foo.weave
909
535
    % vi foo.txt
910
 
    % weave add foo.weave ver0 < foo.txt
 
536
    % weave add foo.weave < foo.txt
911
537
    added version 0
912
538
 
913
539
    (create updated version)
914
540
    % vi foo.txt
915
541
    % weave get foo.weave 0 | diff -u - foo.txt
916
 
    % weave add foo.weave ver1 0 < foo.txt
 
542
    % weave add foo.weave 0 < foo.txt
917
543
    added version 1
918
544
 
919
545
    % weave get foo.weave 0 > foo.txt       (create forked version)
920
546
    % vi foo.txt
921
 
    % weave add foo.weave ver2 0 < foo.txt
 
547
    % weave add foo.weave 0 < foo.txt
922
548
    added version 2
923
549
 
924
550
    % weave merge foo.weave 1 2 > foo.txt   (merge them)
925
551
    % vi foo.txt                            (resolve conflicts)
926
 
    % weave add foo.weave merged 1 2 < foo.txt     (commit merged version)     
 
552
    % weave add foo.weave 1 2 < foo.txt     (commit merged version)     
927
553
    
928
554
"""
929
555
    
932
558
def main(argv):
933
559
    import sys
934
560
    import os
935
 
    try:
936
 
        import bzrlib
937
 
    except ImportError:
938
 
        # in case we're run directly from the subdirectory
939
 
        sys.path.append('..')
940
 
        import bzrlib
941
 
    from bzrlib.weavefile import write_weave, read_weave
942
 
    from bzrlib.progress import ProgressBar
943
 
 
944
 
    try:
945
 
        import psyco
946
 
        psyco.full()
947
 
    except ImportError:
948
 
        pass
949
 
 
950
 
    if len(argv) < 2:
951
 
        usage()
952
 
        return 0
953
 
 
 
561
    from weavefile import write_weave, read_weave
954
562
    cmd = argv[1]
955
563
 
956
564
    def readit():
961
569
    elif cmd == 'add':
962
570
        w = readit()
963
571
        # at the moment, based on everything in the file
964
 
        name = argv[3]
965
 
        parents = map(int, argv[4:])
 
572
        parents = map(int, argv[3:])
966
573
        lines = sys.stdin.readlines()
967
 
        ver = w.add(name, parents, lines)
 
574
        ver = w.add(parents, lines)
968
575
        write_weave(w, file(argv[2], 'wb'))
969
 
        print 'added version %r %d' % (name, ver)
 
576
        print 'added version %d' % ver
970
577
    elif cmd == 'init':
971
578
        fn = argv[2]
972
579
        if os.path.exists(fn):
981
588
        w = readit()
982
589
        sys.stdout.writelines(w.mash_iter(map(int, argv[3:])))
983
590
 
984
 
    elif cmd == 'diff':
985
 
        from difflib import unified_diff
986
 
        w = readit()
987
 
        fn = argv[2]
988
 
        v1, v2 = map(int, argv[3:5])
989
 
        lines1 = w.get(v1)
990
 
        lines2 = w.get(v2)
991
 
        diff_gen = unified_diff(lines1, lines2,
992
 
                                '%s version %d' % (fn, v1),
993
 
                                '%s version %d' % (fn, v2))
994
 
        sys.stdout.writelines(diff_gen)
995
 
            
996
591
    elif cmd == 'annotate':
997
592
        w = readit()
998
593
        # newline is added to all lines regardless; too hard to get
1006
601
                print '%5d | %s' % (origin, text)
1007
602
                lasto = origin
1008
603
                
1009
 
    elif cmd == 'toc':
1010
 
        weave_toc(readit())
1011
 
 
1012
 
    elif cmd == 'stats':
1013
 
        weave_stats(argv[2], ProgressBar())
 
604
    elif cmd == 'info':
 
605
        weave_info(argv[2], sys.stdout)
1014
606
        
1015
607
    elif cmd == 'check':
1016
608
        w = readit()
1017
 
        pb = ProgressBar()
1018
 
        w.check(pb)
1019
 
        pb.clear()
1020
 
        print '%d versions ok' % w.numversions()
1021
 
 
1022
 
    elif cmd == 'inclusions':
1023
 
        w = readit()
1024
 
        print ' '.join(map(str, w.inclusions([int(argv[3])])))
1025
 
 
1026
 
    elif cmd == 'parents':
1027
 
        w = readit()
1028
 
        print ' '.join(map(str, w._parents[int(argv[3])]))
1029
 
 
1030
 
    elif cmd == 'plan-merge':
1031
 
        w = readit()
1032
 
        for state, line in w.plan_merge(int(argv[3]), int(argv[4])):
1033
 
            if line:
1034
 
                print '%14s | %s' % (state, line),
 
609
        w.check()
1035
610
 
1036
611
    elif cmd == 'merge':
1037
 
        w = readit()
1038
 
        p = w.plan_merge(int(argv[3]), int(argv[4]))
1039
 
        sys.stdout.writelines(w.weave_merge(p))
1040
 
            
1041
 
    elif cmd == 'mash-merge':
1042
612
        if len(argv) != 5:
1043
613
            usage()
1044
614
            return 1
1062
632
        raise ValueError('unknown command %r' % cmd)
1063
633
    
1064
634
 
1065
 
 
1066
 
def profile_main(argv): 
1067
 
    import tempfile, hotshot, hotshot.stats
1068
 
 
1069
 
    prof_f = tempfile.NamedTemporaryFile()
1070
 
 
1071
 
    prof = hotshot.Profile(prof_f.name)
1072
 
 
1073
 
    ret = prof.runcall(main, argv)
1074
 
    prof.close()
1075
 
 
1076
 
    stats = hotshot.stats.load(prof_f.name)
1077
 
    #stats.strip_dirs()
1078
 
    stats.sort_stats('cumulative')
1079
 
    ## XXX: Might like to write to stderr or the trace file instead but
1080
 
    ## print_stats seems hardcoded to stdout
1081
 
    stats.print_stats(20)
1082
 
            
1083
 
    return ret
1084
 
 
1085
 
 
1086
635
if __name__ == '__main__':
1087
636
    import sys
1088
 
    if '--profile' in sys.argv:
1089
 
        args = sys.argv[:]
1090
 
        args.remove('--profile')
1091
 
        sys.exit(profile_main(args))
1092
 
    else:
1093
 
        sys.exit(main(sys.argv))
1094
 
 
 
637
    sys.exit(main(sys.argv))