/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/merge3.py

  • Committer: Martin Pool
  • Date: 2008-04-24 07:22:53 UTC
  • mto: This revision was merged to the branch mainline in revision 3415.
  • Revision ID: mbp@sourcefrog.net-20080424072253-opmjij7xfy38w27f
Remove every assert statement from bzrlib!

Depending on the context they are:

 * turned into an explicit if/raise of either AssertionError 
   or something more specific -- particularly where they protect
   programming interfaces, complex invariants, or data file integrity
 * removed, if they're redundant with a later check, not protecting
   a meaningful invariant
 * turned into a selftest method on tests

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005 by Canonical Ltd
2
 
 
 
1
# Copyright (C) 2004, 2005 Canonical Ltd
 
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
 
 
7
#
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
 
 
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
19
# s: "i hate that."
20
20
 
21
21
 
 
22
from bzrlib.errors import CantReprocessAndShowBase
 
23
import bzrlib.patiencediff
 
24
from bzrlib.textfile import check_text_lines
 
25
 
22
26
 
23
27
def intersect(ra, rb):
24
28
    """Given two ranges return the range where they intersect or None.
32
36
    >>> intersect((0, 9), (7, 15))
33
37
    (7, 9)
34
38
    """
35
 
    assert ra[0] <= ra[1]
36
 
    assert rb[0] <= rb[1]
37
 
    
38
39
    sa = max(ra[0], rb[0])
39
40
    sb = min(ra[1], rb[1])
40
41
    if sa < sb:
63
64
    Given BASE, OTHER, THIS, tries to produce a combined text
64
65
    incorporating the changes from both BASE->OTHER and BASE->THIS.
65
66
    All three will typically be sequences of lines."""
66
 
    def __init__(self, base, a, b):
 
67
    def __init__(self, base, a, b, is_cherrypick=False):
 
68
        check_text_lines(base)
 
69
        check_text_lines(a)
 
70
        check_text_lines(b)
67
71
        self.base = base
68
72
        self.a = a
69
73
        self.b = b
70
 
        from difflib import SequenceMatcher
71
 
        self.a_ops = SequenceMatcher(None, base, a).get_opcodes()
72
 
        self.b_ops = SequenceMatcher(None, base, b).get_opcodes()
73
 
 
74
 
 
 
74
        self.is_cherrypick = is_cherrypick
75
75
 
76
76
    def merge_lines(self,
77
77
                    name_a=None,
78
78
                    name_b=None,
79
 
                    start_marker='<<<<<<<<',
80
 
                    mid_marker='========',
81
 
                    end_marker='>>>>>>>>',
82
 
                    show_base=False):
 
79
                    name_base=None,
 
80
                    start_marker='<<<<<<<',
 
81
                    mid_marker='=======',
 
82
                    end_marker='>>>>>>>',
 
83
                    base_marker=None,
 
84
                    reprocess=False):
83
85
        """Return merge in cvs-like form.
84
86
        """
 
87
        newline = '\n'
 
88
        if len(self.a) > 0:
 
89
            if self.a[0].endswith('\r\n'):
 
90
                newline = '\r\n'
 
91
            elif self.a[0].endswith('\r'):
 
92
                newline = '\r'
 
93
        if base_marker and reprocess:
 
94
            raise CantReprocessAndShowBase()
85
95
        if name_a:
86
96
            start_marker = start_marker + ' ' + name_a
87
97
        if name_b:
88
98
            end_marker = end_marker + ' ' + name_b
89
 
            
90
 
        for t in self.merge_regions():
 
99
        if name_base and base_marker:
 
100
            base_marker = base_marker + ' ' + name_base
 
101
        merge_regions = self.merge_regions()
 
102
        if reprocess is True:
 
103
            merge_regions = self.reprocess_merge_regions(merge_regions)
 
104
        for t in merge_regions:
91
105
            what = t[0]
92
106
            if what == 'unchanged':
93
107
                for i in range(t[1], t[2]):
99
113
                for i in range(t[1], t[2]):
100
114
                    yield self.b[i]
101
115
            elif what == 'conflict':
102
 
                yield start_marker + '\n'
 
116
                yield start_marker + newline
103
117
                for i in range(t[3], t[4]):
104
118
                    yield self.a[i]
105
 
                yield mid_marker + '\n'
 
119
                if base_marker is not None:
 
120
                    yield base_marker + newline
 
121
                    for i in range(t[1], t[2]):
 
122
                        yield self.base[i]
 
123
                yield mid_marker + newline
106
124
                for i in range(t[5], t[6]):
107
125
                    yield self.b[i]
108
 
                yield end_marker + '\n'
 
126
                yield end_marker + newline
109
127
            else:
110
128
                raise ValueError(what)
111
 
        
112
 
        
113
 
 
114
 
 
115
129
 
116
130
    def merge_annotated(self):
117
131
        """Return merge with conflicts, showing origin of lines.
139
153
                yield '>>>>\n'
140
154
            else:
141
155
                raise ValueError(what)
142
 
        
143
 
        
144
 
 
145
 
 
146
156
 
147
157
    def merge_groups(self):
148
158
        """Yield sequence of line groups.  Each one is a tuple:
178
188
            else:
179
189
                raise ValueError(what)
180
190
 
181
 
 
182
191
    def merge_regions(self):
183
192
        """Return sequences of matching and conflicting regions.
184
193
 
210
219
        iz = ia = ib = 0
211
220
        
212
221
        for zmatch, zend, amatch, aend, bmatch, bend in self.find_sync_regions():
213
 
            #print 'match base [%d:%d]' % (zmatch, zend)
214
 
            
215
222
            matchlen = zend - zmatch
216
 
            assert matchlen >= 0
217
 
            assert matchlen == (aend - amatch)
218
 
            assert matchlen == (bend - bmatch)
219
 
            
220
223
            len_a = amatch - ia
221
224
            len_b = bmatch - ib
222
225
            len_base = zmatch - iz
223
 
            assert len_a >= 0
224
 
            assert len_b >= 0
225
 
            assert len_base >= 0
226
 
 
227
226
            #print 'unmatched a=%d, b=%d' % (len_a, len_b)
228
227
 
229
228
            if len_a or len_b:
230
229
                # try to avoid actually slicing the lists
231
 
                equal_a = compare_range(self.a, ia, amatch,
232
 
                                        self.base, iz, zmatch)
233
 
                equal_b = compare_range(self.b, ib, bmatch,
234
 
                                        self.base, iz, zmatch)
235
230
                same = compare_range(self.a, ia, amatch,
236
231
                                     self.b, ib, bmatch)
237
232
 
238
233
                if same:
239
234
                    yield 'same', ia, amatch
240
 
                elif equal_a and not equal_b:
241
 
                    yield 'b', ib, bmatch
242
 
                elif equal_b and not equal_a:
243
 
                    yield 'a', ia, amatch
244
 
                elif not equal_a and not equal_b:
245
 
                    yield 'conflict', iz, zmatch, ia, amatch, ib, bmatch
246
235
                else:
247
 
                    raise AssertionError("can't handle a=b=base but unmatched")
 
236
                    equal_a = compare_range(self.a, ia, amatch,
 
237
                                            self.base, iz, zmatch)
 
238
                    equal_b = compare_range(self.b, ib, bmatch,
 
239
                                            self.base, iz, zmatch)
 
240
                    if equal_a and not equal_b:
 
241
                        yield 'b', ib, bmatch
 
242
                    elif equal_b and not equal_a:
 
243
                        yield 'a', ia, amatch
 
244
                    elif not equal_a and not equal_b:
 
245
                        if self.is_cherrypick:
 
246
                            for node in self._refine_cherrypick_conflict(
 
247
                                                    iz, zmatch, ia, amatch,
 
248
                                                    ib, bmatch):
 
249
                                yield node
 
250
                        else:
 
251
                            yield 'conflict', iz, zmatch, ia, amatch, ib, bmatch
 
252
                    else:
 
253
                        raise AssertionError("can't handle a=b=base but unmatched")
248
254
 
249
255
                ia = amatch
250
256
                ib = bmatch
253
259
            # if the same part of the base was deleted on both sides
254
260
            # that's OK, we can just skip it.
255
261
 
256
 
                
257
262
            if matchlen > 0:
258
 
                assert ia == amatch
259
 
                assert ib == bmatch
260
 
                assert iz == zmatch
261
 
                
262
263
                yield 'unchanged', zmatch, zend
263
264
                iz = zend
264
265
                ia = aend
265
266
                ib = bend
266
 
        
267
 
 
268
 
        
 
267
 
 
268
    def _refine_cherrypick_conflict(self, zstart, zend, astart, aend, bstart, bend):
 
269
        """When cherrypicking b => a, ignore matches with b and base."""
 
270
        # Do not emit regions which match, only regions which do not match
 
271
        matches = bzrlib.patiencediff.PatienceSequenceMatcher(None,
 
272
            self.base[zstart:zend], self.b[bstart:bend]).get_matching_blocks()
 
273
        last_base_idx = 0
 
274
        last_b_idx = 0
 
275
        last_b_idx = 0
 
276
        yielded_a = False
 
277
        for base_idx, b_idx, match_len in matches:
 
278
            conflict_z_len = base_idx - last_base_idx
 
279
            conflict_b_len = b_idx - last_b_idx
 
280
            if conflict_b_len == 0: # There are no lines in b which conflict,
 
281
                                    # so skip it
 
282
                pass
 
283
            else:
 
284
                if yielded_a:
 
285
                    yield ('conflict',
 
286
                           zstart + last_base_idx, zstart + base_idx,
 
287
                           aend, aend, bstart + last_b_idx, bstart + b_idx)
 
288
                else:
 
289
                    # The first conflict gets the a-range
 
290
                    yielded_a = True
 
291
                    yield ('conflict', zstart + last_base_idx, zstart +
 
292
                    base_idx,
 
293
                           astart, aend, bstart + last_b_idx, bstart + b_idx)
 
294
            last_base_idx = base_idx + match_len
 
295
            last_b_idx = b_idx + match_len
 
296
        if last_base_idx != zend - zstart or last_b_idx != bend - bstart:
 
297
            if yielded_a:
 
298
                yield ('conflict', zstart + last_base_idx, zstart + base_idx,
 
299
                       aend, aend, bstart + last_b_idx, bstart + b_idx)
 
300
            else:
 
301
                # The first conflict gets the a-range
 
302
                yielded_a = True
 
303
                yield ('conflict', zstart + last_base_idx, zstart + base_idx,
 
304
                       astart, aend, bstart + last_b_idx, bstart + b_idx)
 
305
        if not yielded_a:
 
306
            yield ('conflict', zstart, zend, astart, aend, bstart, bend)
 
307
 
 
308
    def reprocess_merge_regions(self, merge_regions):
 
309
        """Where there are conflict regions, remove the agreed lines.
 
310
 
 
311
        Lines where both A and B have made the same changes are 
 
312
        eliminated.
 
313
        """
 
314
        for region in merge_regions:
 
315
            if region[0] != "conflict":
 
316
                yield region
 
317
                continue
 
318
            type, iz, zmatch, ia, amatch, ib, bmatch = region
 
319
            a_region = self.a[ia:amatch]
 
320
            b_region = self.b[ib:bmatch]
 
321
            matches = bzrlib.patiencediff.PatienceSequenceMatcher(
 
322
                    None, a_region, b_region).get_matching_blocks()
 
323
            next_a = ia
 
324
            next_b = ib
 
325
            for region_ia, region_ib, region_len in matches[:-1]:
 
326
                region_ia += ia
 
327
                region_ib += ib
 
328
                reg = self.mismatch_region(next_a, region_ia, next_b,
 
329
                                           region_ib)
 
330
                if reg is not None:
 
331
                    yield reg
 
332
                yield 'same', region_ia, region_len+region_ia
 
333
                next_a = region_ia + region_len
 
334
                next_b = region_ib + region_len
 
335
            reg = self.mismatch_region(next_a, amatch, next_b, bmatch)
 
336
            if reg is not None:
 
337
                yield reg
 
338
 
 
339
    @staticmethod
 
340
    def mismatch_region(next_a, region_ia,  next_b, region_ib):
 
341
        if next_a < region_ia or next_b < region_ib:
 
342
            return 'conflict', None, None, next_a, region_ia, next_b, region_ib
 
343
 
269
344
    def find_sync_regions(self):
270
345
        """Return a list of sync regions, where both descendents match the base.
271
346
 
272
347
        Generates a list of (base1, base2, a1, a2, b1, b2).  There is
273
348
        always a zero-length sync region at the end of all the files.
274
349
        """
275
 
        from difflib import SequenceMatcher
276
350
 
277
351
        ia = ib = 0
278
 
        amatches = SequenceMatcher(None, self.base, self.a).get_matching_blocks()
279
 
        bmatches = SequenceMatcher(None, self.base, self.b).get_matching_blocks()
 
352
        amatches = bzrlib.patiencediff.PatienceSequenceMatcher(
 
353
                None, self.base, self.a).get_matching_blocks()
 
354
        bmatches = bzrlib.patiencediff.PatienceSequenceMatcher(
 
355
                None, self.base, self.b).get_matching_blocks()
280
356
        len_a = len(amatches)
281
357
        len_b = len(bmatches)
282
358
 
293
369
                intbase = i[0]
294
370
                intend = i[1]
295
371
                intlen = intend - intbase
296
 
 
297
 
                # found a match of base[i[0], i[1]]; this may be less than
298
 
                # the region that matches in either one
299
 
                assert intlen <= alen
300
 
                assert intlen <= blen
301
 
                assert abase <= intbase
302
 
                assert bbase <= intbase
303
 
 
304
372
                asub = amatch + (intbase - abase)
305
373
                bsub = bmatch + (intbase - bbase)
306
374
                aend = asub + intlen
307
375
                bend = bsub + intlen
308
 
 
309
 
                assert self.base[intbase:intend] == self.a[asub:aend], \
310
 
                       (self.base[intbase:intend], self.a[asub:aend])
311
 
 
312
 
                assert self.base[intbase:intend] == self.b[bsub:bend]
313
 
 
314
376
                sl.append((intbase, intend,
315
377
                           asub, aend,
316
378
                           bsub, bend))
317
 
 
318
379
            # advance whichever one ends first in the base text
319
380
            if (abase + alen) < (bbase + blen):
320
381
                ia += 1
328
389
 
329
390
        return sl
330
391
 
331
 
 
332
 
 
333
392
    def find_unconflicted(self):
334
393
        """Return a list of ranges in base that are not conflicted."""
335
 
        from difflib import SequenceMatcher
336
 
 
337
 
        import re
338
 
 
339
 
        # don't sync-up on lines containing only blanks or pounds
340
 
        junk_re = re.compile(r'^[ \t#]*$')
341
 
        
342
 
        am = SequenceMatcher(junk_re.match, self.base, self.a).get_matching_blocks()
343
 
        bm = SequenceMatcher(junk_re.match, self.base, self.b).get_matching_blocks()
 
394
        am = bzrlib.patiencediff.PatienceSequenceMatcher(
 
395
                None, self.base, self.a).get_matching_blocks()
 
396
        bm = bzrlib.patiencediff.PatienceSequenceMatcher(
 
397
                None, self.base, self.b).get_matching_blocks()
344
398
 
345
399
        unc = []
346
400