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 HistogramDiff} is used as diff algorithm.
61   */
62  public final class MergeAlgorithm {
63  	private final DiffAlgorithm diffAlg;
64  
65  	/**
66  	 * Creates a new MergeAlgorithm which uses {@link HistogramDiff} as diff
67  	 * algorithm
68  	 */
69  	public MergeAlgorithm() {
70  		this(new HistogramDiff());
71  	}
72  
73  	/**
74  	 * Creates a new MergeAlgorithm
75  	 *
76  	 * @param diff
77  	 *            the diff algorithm used by this merge
78  	 */
79  	public MergeAlgorithm(DiffAlgorithm diff) {
80  		this.diffAlg = diff;
81  	}
82  
83  	// An special edit which acts as a sentinel value by marking the end the
84  	// list of edits
85  	private final static Edit END_EDIT = new Edit(Integer.MAX_VALUE,
86  			Integer.MAX_VALUE);
87  
88  	/**
89  	 * Does the three way merge between a common base and two sequences.
90  	 *
91  	 * @param <S>
92  	 *            type of sequence.
93  	 * @param cmp comparison method for this execution.
94  	 * @param base the common base sequence
95  	 * @param ours the first sequence to be merged
96  	 * @param theirs the second sequence to be merged
97  	 * @return the resulting content
98  	 */
99  	public <S extends Sequence> MergeResult<S> merge(
100 			SequenceComparator<S> cmp, S base, S ours, S theirs) {
101 		List<S> sequences = new ArrayList<S>(3);
102 		sequences.add(base);
103 		sequences.add(ours);
104 		sequences.add(theirs);
105 		MergeResult<S> result = new MergeResult<S>(sequences);
106 
107 		if (ours.size() == 0) {
108 			if (theirs.size() != 0) {
109 				EditList theirsEdits = diffAlg.diff(cmp, base, theirs);
110 				if (!theirsEdits.isEmpty()) {
111 					// we deleted, they modified -> Let their complete content
112 					// conflict with empty text
113 					result.add(1, 0, 0, ConflictState.FIRST_CONFLICTING_RANGE);
114 					result.add(2, 0, theirs.size(),
115 							ConflictState.NEXT_CONFLICTING_RANGE);
116 				} else
117 					// we deleted, they didn't modify -> Let our deletion win
118 					result.add(1, 0, 0, ConflictState.NO_CONFLICT);
119 			} else
120 				// we and they deleted -> return a single chunk of nothing
121 				result.add(1, 0, 0, ConflictState.NO_CONFLICT);
122 			return result;
123 		} else if (theirs.size() == 0) {
124 			EditList oursEdits = diffAlg.diff(cmp, base, ours);
125 			if (!oursEdits.isEmpty()) {
126 				// we modified, they deleted -> Let our complete content
127 				// conflict with empty text
128 				result.add(1, 0, ours.size(),
129 						ConflictState.FIRST_CONFLICTING_RANGE);
130 				result.add(2, 0, 0, ConflictState.NEXT_CONFLICTING_RANGE);
131 			} else
132 				// they deleted, we didn't modify -> Let their deletion win
133 				result.add(2, 0, 0, ConflictState.NO_CONFLICT);
134 			return result;
135 		}
136 
137 		EditList oursEdits = diffAlg.diff(cmp, base, ours);
138 		Iterator<Edit> baseToOurs = oursEdits.iterator();
139 		EditList theirsEdits = diffAlg.diff(cmp, base, theirs);
140 		Iterator<Edit> baseToTheirs = theirsEdits.iterator();
141 		int current = 0; // points to the next line (first line is 0) of base
142 		                 // which was not handled yet
143 		Edit oursEdit = nextEdit(baseToOurs);
144 		Edit theirsEdit = nextEdit(baseToTheirs);
145 
146 		// iterate over all edits from base to ours and from base to theirs
147 		// leave the loop when there are no edits more for ours or for theirs
148 		// (or both)
149 		while (theirsEdit != END_EDIT || oursEdit != END_EDIT) {
150 			if (oursEdit.getEndA() < theirsEdit.getBeginA()) {
151 				// something was changed in ours not overlapping with any change
152 				// from theirs. First add the common part in front of the edit
153 				// then the edit.
154 				if (current != oursEdit.getBeginA()) {
155 					result.add(0, current, oursEdit.getBeginA(),
156 							ConflictState.NO_CONFLICT);
157 				}
158 				result.add(1, oursEdit.getBeginB(), oursEdit.getEndB(),
159 						ConflictState.NO_CONFLICT);
160 				current = oursEdit.getEndA();
161 				oursEdit = nextEdit(baseToOurs);
162 			} else if (theirsEdit.getEndA() < oursEdit.getBeginA()) {
163 				// something was changed in theirs not overlapping with any
164 				// from ours. First add the common part in front of the edit
165 				// then the edit.
166 				if (current != theirsEdit.getBeginA()) {
167 					result.add(0, current, theirsEdit.getBeginA(),
168 							ConflictState.NO_CONFLICT);
169 				}
170 				result.add(2, theirsEdit.getBeginB(), theirsEdit.getEndB(),
171 						ConflictState.NO_CONFLICT);
172 				current = theirsEdit.getEndA();
173 				theirsEdit = nextEdit(baseToTheirs);
174 			} else {
175 				// here we found a real overlapping modification
176 
177 				// if there is a common part in front of the conflict add it
178 				if (oursEdit.getBeginA() != current
179 						&& theirsEdit.getBeginA() != current) {
180 					result.add(0, current, Math.min(oursEdit.getBeginA(),
181 							theirsEdit.getBeginA()), ConflictState.NO_CONFLICT);
182 				}
183 
184 				// set some initial values for the ranges in A and B which we
185 				// want to handle
186 				int oursBeginB = oursEdit.getBeginB();
187 				int theirsBeginB = theirsEdit.getBeginB();
188 				// harmonize the start of the ranges in A and B
189 				if (oursEdit.getBeginA() < theirsEdit.getBeginA()) {
190 					theirsBeginB -= theirsEdit.getBeginA()
191 							- oursEdit.getBeginA();
192 				} else {
193 					oursBeginB -= oursEdit.getBeginA() - theirsEdit.getBeginA();
194 				}
195 
196 				// combine edits:
197 				// Maybe an Edit on one side corresponds to multiple Edits on
198 				// the other side. Then we have to combine the Edits of the
199 				// other side - so in the end we can merge together two single
200 				// edits.
201 				//
202 				// It is important to notice that this combining will extend the
203 				// ranges of our conflict always downwards (towards the end of
204 				// the content). The starts of the conflicting ranges in ours
205 				// and theirs are not touched here.
206 				//
207 				// This combining is an iterative process: after we have
208 				// combined some edits we have to do the check again. The
209 				// combined edits could now correspond to multiple edits on the
210 				// other side.
211 				//
212 				// Example: when this combining algorithm works on the following
213 				// edits
214 				// oursEdits=((0-5,0-5),(6-8,6-8),(10-11,10-11)) and
215 				// theirsEdits=((0-1,0-1),(2-3,2-3),(5-7,5-7))
216 				// it will merge them into
217 				// oursEdits=((0-8,0-8),(10-11,10-11)) and
218 				// theirsEdits=((0-7,0-7))
219 				//
220 				// Since the only interesting thing to us is how in ours and
221 				// theirs the end of the conflicting range is changing we let
222 				// oursEdit and theirsEdit point to the last conflicting edit
223 				Edit nextOursEdit = nextEdit(baseToOurs);
224 				Edit nextTheirsEdit = nextEdit(baseToTheirs);
225 				for (;;) {
226 					if (oursEdit.getEndA() >= nextTheirsEdit.getBeginA()) {
227 						theirsEdit = nextTheirsEdit;
228 						nextTheirsEdit = nextEdit(baseToTheirs);
229 					} else if (theirsEdit.getEndA() >= nextOursEdit.getBeginA()) {
230 						oursEdit = nextOursEdit;
231 						nextOursEdit = nextEdit(baseToOurs);
232 					} else {
233 						break;
234 					}
235 				}
236 
237 				// harmonize the end of the ranges in A and B
238 				int oursEndB = oursEdit.getEndB();
239 				int theirsEndB = theirsEdit.getEndB();
240 				if (oursEdit.getEndA() < theirsEdit.getEndA()) {
241 					oursEndB += theirsEdit.getEndA() - oursEdit.getEndA();
242 				} else {
243 					theirsEndB += oursEdit.getEndA() - theirsEdit.getEndA();
244 				}
245 
246 				// A conflicting region is found. Strip off common lines in
247 				// in the beginning and the end of the conflicting region
248 
249 				// Determine the minimum length of the conflicting areas in OURS
250 				// and THEIRS. Also determine how much bigger the conflicting
251 				// area in THEIRS is compared to OURS. All that is needed to
252 				// limit the search for common areas at the beginning or end
253 				// (the common areas cannot be bigger then the smaller
254 				// conflicting area. The delta is needed to know whether the
255 				// complete conflicting area is common in OURS and THEIRS.
256 				int minBSize = oursEndB - oursBeginB;
257 				int BSizeDelta = minBSize - (theirsEndB - theirsBeginB);
258 				if (BSizeDelta > 0)
259 					minBSize -= BSizeDelta;
260 
261 				int commonPrefix = 0;
262 				while (commonPrefix < minBSize
263 						&& cmp.equals(ours, oursBeginB + commonPrefix, theirs,
264 								theirsBeginB + commonPrefix))
265 					commonPrefix++;
266 				minBSize -= commonPrefix;
267 				int commonSuffix = 0;
268 				while (commonSuffix < minBSize
269 						&& cmp.equals(ours, oursEndB - commonSuffix - 1, theirs,
270 								theirsEndB - commonSuffix - 1))
271 					commonSuffix++;
272 				minBSize -= commonSuffix;
273 
274 				// Add the common lines at start of conflict
275 				if (commonPrefix > 0)
276 					result.add(1, oursBeginB, oursBeginB + commonPrefix,
277 							ConflictState.NO_CONFLICT);
278 
279 				// Add the conflict (Only if there is a conflict left to report)
280 				if (minBSize > 0 || BSizeDelta != 0) {
281 					result.add(1, oursBeginB + commonPrefix, oursEndB
282 							- commonSuffix,
283 							ConflictState.FIRST_CONFLICTING_RANGE);
284 					result.add(2, theirsBeginB + commonPrefix, theirsEndB
285 							- commonSuffix,
286 							ConflictState.NEXT_CONFLICTING_RANGE);
287 				}
288 
289 				// Add the common lines at end of conflict
290 				if (commonSuffix > 0)
291 					result.add(1, oursEndB - commonSuffix, oursEndB,
292 							ConflictState.NO_CONFLICT);
293 
294 				current = Math.max(oursEdit.getEndA(), theirsEdit.getEndA());
295 				oursEdit = nextOursEdit;
296 				theirsEdit = nextTheirsEdit;
297 			}
298 		}
299 		// maybe we have a common part behind the last edit: copy it to the
300 		// result
301 		if (current < base.size()) {
302 			result.add(0, current, base.size(), ConflictState.NO_CONFLICT);
303 		}
304 		return result;
305 	}
306 
307 	/**
308 	 * Helper method which returns the next Edit for an Iterator over Edits.
309 	 * When there are no more edits left this method will return the constant
310 	 * END_EDIT.
311 	 *
312 	 * @param it
313 	 *            the iterator for which the next edit should be returned
314 	 * @return the next edit from the iterator or END_EDIT if there no more
315 	 *         edits
316 	 */
317 	private static Edit nextEdit(Iterator<Edit> it) {
318 		return (it.hasNext() ? it.next() : END_EDIT);
319 	}
320 }