View Javadoc
1   /*
2    * Copyright (C) 2009, Christian Halstrick <christian.halstrick@sap.com>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.merge;
45  
46  import java.util.ArrayList;
47  import java.util.Iterator;
48  import java.util.List;
49  
50  import org.eclipse.jgit.diff.DiffAlgorithm;
51  import org.eclipse.jgit.diff.Edit;
52  import org.eclipse.jgit.diff.EditList;
53  import org.eclipse.jgit.diff.HistogramDiff;
54  import org.eclipse.jgit.diff.Sequence;
55  import org.eclipse.jgit.diff.SequenceComparator;
56  import org.eclipse.jgit.merge.MergeChunk.ConflictState;
57  
58  /**
59   * Provides the merge algorithm which does a three-way merge on content provided
60   * as RawText. By default {@link org.eclipse.jgit.diff.HistogramDiff} is used as
61   * diff algorithm.
62   */
63  public final class MergeAlgorithm {
64  	private final DiffAlgorithm diffAlg;
65  
66  	/**
67  	 * Creates a new MergeAlgorithm which uses
68  	 * {@link org.eclipse.jgit.diff.HistogramDiff} as diff algorithm
69  	 */
70  	public MergeAlgorithm() {
71  		this(new HistogramDiff());
72  	}
73  
74  	/**
75  	 * Creates a new MergeAlgorithm
76  	 *
77  	 * @param diff
78  	 *            the diff algorithm used by this merge
79  	 */
80  	public MergeAlgorithm(DiffAlgorithm diff) {
81  		this.diffAlg = diff;
82  	}
83  
84  	// An special edit which acts as a sentinel value by marking the end the
85  	// list of edits
86  	private final static Edittml#Edit">Edit END_EDIT = new Edit(Integer.MAX_VALUE,
87  			Integer.MAX_VALUE);
88  
89  	@SuppressWarnings("ReferenceEquality")
90  	private static boolean isEndEdit(Edit edit) {
91  		return edit == END_EDIT;
92  	}
93  
94  	/**
95  	 * Does the three way merge between a common base and two sequences.
96  	 *
97  	 * @param cmp comparison method for this execution.
98  	 * @param base the common base sequence
99  	 * @param ours the first sequence to be merged
100 	 * @param theirs the second sequence to be merged
101 	 * @return the resulting content
102 	 */
103 	public <S extends Sequence> MergeResult<S> merge(
104 			SequenceComparator<S> cmp, S base, S ours, S theirs) {
105 		List<S> sequences = new ArrayList<>(3);
106 		sequences.add(base);
107 		sequences.add(ours);
108 		sequences.add(theirs);
109 		MergeResult<S> result = new MergeResult<>(sequences);
110 
111 		if (ours.size() == 0) {
112 			if (theirs.size() != 0) {
113 				EditList theirsEdits = diffAlg.diff(cmp, base, theirs);
114 				if (!theirsEdits.isEmpty()) {
115 					// we deleted, they modified -> Let their complete content
116 					// conflict with empty text
117 					result.add(1, 0, 0, ConflictState.FIRST_CONFLICTING_RANGE);
118 					result.add(2, 0, theirs.size(),
119 							ConflictState.NEXT_CONFLICTING_RANGE);
120 				} else
121 					// we deleted, they didn't modify -> Let our deletion win
122 					result.add(1, 0, 0, ConflictState.NO_CONFLICT);
123 			} else
124 				// we and they deleted -> return a single chunk of nothing
125 				result.add(1, 0, 0, ConflictState.NO_CONFLICT);
126 			return result;
127 		} else if (theirs.size() == 0) {
128 			EditList oursEdits = diffAlg.diff(cmp, base, ours);
129 			if (!oursEdits.isEmpty()) {
130 				// we modified, they deleted -> Let our complete content
131 				// conflict with empty text
132 				result.add(1, 0, ours.size(),
133 						ConflictState.FIRST_CONFLICTING_RANGE);
134 				result.add(2, 0, 0, ConflictState.NEXT_CONFLICTING_RANGE);
135 			} else
136 				// they deleted, we didn't modify -> Let their deletion win
137 				result.add(2, 0, 0, ConflictState.NO_CONFLICT);
138 			return result;
139 		}
140 
141 		EditList oursEdits = diffAlg.diff(cmp, base, ours);
142 		Iterator<Edit> baseToOurs = oursEdits.iterator();
143 		EditList theirsEdits = diffAlg.diff(cmp, base, theirs);
144 		Iterator<Edit> baseToTheirs = theirsEdits.iterator();
145 		int current = 0; // points to the next line (first line is 0) of base
146 		                 // which was not handled yet
147 		Edit oursEdit = nextEdit(baseToOurs);
148 		Edit theirsEdit = nextEdit(baseToTheirs);
149 
150 		// iterate over all edits from base to ours and from base to theirs
151 		// leave the loop when there are no edits more for ours or for theirs
152 		// (or both)
153 		while (!isEndEdit(theirsEdit) || !isEndEdit(oursEdit)) {
154 			if (oursEdit.getEndA() < theirsEdit.getBeginA()) {
155 				// something was changed in ours not overlapping with any change
156 				// from theirs. First add the common part in front of the edit
157 				// then the edit.
158 				if (current != oursEdit.getBeginA()) {
159 					result.add(0, current, oursEdit.getBeginA(),
160 							ConflictState.NO_CONFLICT);
161 				}
162 				result.add(1, oursEdit.getBeginB(), oursEdit.getEndB(),
163 						ConflictState.NO_CONFLICT);
164 				current = oursEdit.getEndA();
165 				oursEdit = nextEdit(baseToOurs);
166 			} else if (theirsEdit.getEndA() < oursEdit.getBeginA()) {
167 				// something was changed in theirs not overlapping with any
168 				// from ours. First add the common part in front of the edit
169 				// then the edit.
170 				if (current != theirsEdit.getBeginA()) {
171 					result.add(0, current, theirsEdit.getBeginA(),
172 							ConflictState.NO_CONFLICT);
173 				}
174 				result.add(2, theirsEdit.getBeginB(), theirsEdit.getEndB(),
175 						ConflictState.NO_CONFLICT);
176 				current = theirsEdit.getEndA();
177 				theirsEdit = nextEdit(baseToTheirs);
178 			} else {
179 				// here we found a real overlapping modification
180 
181 				// if there is a common part in front of the conflict add it
182 				if (oursEdit.getBeginA() != current
183 						&& theirsEdit.getBeginA() != current) {
184 					result.add(0, current, Math.min(oursEdit.getBeginA(),
185 							theirsEdit.getBeginA()), ConflictState.NO_CONFLICT);
186 				}
187 
188 				// set some initial values for the ranges in A and B which we
189 				// want to handle
190 				int oursBeginB = oursEdit.getBeginB();
191 				int theirsBeginB = theirsEdit.getBeginB();
192 				// harmonize the start of the ranges in A and B
193 				if (oursEdit.getBeginA() < theirsEdit.getBeginA()) {
194 					theirsBeginB -= theirsEdit.getBeginA()
195 							- oursEdit.getBeginA();
196 				} else {
197 					oursBeginB -= oursEdit.getBeginA() - theirsEdit.getBeginA();
198 				}
199 
200 				// combine edits:
201 				// Maybe an Edit on one side corresponds to multiple Edits on
202 				// the other side. Then we have to combine the Edits of the
203 				// other side - so in the end we can merge together two single
204 				// edits.
205 				//
206 				// It is important to notice that this combining will extend the
207 				// ranges of our conflict always downwards (towards the end of
208 				// the content). The starts of the conflicting ranges in ours
209 				// and theirs are not touched here.
210 				//
211 				// This combining is an iterative process: after we have
212 				// combined some edits we have to do the check again. The
213 				// combined edits could now correspond to multiple edits on the
214 				// other side.
215 				//
216 				// Example: when this combining algorithm works on the following
217 				// edits
218 				// oursEdits=((0-5,0-5),(6-8,6-8),(10-11,10-11)) and
219 				// theirsEdits=((0-1,0-1),(2-3,2-3),(5-7,5-7))
220 				// it will merge them into
221 				// oursEdits=((0-8,0-8),(10-11,10-11)) and
222 				// theirsEdits=((0-7,0-7))
223 				//
224 				// Since the only interesting thing to us is how in ours and
225 				// theirs the end of the conflicting range is changing we let
226 				// oursEdit and theirsEdit point to the last conflicting edit
227 				Edit nextOursEdit = nextEdit(baseToOurs);
228 				Edit nextTheirsEdit = nextEdit(baseToTheirs);
229 				for (;;) {
230 					if (oursEdit.getEndA() >= nextTheirsEdit.getBeginA()) {
231 						theirsEdit = nextTheirsEdit;
232 						nextTheirsEdit = nextEdit(baseToTheirs);
233 					} else if (theirsEdit.getEndA() >= nextOursEdit.getBeginA()) {
234 						oursEdit = nextOursEdit;
235 						nextOursEdit = nextEdit(baseToOurs);
236 					} else {
237 						break;
238 					}
239 				}
240 
241 				// harmonize the end of the ranges in A and B
242 				int oursEndB = oursEdit.getEndB();
243 				int theirsEndB = theirsEdit.getEndB();
244 				if (oursEdit.getEndA() < theirsEdit.getEndA()) {
245 					oursEndB += theirsEdit.getEndA() - oursEdit.getEndA();
246 				} else {
247 					theirsEndB += oursEdit.getEndA() - theirsEdit.getEndA();
248 				}
249 
250 				// A conflicting region is found. Strip off common lines in
251 				// in the beginning and the end of the conflicting region
252 
253 				// Determine the minimum length of the conflicting areas in OURS
254 				// and THEIRS. Also determine how much bigger the conflicting
255 				// area in THEIRS is compared to OURS. All that is needed to
256 				// limit the search for common areas at the beginning or end
257 				// (the common areas cannot be bigger then the smaller
258 				// conflicting area. The delta is needed to know whether the
259 				// complete conflicting area is common in OURS and THEIRS.
260 				int minBSize = oursEndB - oursBeginB;
261 				int BSizeDelta = minBSize - (theirsEndB - theirsBeginB);
262 				if (BSizeDelta > 0)
263 					minBSize -= BSizeDelta;
264 
265 				int commonPrefix = 0;
266 				while (commonPrefix < minBSize
267 						&& cmp.equals(ours, oursBeginB + commonPrefix, theirs,
268 								theirsBeginB + commonPrefix))
269 					commonPrefix++;
270 				minBSize -= commonPrefix;
271 				int commonSuffix = 0;
272 				while (commonSuffix < minBSize
273 						&& cmp.equals(ours, oursEndB - commonSuffix - 1, theirs,
274 								theirsEndB - commonSuffix - 1))
275 					commonSuffix++;
276 				minBSize -= commonSuffix;
277 
278 				// Add the common lines at start of conflict
279 				if (commonPrefix > 0)
280 					result.add(1, oursBeginB, oursBeginB + commonPrefix,
281 							ConflictState.NO_CONFLICT);
282 
283 				// Add the conflict (Only if there is a conflict left to report)
284 				if (minBSize > 0 || BSizeDelta != 0) {
285 					result.add(1, oursBeginB + commonPrefix, oursEndB
286 							- commonSuffix,
287 							ConflictState.FIRST_CONFLICTING_RANGE);
288 					result.add(2, theirsBeginB + commonPrefix, theirsEndB
289 							- commonSuffix,
290 							ConflictState.NEXT_CONFLICTING_RANGE);
291 				}
292 
293 				// Add the common lines at end of conflict
294 				if (commonSuffix > 0)
295 					result.add(1, oursEndB - commonSuffix, oursEndB,
296 							ConflictState.NO_CONFLICT);
297 
298 				current = Math.max(oursEdit.getEndA(), theirsEdit.getEndA());
299 				oursEdit = nextOursEdit;
300 				theirsEdit = nextTheirsEdit;
301 			}
302 		}
303 		// maybe we have a common part behind the last edit: copy it to the
304 		// result
305 		if (current < base.size()) {
306 			result.add(0, current, base.size(), ConflictState.NO_CONFLICT);
307 		}
308 		return result;
309 	}
310 
311 	/**
312 	 * Helper method which returns the next Edit for an Iterator over Edits.
313 	 * When there are no more edits left this method will return the constant
314 	 * END_EDIT.
315 	 *
316 	 * @param it
317 	 *            the iterator for which the next edit should be returned
318 	 * @return the next edit from the iterator or END_EDIT if there no more
319 	 *         edits
320 	 */
321 	private static Edit nextEdit(Iterator<Edit> it) {
322 		return (it.hasNext() ? it.next() : END_EDIT);
323 	}
324 }