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