View Javadoc
1   /*
2    * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>,
3    * Copyright (C) 2010-2012, Matthias Sohn <matthias.sohn@sap.com>
4    * Copyright (C) 2012, Research In Motion Limited
5    * and other copyright owners as documented in the project's IP log.
6    *
7    * This program and the accompanying materials are made available
8    * under the terms of the Eclipse Distribution License v1.0 which
9    * accompanies this distribution, is reproduced below, and is
10   * available at http://www.eclipse.org/org/documents/edl-v10.php
11   *
12   * All rights reserved.
13   *
14   * Redistribution and use in source and binary forms, with or
15   * without modification, are permitted provided that the following
16   * conditions are met:
17   *
18   * - Redistributions of source code must retain the above copyright
19   *   notice, this list of conditions and the following disclaimer.
20   *
21   * - Redistributions in binary form must reproduce the above
22   *   copyright notice, this list of conditions and the following
23   *   disclaimer in the documentation and/or other materials provided
24   *   with the distribution.
25   *
26   * - Neither the name of the Eclipse Foundation, Inc. nor the
27   *   names of its contributors may be used to endorse or promote
28   *   products derived from this software without specific prior
29   *   written permission.
30   *
31   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
32   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
33   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
36   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
37   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
39   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
41   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
42   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
43   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44   */
45  package org.eclipse.jgit.merge;
46  
47  import static org.eclipse.jgit.lib.Constants.CHARACTER_ENCODING;
48  import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
49  
50  import java.io.BufferedOutputStream;
51  import java.io.File;
52  import java.io.FileInputStream;
53  import java.io.FileNotFoundException;
54  import java.io.FileOutputStream;
55  import java.io.IOException;
56  import java.io.InputStream;
57  import java.io.OutputStream;
58  import java.util.ArrayList;
59  import java.util.Arrays;
60  import java.util.Collections;
61  import java.util.HashMap;
62  import java.util.Iterator;
63  import java.util.LinkedList;
64  import java.util.List;
65  import java.util.Map;
66  
67  import org.eclipse.jgit.diff.DiffAlgorithm;
68  import org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm;
69  import org.eclipse.jgit.diff.RawText;
70  import org.eclipse.jgit.diff.RawTextComparator;
71  import org.eclipse.jgit.diff.Sequence;
72  import org.eclipse.jgit.dircache.DirCache;
73  import org.eclipse.jgit.dircache.DirCacheBuildIterator;
74  import org.eclipse.jgit.dircache.DirCacheBuilder;
75  import org.eclipse.jgit.dircache.DirCacheCheckout;
76  import org.eclipse.jgit.dircache.DirCacheEntry;
77  import org.eclipse.jgit.errors.CorruptObjectException;
78  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
79  import org.eclipse.jgit.errors.IndexWriteException;
80  import org.eclipse.jgit.errors.MissingObjectException;
81  import org.eclipse.jgit.errors.NoWorkTreeException;
82  import org.eclipse.jgit.lib.ConfigConstants;
83  import org.eclipse.jgit.lib.FileMode;
84  import org.eclipse.jgit.lib.ObjectId;
85  import org.eclipse.jgit.lib.ObjectReader;
86  import org.eclipse.jgit.lib.Repository;
87  import org.eclipse.jgit.revwalk.RevTree;
88  import org.eclipse.jgit.treewalk.AbstractTreeIterator;
89  import org.eclipse.jgit.treewalk.CanonicalTreeParser;
90  import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
91  import org.eclipse.jgit.treewalk.TreeWalk;
92  import org.eclipse.jgit.treewalk.WorkingTreeIterator;
93  import org.eclipse.jgit.treewalk.filter.TreeFilter;
94  import org.eclipse.jgit.util.FS;
95  import org.eclipse.jgit.util.TemporaryBuffer;
96  
97  /**
98   * A three-way merger performing a content-merge if necessary
99   */
100 public class ResolveMerger extends ThreeWayMerger {
101 	/**
102 	 * If the merge fails (means: not stopped because of unresolved conflicts)
103 	 * this enum is used to explain why it failed
104 	 */
105 	public enum MergeFailureReason {
106 		/** the merge failed because of a dirty index */
107 		DIRTY_INDEX,
108 		/** the merge failed because of a dirty workingtree */
109 		DIRTY_WORKTREE,
110 		/** the merge failed because of a file could not be deleted */
111 		COULD_NOT_DELETE
112 	}
113 
114 	/**
115 	 * The tree walk which we'll iterate over to merge entries.
116 	 *
117 	 * @since 3.4
118 	 */
119 	protected NameConflictTreeWalk tw;
120 
121 	/**
122 	 * string versions of a list of commit SHA1s
123 	 *
124 	 * @since 3.0
125 	 */
126 	protected String commitNames[];
127 
128 	/**
129 	 * Index of the base tree within the {@link #tw tree walk}.
130 	 *
131 	 * @since 3.4
132 	 */
133 	protected static final int T_BASE = 0;
134 
135 	/**
136 	 * Index of our tree in withthe {@link #tw tree walk}.
137 	 *
138 	 * @since 3.4
139 	 */
140 	protected static final int T_OURS = 1;
141 
142 	/**
143 	 * Index of their tree within the {@link #tw tree walk}.
144 	 *
145 	 * @since 3.4
146 	 */
147 	protected static final int T_THEIRS = 2;
148 
149 	/**
150 	 * Index of the index tree within the {@link #tw tree walk}.
151 	 *
152 	 * @since 3.4
153 	 */
154 	protected static final int T_INDEX = 3;
155 
156 	/**
157 	 * Index of the working directory tree within the {@link #tw tree walk}.
158 	 *
159 	 * @since 3.4
160 	 */
161 	protected static final int T_FILE = 4;
162 
163 	/**
164 	 * Builder to update the cache during this merge.
165 	 *
166 	 * @since 3.4
167 	 */
168 	protected DirCacheBuilder builder;
169 
170 	/**
171 	 * merge result as tree
172 	 *
173 	 * @since 3.0
174 	 */
175 	protected ObjectId resultTree;
176 
177 	/**
178 	 * Paths that could not be merged by this merger because of an unsolvable
179 	 * conflict.
180 	 *
181 	 * @since 3.4
182 	 */
183 	protected List<String> unmergedPaths = new ArrayList<String>();
184 
185 	/**
186 	 * Files modified during this merge operation.
187 	 *
188 	 * @since 3.4
189 	 */
190 	protected List<String> modifiedFiles = new LinkedList<String>();
191 
192 	/**
193 	 * If the merger has nothing to do for a file but check it out at the end of
194 	 * the operation, it can be added here.
195 	 *
196 	 * @since 3.4
197 	 */
198 	protected Map<String, DirCacheEntry> toBeCheckedOut = new HashMap<String, DirCacheEntry>();
199 
200 	/**
201 	 * Paths in this list will be deleted from the local copy at the end of the
202 	 * operation.
203 	 *
204 	 * @since 3.4
205 	 */
206 	protected List<String> toBeDeleted = new ArrayList<String>();
207 
208 	/**
209 	 * Low-level textual merge results. Will be passed on to the callers in case
210 	 * of conflicts.
211 	 *
212 	 * @since 3.4
213 	 */
214 	protected Map<String, MergeResult<? extends Sequence>> mergeResults = new HashMap<String, MergeResult<? extends Sequence>>();
215 
216 	/**
217 	 * Paths for which the merge failed altogether.
218 	 *
219 	 * @since 3.4
220 	 */
221 	protected Map<String, MergeFailureReason> failingPaths = new HashMap<String, MergeFailureReason>();
222 
223 	/**
224 	 * Updated as we merge entries of the tree walk. Tells us whether we should
225 	 * recurse into the entry if it is a subtree.
226 	 *
227 	 * @since 3.4
228 	 */
229 	protected boolean enterSubtree;
230 
231 	/**
232 	 * Set to true if this merge should work in-memory. The repos dircache and
233 	 * workingtree are not touched by this method. Eventually needed files are
234 	 * created as temporary files and a new empty, in-memory dircache will be
235 	 * used instead the repo's one. Often used for bare repos where the repo
236 	 * doesn't even have a workingtree and dircache.
237 	 * @since 3.0
238 	 */
239 	protected boolean inCore;
240 
241 	/**
242 	 * Set to true if this merger should use the default dircache of the
243 	 * repository and should handle locking and unlocking of the dircache. If
244 	 * this merger should work in-core or if an explicit dircache was specified
245 	 * during construction then this field is set to false.
246 	 * @since 3.0
247 	 */
248 	protected boolean implicitDirCache;
249 
250 	/**
251 	 * Directory cache
252 	 * @since 3.0
253 	 */
254 	protected DirCache dircache;
255 
256 	/**
257 	 * The iterator to access the working tree. If set to <code>null</code> this
258 	 * merger will not touch the working tree.
259 	 * @since 3.0
260 	 */
261 	protected WorkingTreeIterator workingTreeIterator;
262 
263 	/**
264 	 * our merge algorithm
265 	 * @since 3.0
266 	 */
267 	protected MergeAlgorithm mergeAlgorithm;
268 
269 	/**
270 	 * @param local
271 	 * @param inCore
272 	 */
273 	protected ResolveMerger(Repository local, boolean inCore) {
274 		super(local);
275 		SupportedAlgorithm diffAlg = local.getConfig().getEnum(
276 				ConfigConstants.CONFIG_DIFF_SECTION, null,
277 				ConfigConstants.CONFIG_KEY_ALGORITHM,
278 				SupportedAlgorithm.HISTOGRAM);
279 		mergeAlgorithm = new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg));
280 		commitNames = new String[] { "BASE", "OURS", "THEIRS" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
281 		this.inCore = inCore;
282 
283 		if (inCore) {
284 			implicitDirCache = false;
285 			dircache = DirCache.newInCore();
286 		} else {
287 			implicitDirCache = true;
288 		}
289 	}
290 
291 	/**
292 	 * @param local
293 	 */
294 	protected ResolveMerger(Repository local) {
295 		this(local, false);
296 	}
297 
298 	@Override
299 	protected boolean mergeImpl() throws IOException {
300 		if (implicitDirCache)
301 			dircache = getRepository().lockDirCache();
302 
303 		try {
304 			return mergeTrees(mergeBase(), sourceTrees[0], sourceTrees[1],
305 					false);
306 		} finally {
307 			if (implicitDirCache)
308 				dircache.unlock();
309 		}
310 	}
311 
312 	private void checkout() throws NoWorkTreeException, IOException {
313 		// Iterate in reverse so that "folder/file" is deleted before
314 		// "folder". Otherwise this could result in a failing path because
315 		// of a non-empty directory, for which delete() would fail.
316 		for (int i = toBeDeleted.size() - 1; i >= 0; i--) {
317 			String fileName = toBeDeleted.get(i);
318 			File f = new File(db.getWorkTree(), fileName);
319 			if (!f.delete())
320 				if (!f.isDirectory())
321 					failingPaths.put(fileName,
322 							MergeFailureReason.COULD_NOT_DELETE);
323 			modifiedFiles.add(fileName);
324 		}
325 		for (Map.Entry<String, DirCacheEntry> entry : toBeCheckedOut
326 				.entrySet()) {
327 			DirCacheCheckout.checkoutEntry(db, entry.getValue(), reader);
328 			modifiedFiles.add(entry.getKey());
329 		}
330 	}
331 
332 	/**
333 	 * Reverts the worktree after an unsuccessful merge. We know that for all
334 	 * modified files the old content was in the old index and the index
335 	 * contained only stage 0. In case if inCore operation just clear the
336 	 * history of modified files.
337 	 *
338 	 * @throws IOException
339 	 * @throws CorruptObjectException
340 	 * @throws NoWorkTreeException
341 	 * @since 3.4
342 	 */
343 	protected void cleanUp() throws NoWorkTreeException,
344 			CorruptObjectException,
345 			IOException {
346 		if (inCore) {
347 			modifiedFiles.clear();
348 			return;
349 		}
350 
351 		DirCache dc = db.readDirCache();
352 		Iterator<String> mpathsIt=modifiedFiles.iterator();
353 		while(mpathsIt.hasNext()) {
354 			String mpath=mpathsIt.next();
355 			DirCacheEntry entry = dc.getEntry(mpath);
356 			if (entry != null)
357 				DirCacheCheckout.checkoutEntry(db, entry, reader);
358 			mpathsIt.remove();
359 		}
360 	}
361 
362 	/**
363 	 * adds a new path with the specified stage to the index builder
364 	 *
365 	 * @param path
366 	 * @param p
367 	 * @param stage
368 	 * @param lastMod
369 	 * @param len
370 	 * @return the entry which was added to the index
371 	 */
372 	private DirCacheEntry add(byte[] path, CanonicalTreeParser p, int stage,
373 			long lastMod, long len) {
374 		if (p != null && !p.getEntryFileMode().equals(FileMode.TREE)) {
375 			DirCacheEntry e = new DirCacheEntry(path, stage);
376 			e.setFileMode(p.getEntryFileMode());
377 			e.setObjectId(p.getEntryObjectId());
378 			e.setLastModified(lastMod);
379 			e.setLength(len);
380 			builder.add(e);
381 			return e;
382 		}
383 		return null;
384 	}
385 
386 	/**
387 	 * adds a entry to the index builder which is a copy of the specified
388 	 * DirCacheEntry
389 	 *
390 	 * @param e
391 	 *            the entry which should be copied
392 	 *
393 	 * @return the entry which was added to the index
394 	 */
395 	private DirCacheEntry keep(DirCacheEntry e) {
396 		DirCacheEntry newEntry = new DirCacheEntry(e.getPathString(),
397 				e.getStage());
398 		newEntry.setFileMode(e.getFileMode());
399 		newEntry.setObjectId(e.getObjectId());
400 		newEntry.setLastModified(e.getLastModified());
401 		newEntry.setLength(e.getLength());
402 		builder.add(newEntry);
403 		return newEntry;
404 	}
405 
406 	/**
407 	 * Processes one path and tries to merge. This method will do all do all
408 	 * trivial (not content) merges and will also detect if a merge will fail.
409 	 * The merge will fail when one of the following is true
410 	 * <ul>
411 	 * <li>the index entry does not match the entry in ours. When merging one
412 	 * branch into the current HEAD, ours will point to HEAD and theirs will
413 	 * point to the other branch. It is assumed that the index matches the HEAD
414 	 * because it will only not match HEAD if it was populated before the merge
415 	 * operation. But the merge commit should not accidentally contain
416 	 * modifications done before the merge. Check the <a href=
417 	 * "http://www.kernel.org/pub/software/scm/git/docs/git-read-tree.html#_3_way_merge"
418 	 * >git read-tree</a> documentation for further explanations.</li>
419 	 * <li>A conflict was detected and the working-tree file is dirty. When a
420 	 * conflict is detected the content-merge algorithm will try to write a
421 	 * merged version into the working-tree. If the file is dirty we would
422 	 * override unsaved data.</li>
423 	 * </ul>
424 	 *
425 	 * @param base
426 	 *            the common base for ours and theirs
427 	 * @param ours
428 	 *            the ours side of the merge. When merging a branch into the
429 	 *            HEAD ours will point to HEAD
430 	 * @param theirs
431 	 *            the theirs side of the merge. When merging a branch into the
432 	 *            current HEAD theirs will point to the branch which is merged
433 	 *            into HEAD.
434 	 * @param index
435 	 *            the index entry
436 	 * @param work
437 	 *            the file in the working tree
438 	 * @param ignoreConflicts
439 	 *            see
440 	 *            {@link ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)}
441 	 * @return <code>false</code> if the merge will fail because the index entry
442 	 *         didn't match ours or the working-dir file was dirty and a
443 	 *         conflict occurred
444 	 * @throws MissingObjectException
445 	 * @throws IncorrectObjectTypeException
446 	 * @throws CorruptObjectException
447 	 * @throws IOException
448 	 * @since 3.5
449 	 */
450 	protected boolean processEntry(CanonicalTreeParser base,
451 			CanonicalTreeParser ours, CanonicalTreeParser theirs,
452 			DirCacheBuildIterator index, WorkingTreeIterator work,
453 			boolean ignoreConflicts)
454 			throws MissingObjectException, IncorrectObjectTypeException,
455 			CorruptObjectException, IOException {
456 		enterSubtree = true;
457 		final int modeO = tw.getRawMode(T_OURS);
458 		final int modeT = tw.getRawMode(T_THEIRS);
459 		final int modeB = tw.getRawMode(T_BASE);
460 
461 		if (modeO == 0 && modeT == 0 && modeB == 0)
462 			// File is either untracked or new, staged but uncommitted
463 			return true;
464 
465 		if (isIndexDirty())
466 			return false;
467 
468 		DirCacheEntry ourDce = null;
469 
470 		if (index == null || index.getDirCacheEntry() == null) {
471 			// create a fake DCE, but only if ours is valid. ours is kept only
472 			// in case it is valid, so a null ourDce is ok in all other cases.
473 			if (nonTree(modeO)) {
474 				ourDce = new DirCacheEntry(tw.getRawPath());
475 				ourDce.setObjectId(tw.getObjectId(T_OURS));
476 				ourDce.setFileMode(tw.getFileMode(T_OURS));
477 			}
478 		} else {
479 			ourDce = index.getDirCacheEntry();
480 		}
481 
482 		if (nonTree(modeO) && nonTree(modeT) && tw.idEqual(T_OURS, T_THEIRS)) {
483 			// OURS and THEIRS have equal content. Check the file mode
484 			if (modeO == modeT) {
485 				// content and mode of OURS and THEIRS are equal: it doesn't
486 				// matter which one we choose. OURS is chosen. Since the index
487 				// is clean (the index matches already OURS) we can keep the existing one
488 				keep(ourDce);
489 				// no checkout needed!
490 				return true;
491 			} else {
492 				// same content but different mode on OURS and THEIRS.
493 				// Try to merge the mode and report an error if this is
494 				// not possible.
495 				int newMode = mergeFileModes(modeB, modeO, modeT);
496 				if (newMode != FileMode.MISSING.getBits()) {
497 					if (newMode == modeO)
498 						// ours version is preferred
499 						keep(ourDce);
500 					else {
501 						// the preferred version THEIRS has a different mode
502 						// than ours. Check it out!
503 						if (isWorktreeDirty(work, ourDce))
504 							return false;
505 						// we know about length and lastMod only after we have written the new content.
506 						// This will happen later. Set these values to 0 for know.
507 						DirCacheEntry e = add(tw.getRawPath(), theirs,
508 								DirCacheEntry.STAGE_0, 0, 0);
509 						toBeCheckedOut.put(tw.getPathString(), e);
510 					}
511 					return true;
512 				} else {
513 					// FileModes are not mergeable. We found a conflict on modes.
514 					// For conflicting entries we don't know lastModified and length.
515 					add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
516 					add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
517 					add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
518 					unmergedPaths.add(tw.getPathString());
519 					mergeResults.put(
520 							tw.getPathString(),
521 							new MergeResult<RawText>(Collections
522 									.<RawText> emptyList()));
523 				}
524 				return true;
525 			}
526 		}
527 
528 		if (nonTree(modeO) && modeB == modeT && tw.idEqual(T_BASE, T_THEIRS)) {
529 			// THEIRS was not changed compared to BASE. All changes must be in
530 			// OURS. OURS is chosen. We can keep the existing entry.
531 			keep(ourDce);
532 			// no checkout needed!
533 			return true;
534 		}
535 
536 		if (modeB == modeO && tw.idEqual(T_BASE, T_OURS)) {
537 			// OURS was not changed compared to BASE. All changes must be in
538 			// THEIRS. THEIRS is chosen.
539 
540 			// Check worktree before checking out THEIRS
541 			if (isWorktreeDirty(work, ourDce))
542 				return false;
543 			if (nonTree(modeT)) {
544 				// we know about length and lastMod only after we have written
545 				// the new content.
546 				// This will happen later. Set these values to 0 for know.
547 				DirCacheEntry e = add(tw.getRawPath(), theirs,
548 						DirCacheEntry.STAGE_0, 0, 0);
549 				if (e != null)
550 					toBeCheckedOut.put(tw.getPathString(), e);
551 				return true;
552 			} else if (modeT == 0 && modeB != 0) {
553 				// we want THEIRS ... but THEIRS contains the deletion of the
554 				// file. Also, do not complain if the file is already deleted
555 				// locally. This complements the test in isWorktreeDirty() for
556 				// the same case.
557 				if (tw.getTreeCount() > T_FILE && tw.getRawMode(T_FILE) == 0)
558 					return true;
559 				toBeDeleted.add(tw.getPathString());
560 				return true;
561 			}
562 		}
563 
564 		if (tw.isSubtree()) {
565 			// file/folder conflicts: here I want to detect only file/folder
566 			// conflict between ours and theirs. file/folder conflicts between
567 			// base/index/workingTree and something else are not relevant or
568 			// detected later
569 			if (nonTree(modeO) && !nonTree(modeT)) {
570 				if (nonTree(modeB))
571 					add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
572 				add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
573 				unmergedPaths.add(tw.getPathString());
574 				enterSubtree = false;
575 				return true;
576 			}
577 			if (nonTree(modeT) && !nonTree(modeO)) {
578 				if (nonTree(modeB))
579 					add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
580 				add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
581 				unmergedPaths.add(tw.getPathString());
582 				enterSubtree = false;
583 				return true;
584 			}
585 
586 			// ours and theirs are both folders or both files (and treewalk
587 			// tells us we are in a subtree because of index or working-dir).
588 			// If they are both folders no content-merge is required - we can
589 			// return here.
590 			if (!nonTree(modeO))
591 				return true;
592 
593 			// ours and theirs are both files, just fall out of the if block
594 			// and do the content merge
595 		}
596 
597 		if (nonTree(modeO) && nonTree(modeT)) {
598 			// Check worktree before modifying files
599 			if (isWorktreeDirty(work, ourDce))
600 				return false;
601 
602 			// Don't attempt to resolve submodule link conflicts
603 			if (isGitLink(modeO) || isGitLink(modeT)) {
604 				add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
605 				add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
606 				add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
607 				unmergedPaths.add(tw.getPathString());
608 				return true;
609 			}
610 
611 			MergeResult<RawText> result = contentMerge(base, ours, theirs);
612 			if (ignoreConflicts)
613 				result.setContainsConflicts(false);
614 			updateIndex(base, ours, theirs, result);
615 			if (result.containsConflicts() && !ignoreConflicts)
616 				unmergedPaths.add(tw.getPathString());
617 			modifiedFiles.add(tw.getPathString());
618 		} else if (modeO != modeT) {
619 			// OURS or THEIRS has been deleted
620 			if (((modeO != 0 && !tw.idEqual(T_BASE, T_OURS)) || (modeT != 0 && !tw
621 					.idEqual(T_BASE, T_THEIRS)))) {
622 
623 				add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
624 				add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
625 				DirCacheEntry e = add(tw.getRawPath(), theirs,
626 						DirCacheEntry.STAGE_3, 0, 0);
627 
628 				// OURS was deleted checkout THEIRS
629 				if (modeO == 0) {
630 					// Check worktree before checking out THEIRS
631 					if (isWorktreeDirty(work, ourDce))
632 						return false;
633 					if (nonTree(modeT)) {
634 						if (e != null)
635 							toBeCheckedOut.put(tw.getPathString(), e);
636 					}
637 				}
638 
639 				unmergedPaths.add(tw.getPathString());
640 
641 				// generate a MergeResult for the deleted file
642 				mergeResults.put(tw.getPathString(),
643 						contentMerge(base, ours, theirs));
644 			}
645 		}
646 		return true;
647 	}
648 
649 	/**
650 	 * Does the content merge. The three texts base, ours and theirs are
651 	 * specified with {@link CanonicalTreeParser}. If any of the parsers is
652 	 * specified as <code>null</code> then an empty text will be used instead.
653 	 *
654 	 * @param base
655 	 * @param ours
656 	 * @param theirs
657 	 *
658 	 * @return the result of the content merge
659 	 * @throws IOException
660 	 */
661 	private MergeResult<RawText> contentMerge(CanonicalTreeParser base,
662 			CanonicalTreeParser ours, CanonicalTreeParser theirs)
663 			throws IOException {
664 		RawText baseText = base == null ? RawText.EMPTY_TEXT : getRawText(
665 				base.getEntryObjectId(), reader);
666 		RawText ourText = ours == null ? RawText.EMPTY_TEXT : getRawText(
667 				ours.getEntryObjectId(), reader);
668 		RawText theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText(
669 				theirs.getEntryObjectId(), reader);
670 		return (mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText,
671 				ourText, theirsText));
672 	}
673 
674 	private boolean isIndexDirty() {
675 		if (inCore)
676 			return false;
677 
678 		final int modeI = tw.getRawMode(T_INDEX);
679 		final int modeO = tw.getRawMode(T_OURS);
680 
681 		// Index entry has to match ours to be considered clean
682 		final boolean isDirty = nonTree(modeI)
683 				&& !(modeO == modeI && tw.idEqual(T_INDEX, T_OURS));
684 		if (isDirty)
685 			failingPaths
686 					.put(tw.getPathString(), MergeFailureReason.DIRTY_INDEX);
687 		return isDirty;
688 	}
689 
690 	private boolean isWorktreeDirty(WorkingTreeIterator work,
691 			DirCacheEntry ourDce) throws IOException {
692 		if (work == null)
693 			return false;
694 
695 		final int modeF = tw.getRawMode(T_FILE);
696 		final int modeO = tw.getRawMode(T_OURS);
697 
698 		// Worktree entry has to match ours to be considered clean
699 		boolean isDirty;
700 		if (ourDce != null)
701 			isDirty = work.isModified(ourDce, true, reader);
702 		else {
703 			isDirty = work.isModeDifferent(modeO);
704 			if (!isDirty && nonTree(modeF))
705 				isDirty = !tw.idEqual(T_FILE, T_OURS);
706 		}
707 
708 		// Ignore existing empty directories
709 		if (isDirty && modeF == FileMode.TYPE_TREE
710 				&& modeO == FileMode.TYPE_MISSING)
711 			isDirty = false;
712 		if (isDirty)
713 			failingPaths.put(tw.getPathString(),
714 					MergeFailureReason.DIRTY_WORKTREE);
715 		return isDirty;
716 	}
717 
718 	/**
719 	 * Updates the index after a content merge has happened. If no conflict has
720 	 * occurred this includes persisting the merged content to the object
721 	 * database. In case of conflicts this method takes care to write the
722 	 * correct stages to the index.
723 	 *
724 	 * @param base
725 	 * @param ours
726 	 * @param theirs
727 	 * @param result
728 	 * @throws FileNotFoundException
729 	 * @throws IOException
730 	 */
731 	private void updateIndex(CanonicalTreeParser base,
732 			CanonicalTreeParser ours, CanonicalTreeParser theirs,
733 			MergeResult<RawText> result) throws FileNotFoundException,
734 			IOException {
735 		File mergedFile = !inCore ? writeMergedFile(result) : null;
736 		if (result.containsConflicts()) {
737 			// A conflict occurred, the file will contain conflict markers
738 			// the index will be populated with the three stages and the
739 			// workdir (if used) contains the halfway merged content.
740 			add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, 0, 0);
741 			add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, 0, 0);
742 			add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, 0, 0);
743 			mergeResults.put(tw.getPathString(), result);
744 			return;
745 		}
746 
747 		// No conflict occurred, the file will contain fully merged content.
748 		// The index will be populated with the new merged version.
749 		DirCacheEntry dce = new DirCacheEntry(tw.getPathString());
750 
751 		// Set the mode for the new content. Fall back to REGULAR_FILE if
752 		// we can't merge modes of OURS and THEIRS.
753 		int newMode = mergeFileModes(
754 				tw.getRawMode(0),
755 				tw.getRawMode(1),
756 				tw.getRawMode(2));
757 		dce.setFileMode(newMode == FileMode.MISSING.getBits()
758 				? FileMode.REGULAR_FILE
759 				: FileMode.fromBits(newMode));
760 		if (mergedFile != null) {
761 			long len = mergedFile.length();
762 			dce.setLastModified(mergedFile.lastModified());
763 			dce.setLength((int) len);
764 			InputStream is = new FileInputStream(mergedFile);
765 			try {
766 				dce.setObjectId(getObjectInserter().insert(OBJ_BLOB, len, is));
767 			} finally {
768 				is.close();
769 			}
770 		} else
771 			dce.setObjectId(insertMergeResult(result));
772 		builder.add(dce);
773 	}
774 
775 	/**
776 	 * Writes merged file content to the working tree.
777 	 *
778 	 * @param result
779 	 *            the result of the content merge
780 	 * @return the working tree file to which the merged content was written.
781 	 * @throws FileNotFoundException
782 	 * @throws IOException
783 	 */
784 	private File writeMergedFile(MergeResult<RawText> result)
785 			throws FileNotFoundException, IOException {
786 		File workTree = db.getWorkTree();
787 		if (workTree == null)
788 			// TODO: This should be handled by WorkingTreeIterators which
789 			// support write operations
790 			throw new UnsupportedOperationException();
791 
792 		FS fs = db.getFS();
793 		File of = new File(workTree, tw.getPathString());
794 		File parentFolder = of.getParentFile();
795 		if (!fs.exists(parentFolder))
796 			parentFolder.mkdirs();
797 		try (OutputStream os = new BufferedOutputStream(
798 				new FileOutputStream(of))) {
799 			new MergeFormatter().formatMerge(os, result,
800 					Arrays.asList(commitNames), CHARACTER_ENCODING);
801 		}
802 		return of;
803 	}
804 
805 	private ObjectId insertMergeResult(MergeResult<RawText> result)
806 			throws IOException {
807 		TemporaryBuffer.LocalFile buf = new TemporaryBuffer.LocalFile(
808 				db.getDirectory(), 10 << 20);
809 		try {
810 			new MergeFormatter().formatMerge(buf, result,
811 					Arrays.asList(commitNames), CHARACTER_ENCODING);
812 			buf.close();
813 			try (InputStream in = buf.openInputStream()) {
814 				return getObjectInserter().insert(OBJ_BLOB, buf.length(), in);
815 			}
816 		} finally {
817 			buf.destroy();
818 		}
819 	}
820 
821 	/**
822 	 * Try to merge filemodes. If only ours or theirs have changed the mode
823 	 * (compared to base) we choose that one. If ours and theirs have equal
824 	 * modes return that one. If also that is not the case the modes are not
825 	 * mergeable. Return {@link FileMode#MISSING} int that case.
826 	 *
827 	 * @param modeB
828 	 *            filemode found in BASE
829 	 * @param modeO
830 	 *            filemode found in OURS
831 	 * @param modeT
832 	 *            filemode found in THEIRS
833 	 *
834 	 * @return the merged filemode or {@link FileMode#MISSING} in case of a
835 	 *         conflict
836 	 */
837 	private int mergeFileModes(int modeB, int modeO, int modeT) {
838 		if (modeO == modeT)
839 			return modeO;
840 		if (modeB == modeO)
841 			// Base equal to Ours -> chooses Theirs if that is not missing
842 			return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT;
843 		if (modeB == modeT)
844 			// Base equal to Theirs -> chooses Ours if that is not missing
845 			return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO;
846 		return FileMode.MISSING.getBits();
847 	}
848 
849 	private static RawText getRawText(ObjectId id, ObjectReader reader)
850 			throws IOException {
851 		if (id.equals(ObjectId.zeroId()))
852 			return new RawText(new byte[] {});
853 		return new RawText(reader.open(id, OBJ_BLOB).getCachedBytes());
854 	}
855 
856 	private static boolean nonTree(final int mode) {
857 		return mode != 0 && !FileMode.TREE.equals(mode);
858 	}
859 
860 	private static boolean isGitLink(final int mode) {
861 		return FileMode.GITLINK.equals(mode);
862 	}
863 
864 	@Override
865 	public ObjectId getResultTreeId() {
866 		return (resultTree == null) ? null : resultTree.toObjectId();
867 	}
868 
869 	/**
870 	 * @param commitNames
871 	 *            the names of the commits as they would appear in conflict
872 	 *            markers
873 	 */
874 	public void setCommitNames(String[] commitNames) {
875 		this.commitNames = commitNames;
876 	}
877 
878 	/**
879 	 * @return the names of the commits as they would appear in conflict
880 	 *         markers.
881 	 */
882 	public String[] getCommitNames() {
883 		return commitNames;
884 	}
885 
886 	/**
887 	 * @return the paths with conflicts. This is a subset of the files listed
888 	 *         by {@link #getModifiedFiles()}
889 	 */
890 	public List<String> getUnmergedPaths() {
891 		return unmergedPaths;
892 	}
893 
894 	/**
895 	 * @return the paths of files which have been modified by this merge. A
896 	 *         file will be modified if a content-merge works on this path or if
897 	 *         the merge algorithm decides to take the theirs-version. This is a
898 	 *         superset of the files listed by {@link #getUnmergedPaths()}.
899 	 */
900 	public List<String> getModifiedFiles() {
901 		return modifiedFiles;
902 	}
903 
904 	/**
905 	 * @return a map which maps the paths of files which have to be checked out
906 	 *         because the merge created new fully-merged content for this file
907 	 *         into the index. This means: the merge wrote a new stage 0 entry
908 	 *         for this path.
909 	 */
910 	public Map<String, DirCacheEntry> getToBeCheckedOut() {
911 		return toBeCheckedOut;
912 	}
913 
914 	/**
915 	 * @return the mergeResults
916 	 */
917 	public Map<String, MergeResult<? extends Sequence>> getMergeResults() {
918 		return mergeResults;
919 	}
920 
921 	/**
922 	 * @return lists paths causing this merge to fail (not stopped because of a
923 	 *         conflict). <code>null</code> is returned if this merge didn't
924 	 *         fail.
925 	 */
926 	public Map<String, MergeFailureReason> getFailingPaths() {
927 		return (failingPaths.size() == 0) ? null : failingPaths;
928 	}
929 
930 	/**
931 	 * Returns whether this merge failed (i.e. not stopped because of a
932 	 * conflict)
933 	 *
934 	 * @return <code>true</code> if a failure occurred, <code>false</code>
935 	 *         otherwise
936 	 */
937 	public boolean failed() {
938 		return failingPaths.size() > 0;
939 	}
940 
941 	/**
942 	 * Sets the DirCache which shall be used by this merger. If the DirCache is
943 	 * not set explicitly and if this merger doesn't work in-core, this merger
944 	 * will implicitly get and lock a default DirCache. If the DirCache is
945 	 * explicitly set the caller is responsible to lock it in advance. Finally
946 	 * the merger will call {@link DirCache#commit()} which requires that the
947 	 * DirCache is locked. If the {@link #mergeImpl()} returns without throwing
948 	 * an exception the lock will be released. In case of exceptions the caller
949 	 * is responsible to release the lock.
950 	 *
951 	 * @param dc
952 	 *            the DirCache to set
953 	 */
954 	public void setDirCache(DirCache dc) {
955 		this.dircache = dc;
956 		implicitDirCache = false;
957 	}
958 
959 	/**
960 	 * Sets the WorkingTreeIterator to be used by this merger. If no
961 	 * WorkingTreeIterator is set this merger will ignore the working tree and
962 	 * fail if a content merge is necessary.
963 	 * <p>
964 	 * TODO: enhance WorkingTreeIterator to support write operations. Then this
965 	 * merger will be able to merge with a different working tree abstraction.
966 	 *
967 	 * @param workingTreeIterator
968 	 *            the workingTreeIt to set
969 	 */
970 	public void setWorkingTreeIterator(WorkingTreeIterator workingTreeIterator) {
971 		this.workingTreeIterator = workingTreeIterator;
972 	}
973 
974 
975 	/**
976 	 * The resolve conflict way of three way merging
977 	 *
978 	 * @param baseTree
979 	 * @param headTree
980 	 * @param mergeTree
981 	 * @param ignoreConflicts
982 	 *            Controls what to do in case a content-merge is done and a
983 	 *            conflict is detected. The default setting for this should be
984 	 *            <code>false</code>. In this case the working tree file is
985 	 *            filled with new content (containing conflict markers) and the
986 	 *            index is filled with multiple stages containing BASE, OURS and
987 	 *            THEIRS content. Having such non-0 stages is the sign to git
988 	 *            tools that there are still conflicts for that path.
989 	 *            <p>
990 	 *            If <code>true</code> is specified the behavior is different.
991 	 *            In case a conflict is detected the working tree file is again
992 	 *            filled with new content (containing conflict markers). But
993 	 *            also stage 0 of the index is filled with that content. No
994 	 *            other stages are filled. Means: there is no conflict on that
995 	 *            path but the new content (including conflict markers) is
996 	 *            stored as successful merge result. This is needed in the
997 	 *            context of {@link RecursiveMerger} where when determining
998 	 *            merge bases we don't want to deal with content-merge
999 	 *            conflicts.
1000 	 * @return whether the trees merged cleanly
1001 	 * @throws IOException
1002 	 * @since 3.5
1003 	 */
1004 	protected boolean mergeTrees(AbstractTreeIterator baseTree,
1005 			RevTree headTree, RevTree mergeTree, boolean ignoreConflicts)
1006 			throws IOException {
1007 
1008 		builder = dircache.builder();
1009 		DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder);
1010 
1011 		tw = new NameConflictTreeWalk(reader);
1012 		tw.addTree(baseTree);
1013 		tw.addTree(headTree);
1014 		tw.addTree(mergeTree);
1015 		tw.addTree(buildIt);
1016 		if (workingTreeIterator != null) {
1017 			tw.addTree(workingTreeIterator);
1018 		} else {
1019 			tw.setFilter(TreeFilter.ANY_DIFF);
1020 		}
1021 
1022 		if (!mergeTreeWalk(tw, ignoreConflicts)) {
1023 			return false;
1024 		}
1025 
1026 		if (!inCore) {
1027 			// No problem found. The only thing left to be done is to
1028 			// checkout all files from "theirs" which have been selected to
1029 			// go into the new index.
1030 			checkout();
1031 
1032 			// All content-merges are successfully done. If we can now write the
1033 			// new index we are on quite safe ground. Even if the checkout of
1034 			// files coming from "theirs" fails the user can work around such
1035 			// failures by checking out the index again.
1036 			if (!builder.commit()) {
1037 				cleanUp();
1038 				throw new IndexWriteException();
1039 			}
1040 			builder = null;
1041 
1042 		} else {
1043 			builder.finish();
1044 			builder = null;
1045 		}
1046 
1047 		if (getUnmergedPaths().isEmpty() && !failed()) {
1048 			resultTree = dircache.writeTree(getObjectInserter());
1049 			return true;
1050 		} else {
1051 			resultTree = null;
1052 			return false;
1053 		}
1054 	}
1055 
1056 	/**
1057 	 * Process the given TreeWalk's entries.
1058 	 *
1059 	 * @param treeWalk
1060 	 *            The walk to iterate over.
1061 	 * @param ignoreConflicts
1062 	 *            see
1063 	 *            {@link ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)}
1064 	 * @return Whether the trees merged cleanly.
1065 	 * @throws IOException
1066 	 * @since 3.5
1067 	 */
1068 	protected boolean mergeTreeWalk(TreeWalk treeWalk, boolean ignoreConflicts)
1069 			throws IOException {
1070 		boolean hasWorkingTreeIterator = tw.getTreeCount() > T_FILE;
1071 		while (treeWalk.next()) {
1072 			if (!processEntry(
1073 					treeWalk.getTree(T_BASE, CanonicalTreeParser.class),
1074 					treeWalk.getTree(T_OURS, CanonicalTreeParser.class),
1075 					treeWalk.getTree(T_THEIRS, CanonicalTreeParser.class),
1076 					treeWalk.getTree(T_INDEX, DirCacheBuildIterator.class),
1077 					hasWorkingTreeIterator ? treeWalk.getTree(T_FILE,
1078 							WorkingTreeIterator.class) : null, ignoreConflicts)) {
1079 				cleanUp();
1080 				return false;
1081 			}
1082 			if (treeWalk.isSubtree() && enterSubtree)
1083 				treeWalk.enterSubtree();
1084 		}
1085 		return true;
1086 	}
1087 }