##// END OF EJS Templates
simplemerge: change _minimize() to minimize a single conflict...
Martin von Zweigbergk -
r49396:da04f362 default draft
parent child Browse files
Show More
@@ -1,530 +1,519 b''
1 # Copyright (C) 2004, 2005 Canonical Ltd
1 # Copyright (C) 2004, 2005 Canonical Ltd
2 #
2 #
3 # This program is free software; you can redistribute it and/or modify
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
6 # (at your option) any later version.
7 #
7 #
8 # This program is distributed in the hope that it will be useful,
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
11 # GNU General Public License for more details.
12 #
12 #
13 # You should have received a copy of the GNU General Public License
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, see <http://www.gnu.org/licenses/>.
14 # along with this program; if not, see <http://www.gnu.org/licenses/>.
15
15
16 # mbp: "you know that thing where cvs gives you conflict markers?"
16 # mbp: "you know that thing where cvs gives you conflict markers?"
17 # s: "i hate that."
17 # s: "i hate that."
18
18
19 from __future__ import absolute_import
19 from __future__ import absolute_import
20
20
21 from .i18n import _
21 from .i18n import _
22 from . import (
22 from . import (
23 error,
23 error,
24 mdiff,
24 mdiff,
25 pycompat,
25 pycompat,
26 )
26 )
27 from .utils import stringutil
27 from .utils import stringutil
28
28
29
29
30 class CantReprocessAndShowBase(Exception):
30 class CantReprocessAndShowBase(Exception):
31 pass
31 pass
32
32
33
33
34 def intersect(ra, rb):
34 def intersect(ra, rb):
35 """Given two ranges return the range where they intersect or None.
35 """Given two ranges return the range where they intersect or None.
36
36
37 >>> intersect((0, 10), (0, 6))
37 >>> intersect((0, 10), (0, 6))
38 (0, 6)
38 (0, 6)
39 >>> intersect((0, 10), (5, 15))
39 >>> intersect((0, 10), (5, 15))
40 (5, 10)
40 (5, 10)
41 >>> intersect((0, 10), (10, 15))
41 >>> intersect((0, 10), (10, 15))
42 >>> intersect((0, 9), (10, 15))
42 >>> intersect((0, 9), (10, 15))
43 >>> intersect((0, 9), (7, 15))
43 >>> intersect((0, 9), (7, 15))
44 (7, 9)
44 (7, 9)
45 """
45 """
46 assert ra[0] <= ra[1]
46 assert ra[0] <= ra[1]
47 assert rb[0] <= rb[1]
47 assert rb[0] <= rb[1]
48
48
49 sa = max(ra[0], rb[0])
49 sa = max(ra[0], rb[0])
50 sb = min(ra[1], rb[1])
50 sb = min(ra[1], rb[1])
51 if sa < sb:
51 if sa < sb:
52 return sa, sb
52 return sa, sb
53 else:
53 else:
54 return None
54 return None
55
55
56
56
57 def compare_range(a, astart, aend, b, bstart, bend):
57 def compare_range(a, astart, aend, b, bstart, bend):
58 """Compare a[astart:aend] == b[bstart:bend], without slicing."""
58 """Compare a[astart:aend] == b[bstart:bend], without slicing."""
59 if (aend - astart) != (bend - bstart):
59 if (aend - astart) != (bend - bstart):
60 return False
60 return False
61 for ia, ib in zip(
61 for ia, ib in zip(
62 pycompat.xrange(astart, aend), pycompat.xrange(bstart, bend)
62 pycompat.xrange(astart, aend), pycompat.xrange(bstart, bend)
63 ):
63 ):
64 if a[ia] != b[ib]:
64 if a[ia] != b[ib]:
65 return False
65 return False
66 else:
66 else:
67 return True
67 return True
68
68
69
69
70 class Merge3Text(object):
70 class Merge3Text(object):
71 """3-way merge of texts.
71 """3-way merge of texts.
72
72
73 Given strings BASE, OTHER, THIS, tries to produce a combined text
73 Given strings BASE, OTHER, THIS, tries to produce a combined text
74 incorporating the changes from both BASE->OTHER and BASE->THIS."""
74 incorporating the changes from both BASE->OTHER and BASE->THIS."""
75
75
76 def __init__(self, basetext, atext, btext, base=None, a=None, b=None):
76 def __init__(self, basetext, atext, btext, base=None, a=None, b=None):
77 self.basetext = basetext
77 self.basetext = basetext
78 self.atext = atext
78 self.atext = atext
79 self.btext = btext
79 self.btext = btext
80 if base is None:
80 if base is None:
81 base = mdiff.splitnewlines(basetext)
81 base = mdiff.splitnewlines(basetext)
82 if a is None:
82 if a is None:
83 a = mdiff.splitnewlines(atext)
83 a = mdiff.splitnewlines(atext)
84 if b is None:
84 if b is None:
85 b = mdiff.splitnewlines(btext)
85 b = mdiff.splitnewlines(btext)
86 self.base = base
86 self.base = base
87 self.a = a
87 self.a = a
88 self.b = b
88 self.b = b
89
89
90 def merge_groups(self):
90 def merge_groups(self):
91 """Yield sequence of line groups. Each one is a tuple:
91 """Yield sequence of line groups. Each one is a tuple:
92
92
93 'unchanged', lines
93 'unchanged', lines
94 Lines unchanged from base
94 Lines unchanged from base
95
95
96 'a', lines
96 'a', lines
97 Lines taken from a
97 Lines taken from a
98
98
99 'same', lines
99 'same', lines
100 Lines taken from a (and equal to b)
100 Lines taken from a (and equal to b)
101
101
102 'b', lines
102 'b', lines
103 Lines taken from b
103 Lines taken from b
104
104
105 'conflict', (base_lines, a_lines, b_lines)
105 'conflict', (base_lines, a_lines, b_lines)
106 Lines from base were changed to either a or b and conflict.
106 Lines from base were changed to either a or b and conflict.
107 """
107 """
108 for t in self.merge_regions():
108 for t in self.merge_regions():
109 what = t[0]
109 what = t[0]
110 if what == b'unchanged':
110 if what == b'unchanged':
111 yield what, self.base[t[1] : t[2]]
111 yield what, self.base[t[1] : t[2]]
112 elif what == b'a' or what == b'same':
112 elif what == b'a' or what == b'same':
113 yield what, self.a[t[1] : t[2]]
113 yield what, self.a[t[1] : t[2]]
114 elif what == b'b':
114 elif what == b'b':
115 yield what, self.b[t[1] : t[2]]
115 yield what, self.b[t[1] : t[2]]
116 elif what == b'conflict':
116 elif what == b'conflict':
117 yield (
117 yield (
118 what,
118 what,
119 (
119 (
120 self.base[t[1] : t[2]],
120 self.base[t[1] : t[2]],
121 self.a[t[3] : t[4]],
121 self.a[t[3] : t[4]],
122 self.b[t[5] : t[6]],
122 self.b[t[5] : t[6]],
123 ),
123 ),
124 )
124 )
125 else:
125 else:
126 raise ValueError(what)
126 raise ValueError(what)
127
127
128 def merge_regions(self):
128 def merge_regions(self):
129 """Return sequences of matching and conflicting regions.
129 """Return sequences of matching and conflicting regions.
130
130
131 This returns tuples, where the first value says what kind we
131 This returns tuples, where the first value says what kind we
132 have:
132 have:
133
133
134 'unchanged', start, end
134 'unchanged', start, end
135 Take a region of base[start:end]
135 Take a region of base[start:end]
136
136
137 'same', astart, aend
137 'same', astart, aend
138 b and a are different from base but give the same result
138 b and a are different from base but give the same result
139
139
140 'a', start, end
140 'a', start, end
141 Non-clashing insertion from a[start:end]
141 Non-clashing insertion from a[start:end]
142
142
143 'conflict', zstart, zend, astart, aend, bstart, bend
143 'conflict', zstart, zend, astart, aend, bstart, bend
144 Conflict between a and b, with z as common ancestor
144 Conflict between a and b, with z as common ancestor
145
145
146 Method is as follows:
146 Method is as follows:
147
147
148 The two sequences align only on regions which match the base
148 The two sequences align only on regions which match the base
149 and both descendants. These are found by doing a two-way diff
149 and both descendants. These are found by doing a two-way diff
150 of each one against the base, and then finding the
150 of each one against the base, and then finding the
151 intersections between those regions. These "sync regions"
151 intersections between those regions. These "sync regions"
152 are by definition unchanged in both and easily dealt with.
152 are by definition unchanged in both and easily dealt with.
153
153
154 The regions in between can be in any of three cases:
154 The regions in between can be in any of three cases:
155 conflicted, or changed on only one side.
155 conflicted, or changed on only one side.
156 """
156 """
157
157
158 # section a[0:ia] has been disposed of, etc
158 # section a[0:ia] has been disposed of, etc
159 iz = ia = ib = 0
159 iz = ia = ib = 0
160
160
161 for region in self.find_sync_regions():
161 for region in self.find_sync_regions():
162 zmatch, zend, amatch, aend, bmatch, bend = region
162 zmatch, zend, amatch, aend, bmatch, bend = region
163 # print 'match base [%d:%d]' % (zmatch, zend)
163 # print 'match base [%d:%d]' % (zmatch, zend)
164
164
165 matchlen = zend - zmatch
165 matchlen = zend - zmatch
166 assert matchlen >= 0
166 assert matchlen >= 0
167 assert matchlen == (aend - amatch)
167 assert matchlen == (aend - amatch)
168 assert matchlen == (bend - bmatch)
168 assert matchlen == (bend - bmatch)
169
169
170 len_a = amatch - ia
170 len_a = amatch - ia
171 len_b = bmatch - ib
171 len_b = bmatch - ib
172 len_base = zmatch - iz
172 len_base = zmatch - iz
173 assert len_a >= 0
173 assert len_a >= 0
174 assert len_b >= 0
174 assert len_b >= 0
175 assert len_base >= 0
175 assert len_base >= 0
176
176
177 # print 'unmatched a=%d, b=%d' % (len_a, len_b)
177 # print 'unmatched a=%d, b=%d' % (len_a, len_b)
178
178
179 if len_a or len_b:
179 if len_a or len_b:
180 # try to avoid actually slicing the lists
180 # try to avoid actually slicing the lists
181 equal_a = compare_range(
181 equal_a = compare_range(
182 self.a, ia, amatch, self.base, iz, zmatch
182 self.a, ia, amatch, self.base, iz, zmatch
183 )
183 )
184 equal_b = compare_range(
184 equal_b = compare_range(
185 self.b, ib, bmatch, self.base, iz, zmatch
185 self.b, ib, bmatch, self.base, iz, zmatch
186 )
186 )
187 same = compare_range(self.a, ia, amatch, self.b, ib, bmatch)
187 same = compare_range(self.a, ia, amatch, self.b, ib, bmatch)
188
188
189 if same:
189 if same:
190 yield b'same', ia, amatch
190 yield b'same', ia, amatch
191 elif equal_a and not equal_b:
191 elif equal_a and not equal_b:
192 yield b'b', ib, bmatch
192 yield b'b', ib, bmatch
193 elif equal_b and not equal_a:
193 elif equal_b and not equal_a:
194 yield b'a', ia, amatch
194 yield b'a', ia, amatch
195 elif not equal_a and not equal_b:
195 elif not equal_a and not equal_b:
196 yield b'conflict', iz, zmatch, ia, amatch, ib, bmatch
196 yield b'conflict', iz, zmatch, ia, amatch, ib, bmatch
197 else:
197 else:
198 raise AssertionError(b"can't handle a=b=base but unmatched")
198 raise AssertionError(b"can't handle a=b=base but unmatched")
199
199
200 ia = amatch
200 ia = amatch
201 ib = bmatch
201 ib = bmatch
202 iz = zmatch
202 iz = zmatch
203
203
204 # if the same part of the base was deleted on both sides
204 # if the same part of the base was deleted on both sides
205 # that's OK, we can just skip it.
205 # that's OK, we can just skip it.
206
206
207 if matchlen > 0:
207 if matchlen > 0:
208 assert ia == amatch
208 assert ia == amatch
209 assert ib == bmatch
209 assert ib == bmatch
210 assert iz == zmatch
210 assert iz == zmatch
211
211
212 yield b'unchanged', zmatch, zend
212 yield b'unchanged', zmatch, zend
213 iz = zend
213 iz = zend
214 ia = aend
214 ia = aend
215 ib = bend
215 ib = bend
216
216
217 def find_sync_regions(self):
217 def find_sync_regions(self):
218 """Return a list of sync regions, where both descendants match the base.
218 """Return a list of sync regions, where both descendants match the base.
219
219
220 Generates a list of (base1, base2, a1, a2, b1, b2). There is
220 Generates a list of (base1, base2, a1, a2, b1, b2). There is
221 always a zero-length sync region at the end of all the files.
221 always a zero-length sync region at the end of all the files.
222 """
222 """
223
223
224 ia = ib = 0
224 ia = ib = 0
225 amatches = mdiff.get_matching_blocks(self.basetext, self.atext)
225 amatches = mdiff.get_matching_blocks(self.basetext, self.atext)
226 bmatches = mdiff.get_matching_blocks(self.basetext, self.btext)
226 bmatches = mdiff.get_matching_blocks(self.basetext, self.btext)
227 len_a = len(amatches)
227 len_a = len(amatches)
228 len_b = len(bmatches)
228 len_b = len(bmatches)
229
229
230 sl = []
230 sl = []
231
231
232 while ia < len_a and ib < len_b:
232 while ia < len_a and ib < len_b:
233 abase, amatch, alen = amatches[ia]
233 abase, amatch, alen = amatches[ia]
234 bbase, bmatch, blen = bmatches[ib]
234 bbase, bmatch, blen = bmatches[ib]
235
235
236 # there is an unconflicted block at i; how long does it
236 # there is an unconflicted block at i; how long does it
237 # extend? until whichever one ends earlier.
237 # extend? until whichever one ends earlier.
238 i = intersect((abase, abase + alen), (bbase, bbase + blen))
238 i = intersect((abase, abase + alen), (bbase, bbase + blen))
239 if i:
239 if i:
240 intbase = i[0]
240 intbase = i[0]
241 intend = i[1]
241 intend = i[1]
242 intlen = intend - intbase
242 intlen = intend - intbase
243
243
244 # found a match of base[i[0], i[1]]; this may be less than
244 # found a match of base[i[0], i[1]]; this may be less than
245 # the region that matches in either one
245 # the region that matches in either one
246 assert intlen <= alen
246 assert intlen <= alen
247 assert intlen <= blen
247 assert intlen <= blen
248 assert abase <= intbase
248 assert abase <= intbase
249 assert bbase <= intbase
249 assert bbase <= intbase
250
250
251 asub = amatch + (intbase - abase)
251 asub = amatch + (intbase - abase)
252 bsub = bmatch + (intbase - bbase)
252 bsub = bmatch + (intbase - bbase)
253 aend = asub + intlen
253 aend = asub + intlen
254 bend = bsub + intlen
254 bend = bsub + intlen
255
255
256 assert self.base[intbase:intend] == self.a[asub:aend], (
256 assert self.base[intbase:intend] == self.a[asub:aend], (
257 self.base[intbase:intend],
257 self.base[intbase:intend],
258 self.a[asub:aend],
258 self.a[asub:aend],
259 )
259 )
260
260
261 assert self.base[intbase:intend] == self.b[bsub:bend]
261 assert self.base[intbase:intend] == self.b[bsub:bend]
262
262
263 sl.append((intbase, intend, asub, aend, bsub, bend))
263 sl.append((intbase, intend, asub, aend, bsub, bend))
264
264
265 # advance whichever one ends first in the base text
265 # advance whichever one ends first in the base text
266 if (abase + alen) < (bbase + blen):
266 if (abase + alen) < (bbase + blen):
267 ia += 1
267 ia += 1
268 else:
268 else:
269 ib += 1
269 ib += 1
270
270
271 intbase = len(self.base)
271 intbase = len(self.base)
272 abase = len(self.a)
272 abase = len(self.a)
273 bbase = len(self.b)
273 bbase = len(self.b)
274 sl.append((intbase, intbase, abase, abase, bbase, bbase))
274 sl.append((intbase, intbase, abase, abase, bbase, bbase))
275
275
276 return sl
276 return sl
277
277
278
278
279 def _verifytext(text, path, ui, opts):
279 def _verifytext(text, path, ui, opts):
280 """verifies that text is non-binary (unless opts[text] is passed,
280 """verifies that text is non-binary (unless opts[text] is passed,
281 then we just warn)"""
281 then we just warn)"""
282 if stringutil.binary(text):
282 if stringutil.binary(text):
283 msg = _(b"%s looks like a binary file.") % path
283 msg = _(b"%s looks like a binary file.") % path
284 if not opts.get('quiet'):
284 if not opts.get('quiet'):
285 ui.warn(_(b'warning: %s\n') % msg)
285 ui.warn(_(b'warning: %s\n') % msg)
286 if not opts.get('text'):
286 if not opts.get('text'):
287 raise error.Abort(msg)
287 raise error.Abort(msg)
288 return text
288 return text
289
289
290
290
291 def _picklabels(overrides):
291 def _picklabels(overrides):
292 if len(overrides) > 3:
292 if len(overrides) > 3:
293 raise error.Abort(_(b"can only specify three labels."))
293 raise error.Abort(_(b"can only specify three labels."))
294 result = [None, None, None]
294 result = [None, None, None]
295 for i, override in enumerate(overrides):
295 for i, override in enumerate(overrides):
296 result[i] = override
296 result[i] = override
297 return result
297 return result
298
298
299
299
300 def _detect_newline(m3):
300 def _detect_newline(m3):
301 if len(m3.a) > 0:
301 if len(m3.a) > 0:
302 if m3.a[0].endswith(b'\r\n'):
302 if m3.a[0].endswith(b'\r\n'):
303 return b'\r\n'
303 return b'\r\n'
304 elif m3.a[0].endswith(b'\r'):
304 elif m3.a[0].endswith(b'\r'):
305 return b'\r'
305 return b'\r'
306 return b'\n'
306 return b'\n'
307
307
308
308
309 def _minimize(merge_groups):
309 def _minimize(a_lines, b_lines):
310 """Trim conflict regions of lines where A and B sides match.
310 """Trim conflict regions of lines where A and B sides match.
311
311
312 Lines where both A and B have made the same changes at the beginning
312 Lines where both A and B have made the same changes at the beginning
313 or the end of each merge region are eliminated from the conflict
313 or the end of each merge region are eliminated from the conflict
314 region and are instead considered the same.
314 region and are instead considered the same.
315 """
315 """
316 for what, lines in merge_groups:
316 alen = len(a_lines)
317 if what != b"conflict":
317 blen = len(b_lines)
318 yield what, lines
319 continue
320 base_lines, a_lines, b_lines = lines
321 alen = len(a_lines)
322 blen = len(b_lines)
323
318
324 # find matches at the front
319 # find matches at the front
325 ii = 0
320 ii = 0
326 while ii < alen and ii < blen and a_lines[ii] == b_lines[ii]:
321 while ii < alen and ii < blen and a_lines[ii] == b_lines[ii]:
327 ii += 1
322 ii += 1
328 startmatches = ii
323 startmatches = ii
329
324
330 # find matches at the end
325 # find matches at the end
331 ii = 0
326 ii = 0
332 while ii < alen and ii < blen and a_lines[-ii - 1] == b_lines[-ii - 1]:
327 while ii < alen and ii < blen and a_lines[-ii - 1] == b_lines[-ii - 1]:
333 ii += 1
328 ii += 1
334 endmatches = ii
329 endmatches = ii
335
336 if startmatches > 0:
337 yield b'same', a_lines[:startmatches]
338
330
339 yield (
331 lines_before = a_lines[:startmatches]
340 b'conflict',
332 new_a_lines = a_lines[startmatches : alen - endmatches]
341 (
333 new_b_lines = b_lines[startmatches : blen - endmatches]
342 base_lines,
334 lines_after = a_lines[alen - endmatches :]
343 a_lines[startmatches : alen - endmatches],
335 return lines_before, new_a_lines, new_b_lines, lines_after
344 b_lines[startmatches : blen - endmatches],
345 ),
346 )
347
348 if endmatches > 0:
349 yield b'same', a_lines[alen - endmatches :]
350
336
351
337
352 def render_minimized(
338 def render_minimized(
353 m3,
339 m3,
354 name_a=None,
340 name_a=None,
355 name_b=None,
341 name_b=None,
356 start_marker=b'<<<<<<<',
342 start_marker=b'<<<<<<<',
357 mid_marker=b'=======',
343 mid_marker=b'=======',
358 end_marker=b'>>>>>>>',
344 end_marker=b'>>>>>>>',
359 ):
345 ):
360 """Return merge in cvs-like form."""
346 """Return merge in cvs-like form."""
361 newline = _detect_newline(m3)
347 newline = _detect_newline(m3)
362 conflicts = False
348 conflicts = False
363 if name_a:
349 if name_a:
364 start_marker = start_marker + b' ' + name_a
350 start_marker = start_marker + b' ' + name_a
365 if name_b:
351 if name_b:
366 end_marker = end_marker + b' ' + name_b
352 end_marker = end_marker + b' ' + name_b
367 merge_groups = m3.merge_groups()
353 merge_groups = m3.merge_groups()
368 merge_groups = _minimize(merge_groups)
369 lines = []
354 lines = []
370 for what, group_lines in merge_groups:
355 for what, group_lines in merge_groups:
371 if what == b'conflict':
356 if what == b'conflict':
357 conflicts = True
372 base_lines, a_lines, b_lines = group_lines
358 base_lines, a_lines, b_lines = group_lines
373 conflicts = True
359 minimized = _minimize(a_lines, b_lines)
360 lines_before, a_lines, b_lines, lines_after = minimized
361 lines.extend(lines_before)
374 lines.append(start_marker + newline)
362 lines.append(start_marker + newline)
375 lines.extend(a_lines)
363 lines.extend(a_lines)
376 lines.append(mid_marker + newline)
364 lines.append(mid_marker + newline)
377 lines.extend(b_lines)
365 lines.extend(b_lines)
378 lines.append(end_marker + newline)
366 lines.append(end_marker + newline)
367 lines.extend(lines_after)
379 else:
368 else:
380 lines.extend(group_lines)
369 lines.extend(group_lines)
381 return lines, conflicts
370 return lines, conflicts
382
371
383
372
384 def render_merge3(m3, name_a, name_b, name_base):
373 def render_merge3(m3, name_a, name_b, name_base):
385 """Render conflicts as 3-way conflict markers."""
374 """Render conflicts as 3-way conflict markers."""
386 newline = _detect_newline(m3)
375 newline = _detect_newline(m3)
387 conflicts = False
376 conflicts = False
388 lines = []
377 lines = []
389 for what, group_lines in m3.merge_groups():
378 for what, group_lines in m3.merge_groups():
390 if what == b'conflict':
379 if what == b'conflict':
391 base_lines, a_lines, b_lines = group_lines
380 base_lines, a_lines, b_lines = group_lines
392 conflicts = True
381 conflicts = True
393 lines.append(b'<<<<<<< ' + name_a + newline)
382 lines.append(b'<<<<<<< ' + name_a + newline)
394 lines.extend(a_lines)
383 lines.extend(a_lines)
395 lines.append(b'||||||| ' + name_base + newline)
384 lines.append(b'||||||| ' + name_base + newline)
396 lines.extend(base_lines)
385 lines.extend(base_lines)
397 lines.append(b'=======' + newline)
386 lines.append(b'=======' + newline)
398 lines.extend(b_lines)
387 lines.extend(b_lines)
399 lines.append(b'>>>>>>> ' + name_b + newline)
388 lines.append(b'>>>>>>> ' + name_b + newline)
400 else:
389 else:
401 lines.extend(group_lines)
390 lines.extend(group_lines)
402 return lines, conflicts
391 return lines, conflicts
403
392
404
393
405 def render_mergediff(m3, name_a, name_b, name_base):
394 def render_mergediff(m3, name_a, name_b, name_base):
406 """Render conflicts as conflict markers with one snapshot and one diff."""
395 """Render conflicts as conflict markers with one snapshot and one diff."""
407 newline = _detect_newline(m3)
396 newline = _detect_newline(m3)
408 lines = []
397 lines = []
409 conflicts = False
398 conflicts = False
410 for what, group_lines in m3.merge_groups():
399 for what, group_lines in m3.merge_groups():
411 if what == b'conflict':
400 if what == b'conflict':
412 base_lines, a_lines, b_lines = group_lines
401 base_lines, a_lines, b_lines = group_lines
413 base_text = b''.join(base_lines)
402 base_text = b''.join(base_lines)
414 b_blocks = list(
403 b_blocks = list(
415 mdiff.allblocks(
404 mdiff.allblocks(
416 base_text,
405 base_text,
417 b''.join(b_lines),
406 b''.join(b_lines),
418 lines1=base_lines,
407 lines1=base_lines,
419 lines2=b_lines,
408 lines2=b_lines,
420 )
409 )
421 )
410 )
422 a_blocks = list(
411 a_blocks = list(
423 mdiff.allblocks(
412 mdiff.allblocks(
424 base_text,
413 base_text,
425 b''.join(a_lines),
414 b''.join(a_lines),
426 lines1=base_lines,
415 lines1=base_lines,
427 lines2=b_lines,
416 lines2=b_lines,
428 )
417 )
429 )
418 )
430
419
431 def matching_lines(blocks):
420 def matching_lines(blocks):
432 return sum(
421 return sum(
433 block[1] - block[0]
422 block[1] - block[0]
434 for block, kind in blocks
423 for block, kind in blocks
435 if kind == b'='
424 if kind == b'='
436 )
425 )
437
426
438 def diff_lines(blocks, lines1, lines2):
427 def diff_lines(blocks, lines1, lines2):
439 for block, kind in blocks:
428 for block, kind in blocks:
440 if kind == b'=':
429 if kind == b'=':
441 for line in lines1[block[0] : block[1]]:
430 for line in lines1[block[0] : block[1]]:
442 yield b' ' + line
431 yield b' ' + line
443 else:
432 else:
444 for line in lines1[block[0] : block[1]]:
433 for line in lines1[block[0] : block[1]]:
445 yield b'-' + line
434 yield b'-' + line
446 for line in lines2[block[2] : block[3]]:
435 for line in lines2[block[2] : block[3]]:
447 yield b'+' + line
436 yield b'+' + line
448
437
449 lines.append(b"<<<<<<<" + newline)
438 lines.append(b"<<<<<<<" + newline)
450 if matching_lines(a_blocks) < matching_lines(b_blocks):
439 if matching_lines(a_blocks) < matching_lines(b_blocks):
451 lines.append(b"======= " + name_a + newline)
440 lines.append(b"======= " + name_a + newline)
452 lines.extend(a_lines)
441 lines.extend(a_lines)
453 lines.append(b"------- " + name_base + newline)
442 lines.append(b"------- " + name_base + newline)
454 lines.append(b"+++++++ " + name_b + newline)
443 lines.append(b"+++++++ " + name_b + newline)
455 lines.extend(diff_lines(b_blocks, base_lines, b_lines))
444 lines.extend(diff_lines(b_blocks, base_lines, b_lines))
456 else:
445 else:
457 lines.append(b"------- " + name_base + newline)
446 lines.append(b"------- " + name_base + newline)
458 lines.append(b"+++++++ " + name_a + newline)
447 lines.append(b"+++++++ " + name_a + newline)
459 lines.extend(diff_lines(a_blocks, base_lines, a_lines))
448 lines.extend(diff_lines(a_blocks, base_lines, a_lines))
460 lines.append(b"======= " + name_b + newline)
449 lines.append(b"======= " + name_b + newline)
461 lines.extend(b_lines)
450 lines.extend(b_lines)
462 lines.append(b">>>>>>>" + newline)
451 lines.append(b">>>>>>>" + newline)
463 conflicts = True
452 conflicts = True
464 else:
453 else:
465 lines.extend(group_lines)
454 lines.extend(group_lines)
466 return lines, conflicts
455 return lines, conflicts
467
456
468
457
469 def _resolve(m3, sides):
458 def _resolve(m3, sides):
470 lines = []
459 lines = []
471 for what, group_lines in m3.merge_groups():
460 for what, group_lines in m3.merge_groups():
472 if what == b'conflict':
461 if what == b'conflict':
473 for side in sides:
462 for side in sides:
474 lines.extend(group_lines[side])
463 lines.extend(group_lines[side])
475 else:
464 else:
476 lines.extend(group_lines)
465 lines.extend(group_lines)
477 return lines
466 return lines
478
467
479
468
480 def simplemerge(ui, localctx, basectx, otherctx, **opts):
469 def simplemerge(ui, localctx, basectx, otherctx, **opts):
481 """Performs the simplemerge algorithm.
470 """Performs the simplemerge algorithm.
482
471
483 The merged result is written into `localctx`.
472 The merged result is written into `localctx`.
484 """
473 """
485
474
486 def readctx(ctx):
475 def readctx(ctx):
487 # Merges were always run in the working copy before, which means
476 # Merges were always run in the working copy before, which means
488 # they used decoded data, if the user defined any repository
477 # they used decoded data, if the user defined any repository
489 # filters.
478 # filters.
490 #
479 #
491 # Maintain that behavior today for BC, though perhaps in the future
480 # Maintain that behavior today for BC, though perhaps in the future
492 # it'd be worth considering whether merging encoded data (what the
481 # it'd be worth considering whether merging encoded data (what the
493 # repository usually sees) might be more useful.
482 # repository usually sees) might be more useful.
494 return _verifytext(ctx.decodeddata(), ctx.path(), ui, opts)
483 return _verifytext(ctx.decodeddata(), ctx.path(), ui, opts)
495
484
496 try:
485 try:
497 localtext = readctx(localctx)
486 localtext = readctx(localctx)
498 basetext = readctx(basectx)
487 basetext = readctx(basectx)
499 othertext = readctx(otherctx)
488 othertext = readctx(otherctx)
500 except error.Abort:
489 except error.Abort:
501 return 1
490 return 1
502
491
503 m3 = Merge3Text(basetext, localtext, othertext)
492 m3 = Merge3Text(basetext, localtext, othertext)
504 conflicts = False
493 conflicts = False
505 mode = opts.get('mode', b'merge')
494 mode = opts.get('mode', b'merge')
506 if mode == b'union':
495 if mode == b'union':
507 lines = _resolve(m3, (1, 2))
496 lines = _resolve(m3, (1, 2))
508 elif mode == b'local':
497 elif mode == b'local':
509 lines = _resolve(m3, (1,))
498 lines = _resolve(m3, (1,))
510 elif mode == b'other':
499 elif mode == b'other':
511 lines = _resolve(m3, (2,))
500 lines = _resolve(m3, (2,))
512 else:
501 else:
513 name_a, name_b, name_base = _picklabels(opts.get('label', []))
502 name_a, name_b, name_base = _picklabels(opts.get('label', []))
514 if mode == b'mergediff':
503 if mode == b'mergediff':
515 lines, conflicts = render_mergediff(m3, name_a, name_b, name_base)
504 lines, conflicts = render_mergediff(m3, name_a, name_b, name_base)
516 elif mode == b'merge3':
505 elif mode == b'merge3':
517 lines, conflicts = render_merge3(m3, name_a, name_b, name_base)
506 lines, conflicts = render_merge3(m3, name_a, name_b, name_base)
518 else:
507 else:
519 lines, conflicts = render_minimized(m3, name_a, name_b)
508 lines, conflicts = render_minimized(m3, name_a, name_b)
520
509
521 mergedtext = b''.join(lines)
510 mergedtext = b''.join(lines)
522 if opts.get('print'):
511 if opts.get('print'):
523 ui.fout.write(mergedtext)
512 ui.fout.write(mergedtext)
524 else:
513 else:
525 # localctx.flags() already has the merged flags (done in
514 # localctx.flags() already has the merged flags (done in
526 # mergestate.resolve())
515 # mergestate.resolve())
527 localctx.write(mergedtext, localctx.flags())
516 localctx.write(mergedtext, localctx.flags())
528
517
529 if conflicts:
518 if conflicts:
530 return 1
519 return 1
General Comments 0
You need to be logged in to leave comments. Login now