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 java.nio.charset.StandardCharsets.UTF_8;
50  import static java.time.Instant.EPOCH;
51  import static org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm.HISTOGRAM;
52  import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_DIFF_SECTION;
53  import static org.eclipse.jgit.lib.ConfigConstants.CONFIG_KEY_ALGORITHM;
54  import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
55  
56  import java.io.BufferedOutputStream;
57  import java.io.File;
58  import java.io.FileNotFoundException;
59  import java.io.FileOutputStream;
60  import java.io.IOException;
61  import java.io.InputStream;
62  import java.io.OutputStream;
63  import java.time.Instant;
64  import java.util.ArrayList;
65  import java.util.Arrays;
66  import java.util.Collections;
67  import java.util.HashMap;
68  import java.util.Iterator;
69  import java.util.LinkedList;
70  import java.util.List;
71  import java.util.Map;
72  
73  import org.eclipse.jgit.attributes.Attributes;
74  import org.eclipse.jgit.diff.DiffAlgorithm;
75  import org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm;
76  import org.eclipse.jgit.diff.RawText;
77  import org.eclipse.jgit.diff.RawTextComparator;
78  import org.eclipse.jgit.diff.Sequence;
79  import org.eclipse.jgit.dircache.DirCache;
80  import org.eclipse.jgit.dircache.DirCacheBuildIterator;
81  import org.eclipse.jgit.dircache.DirCacheBuilder;
82  import org.eclipse.jgit.dircache.DirCacheCheckout;
83  import org.eclipse.jgit.dircache.DirCacheCheckout.CheckoutMetadata;
84  import org.eclipse.jgit.dircache.DirCacheEntry;
85  import org.eclipse.jgit.errors.BinaryBlobException;
86  import org.eclipse.jgit.errors.CorruptObjectException;
87  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
88  import org.eclipse.jgit.errors.IndexWriteException;
89  import org.eclipse.jgit.errors.MissingObjectException;
90  import org.eclipse.jgit.errors.NoWorkTreeException;
91  import org.eclipse.jgit.lib.Config;
92  import org.eclipse.jgit.lib.ConfigConstants;
93  import org.eclipse.jgit.lib.Constants;
94  import org.eclipse.jgit.lib.CoreConfig.EolStreamType;
95  import org.eclipse.jgit.lib.FileMode;
96  import org.eclipse.jgit.lib.ObjectId;
97  import org.eclipse.jgit.lib.ObjectInserter;
98  import org.eclipse.jgit.lib.ObjectLoader;
99  import org.eclipse.jgit.lib.Repository;
100 import org.eclipse.jgit.revwalk.RevTree;
101 import org.eclipse.jgit.storage.pack.PackConfig;
102 import org.eclipse.jgit.submodule.SubmoduleConflict;
103 import org.eclipse.jgit.treewalk.AbstractTreeIterator;
104 import org.eclipse.jgit.treewalk.CanonicalTreeParser;
105 import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
106 import org.eclipse.jgit.treewalk.TreeWalk;
107 import org.eclipse.jgit.treewalk.TreeWalk.OperationType;
108 import org.eclipse.jgit.treewalk.WorkingTreeIterator;
109 import org.eclipse.jgit.treewalk.WorkingTreeOptions;
110 import org.eclipse.jgit.treewalk.filter.TreeFilter;
111 import org.eclipse.jgit.util.FS;
112 import org.eclipse.jgit.util.LfsFactory;
113 import org.eclipse.jgit.util.LfsFactory.LfsInputStream;
114 import org.eclipse.jgit.util.TemporaryBuffer;
115 import org.eclipse.jgit.util.io.EolStreamTypeUtil;
116 
117 /**
118  * A three-way merger performing a content-merge if necessary
119  */
120 public class ResolveMerger extends ThreeWayMerger {
121 	/**
122 	 * If the merge fails (means: not stopped because of unresolved conflicts)
123 	 * this enum is used to explain why it failed
124 	 */
125 	public enum MergeFailureReason {
126 		/** the merge failed because of a dirty index */
127 		DIRTY_INDEX,
128 		/** the merge failed because of a dirty workingtree */
129 		DIRTY_WORKTREE,
130 		/** the merge failed because of a file could not be deleted */
131 		COULD_NOT_DELETE
132 	}
133 
134 	/**
135 	 * The tree walk which we'll iterate over to merge entries.
136 	 *
137 	 * @since 3.4
138 	 */
139 	protected NameConflictTreeWalk tw;
140 
141 	/**
142 	 * string versions of a list of commit SHA1s
143 	 *
144 	 * @since 3.0
145 	 */
146 	protected String commitNames[];
147 
148 	/**
149 	 * Index of the base tree within the {@link #tw tree walk}.
150 	 *
151 	 * @since 3.4
152 	 */
153 	protected static final int T_BASE = 0;
154 
155 	/**
156 	 * Index of our tree in withthe {@link #tw tree walk}.
157 	 *
158 	 * @since 3.4
159 	 */
160 	protected static final int T_OURS = 1;
161 
162 	/**
163 	 * Index of their tree within the {@link #tw tree walk}.
164 	 *
165 	 * @since 3.4
166 	 */
167 	protected static final int T_THEIRS = 2;
168 
169 	/**
170 	 * Index of the index tree within the {@link #tw tree walk}.
171 	 *
172 	 * @since 3.4
173 	 */
174 	protected static final int T_INDEX = 3;
175 
176 	/**
177 	 * Index of the working directory tree within the {@link #tw tree walk}.
178 	 *
179 	 * @since 3.4
180 	 */
181 	protected static final int T_FILE = 4;
182 
183 	/**
184 	 * Builder to update the cache during this merge.
185 	 *
186 	 * @since 3.4
187 	 */
188 	protected DirCacheBuilder builder;
189 
190 	/**
191 	 * merge result as tree
192 	 *
193 	 * @since 3.0
194 	 */
195 	protected ObjectId resultTree;
196 
197 	/**
198 	 * Paths that could not be merged by this merger because of an unsolvable
199 	 * conflict.
200 	 *
201 	 * @since 3.4
202 	 */
203 	protected List<String> unmergedPaths = new ArrayList<>();
204 
205 	/**
206 	 * Files modified during this merge operation.
207 	 *
208 	 * @since 3.4
209 	 */
210 	protected List<String> modifiedFiles = new LinkedList<>();
211 
212 	/**
213 	 * If the merger has nothing to do for a file but check it out at the end of
214 	 * the operation, it can be added here.
215 	 *
216 	 * @since 3.4
217 	 */
218 	protected Map<String, DirCacheEntry> toBeCheckedOut = new HashMap<>();
219 
220 	/**
221 	 * Paths in this list will be deleted from the local copy at the end of the
222 	 * operation.
223 	 *
224 	 * @since 3.4
225 	 */
226 	protected List<String> toBeDeleted = new ArrayList<>();
227 
228 	/**
229 	 * Low-level textual merge results. Will be passed on to the callers in case
230 	 * of conflicts.
231 	 *
232 	 * @since 3.4
233 	 */
234 	protected Map<String, MergeResult<? extends Sequence>> mergeResults = new HashMap<>();
235 
236 	/**
237 	 * Paths for which the merge failed altogether.
238 	 *
239 	 * @since 3.4
240 	 */
241 	protected Map<String, MergeFailureReason> failingPaths = new HashMap<>();
242 
243 	/**
244 	 * Updated as we merge entries of the tree walk. Tells us whether we should
245 	 * recurse into the entry if it is a subtree.
246 	 *
247 	 * @since 3.4
248 	 */
249 	protected boolean enterSubtree;
250 
251 	/**
252 	 * Set to true if this merge should work in-memory. The repos dircache and
253 	 * workingtree are not touched by this method. Eventually needed files are
254 	 * created as temporary files and a new empty, in-memory dircache will be
255 	 * used instead the repo's one. Often used for bare repos where the repo
256 	 * doesn't even have a workingtree and dircache.
257 	 * @since 3.0
258 	 */
259 	protected boolean inCore;
260 
261 	/**
262 	 * Set to true if this merger should use the default dircache of the
263 	 * repository and should handle locking and unlocking of the dircache. If
264 	 * this merger should work in-core or if an explicit dircache was specified
265 	 * during construction then this field is set to false.
266 	 * @since 3.0
267 	 */
268 	protected boolean implicitDirCache;
269 
270 	/**
271 	 * Directory cache
272 	 * @since 3.0
273 	 */
274 	protected DirCache dircache;
275 
276 	/**
277 	 * The iterator to access the working tree. If set to <code>null</code> this
278 	 * merger will not touch the working tree.
279 	 * @since 3.0
280 	 */
281 	protected WorkingTreeIterator workingTreeIterator;
282 
283 	/**
284 	 * our merge algorithm
285 	 * @since 3.0
286 	 */
287 	protected MergeAlgorithm mergeAlgorithm;
288 
289 	/**
290 	 * The {@link WorkingTreeOptions} are needed to determine line endings for
291 	 * merged files.
292 	 *
293 	 * @since 4.11
294 	 */
295 	protected WorkingTreeOptions workingTreeOptions;
296 
297 	/**
298 	 * The size limit (bytes) which controls a file to be stored in {@code Heap}
299 	 * or {@code LocalFile} during the merge.
300 	 */
301 	private int inCoreLimit;
302 
303 	/**
304 	 * Keeps {@link CheckoutMetadata} for {@link #checkout()} and
305 	 * {@link #cleanUp()}.
306 	 */
307 	private Map<String, CheckoutMetadata> checkoutMetadata;
308 
309 	private static MergeAlgorithm getMergeAlgorithm(Config config) {
310 		SupportedAlgorithm diffAlg = config.getEnum(
311 				CONFIG_DIFF_SECTION, null, CONFIG_KEY_ALGORITHM,
312 				HISTOGRAM);
313 		return new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg));
314 	}
315 
316 	private static int getInCoreLimit(Config config) {
317 		return config.getInt(
318 				ConfigConstants.CONFIG_MERGE_SECTION, ConfigConstants.CONFIG_KEY_IN_CORE_LIMIT, 10 << 20);
319 	}
320 
321 	private static String[] defaultCommitNames() {
322 		return new String[] { "BASE", "OURS", "THEIRS" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
323 	}
324 
325 	private static final Attributeshtml#Attributes">Attributes NO_ATTRIBUTES = new Attributes();
326 
327 	/**
328 	 * Constructor for ResolveMerger.
329 	 *
330 	 * @param local
331 	 *            the {@link org.eclipse.jgit.lib.Repository}.
332 	 * @param inCore
333 	 *            a boolean.
334 	 */
335 	protected ResolveMerger(Repository local, boolean inCore) {
336 		super(local);
337 		Config config = local.getConfig();
338 		mergeAlgorithm = getMergeAlgorithm(config);
339 		inCoreLimit = getInCoreLimit(config);
340 		commitNames = defaultCommitNames();
341 		this.inCore = inCore;
342 
343 		if (inCore) {
344 			implicitDirCache = false;
345 			dircache = DirCache.newInCore();
346 		} else {
347 			implicitDirCache = true;
348 			workingTreeOptions = local.getConfig().get(WorkingTreeOptions.KEY);
349 		}
350 	}
351 
352 	/**
353 	 * Constructor for ResolveMerger.
354 	 *
355 	 * @param local
356 	 *            the {@link org.eclipse.jgit.lib.Repository}.
357 	 */
358 	protected ResolveMerger(Repository local) {
359 		this(local, false);
360 	}
361 
362 	/**
363 	 * Constructor for ResolveMerger.
364 	 *
365 	 * @param inserter
366 	 *            an {@link org.eclipse.jgit.lib.ObjectInserter} object.
367 	 * @param config
368 	 *            the repository configuration
369 	 * @since 4.8
370 	 */
371 	protected ResolveMerger(ObjectInserter inserter, Config config) {
372 		super(inserter);
373 		mergeAlgorithm = getMergeAlgorithm(config);
374 		commitNames = defaultCommitNames();
375 		inCore = true;
376 		implicitDirCache = false;
377 		dircache = DirCache.newInCore();
378 	}
379 
380 	/** {@inheritDoc} */
381 	@Override
382 	protected boolean mergeImpl() throws IOException {
383 		if (implicitDirCache) {
384 			dircache = nonNullRepo().lockDirCache();
385 		}
386 		if (!inCore) {
387 			checkoutMetadata = new HashMap<>();
388 		}
389 		try {
390 			return mergeTrees(mergeBase(), sourceTrees[0], sourceTrees[1],
391 					false);
392 		} finally {
393 			checkoutMetadata = null;
394 			if (implicitDirCache) {
395 				dircache.unlock();
396 			}
397 		}
398 	}
399 
400 	private void checkout() throws NoWorkTreeException, IOException {
401 		// Iterate in reverse so that "folder/file" is deleted before
402 		// "folder". Otherwise this could result in a failing path because
403 		// of a non-empty directory, for which delete() would fail.
404 		for (int i = toBeDeleted.size() - 1; i >= 0; i--) {
405 			String fileName = toBeDeleted.get(i);
406 			File f = new File(nonNullRepo().getWorkTree(), fileName);
407 			if (!f.delete())
408 				if (!f.isDirectory())
409 					failingPaths.put(fileName,
410 							MergeFailureReason.COULD_NOT_DELETE);
411 			modifiedFiles.add(fileName);
412 		}
413 		for (Map.Entry<String, DirCacheEntry> entry : toBeCheckedOut
414 				.entrySet()) {
415 			DirCacheEntry cacheEntry = entry.getValue();
416 			if (cacheEntry.getFileMode() == FileMode.GITLINK) {
417 				new File(nonNullRepo().getWorkTree(), entry.getKey()).mkdirs();
418 			} else {
419 				DirCacheCheckout.checkoutEntry(db, cacheEntry, reader, false,
420 						checkoutMetadata.get(entry.getKey()));
421 				modifiedFiles.add(entry.getKey());
422 			}
423 		}
424 	}
425 
426 	/**
427 	 * Reverts the worktree after an unsuccessful merge. We know that for all
428 	 * modified files the old content was in the old index and the index
429 	 * contained only stage 0. In case if inCore operation just clear the
430 	 * history of modified files.
431 	 *
432 	 * @throws java.io.IOException
433 	 * @throws org.eclipse.jgit.errors.CorruptObjectException
434 	 * @throws org.eclipse.jgit.errors.NoWorkTreeException
435 	 * @since 3.4
436 	 */
437 	protected void cleanUp() throws NoWorkTreeException,
438 			CorruptObjectException,
439 			IOException {
440 		if (inCore) {
441 			modifiedFiles.clear();
442 			return;
443 		}
444 
445 		DirCache dc = nonNullRepo().readDirCache();
446 		Iterator<String> mpathsIt=modifiedFiles.iterator();
447 		while(mpathsIt.hasNext()) {
448 			String mpath = mpathsIt.next();
449 			DirCacheEntry entry = dc.getEntry(mpath);
450 			if (entry != null) {
451 				DirCacheCheckout.checkoutEntry(db, entry, reader, false,
452 						checkoutMetadata.get(mpath));
453 			}
454 			mpathsIt.remove();
455 		}
456 	}
457 
458 	/**
459 	 * adds a new path with the specified stage to the index builder
460 	 *
461 	 * @param path
462 	 * @param p
463 	 * @param stage
464 	 * @param lastMod
465 	 * @param len
466 	 * @return the entry which was added to the index
467 	 */
468 	private DirCacheEntry add(byte[] path, CanonicalTreeParser p, int stage,
469 			Instant lastMod, long len) {
470 		if (p != null && !p.getEntryFileMode().equals(FileMode.TREE)) {
471 			DirCacheEntry e = new DirCacheEntry(path, stage);
472 			e.setFileMode(p.getEntryFileMode());
473 			e.setObjectId(p.getEntryObjectId());
474 			e.setLastModified(lastMod);
475 			e.setLength(len);
476 			builder.add(e);
477 			return e;
478 		}
479 		return null;
480 	}
481 
482 	/**
483 	 * adds a entry to the index builder which is a copy of the specified
484 	 * DirCacheEntry
485 	 *
486 	 * @param e
487 	 *            the entry which should be copied
488 	 *
489 	 * @return the entry which was added to the index
490 	 */
491 	private DirCacheEntry/../../../org/eclipse/jgit/dircache/DirCacheEntry.html#DirCacheEntry">DirCacheEntry keep(DirCacheEntry e) {
492 		DirCacheEntry newEntry = new DirCacheEntry(e.getRawPath(),
493 				e.getStage());
494 		newEntry.setFileMode(e.getFileMode());
495 		newEntry.setObjectId(e.getObjectId());
496 		newEntry.setLastModified(e.getLastModifiedInstant());
497 		newEntry.setLength(e.getLength());
498 		builder.add(newEntry);
499 		return newEntry;
500 	}
501 
502 	/**
503 	 * Remembers the {@link CheckoutMetadata} for the given path; it may be
504 	 * needed in {@link #checkout()} or in {@link #cleanUp()}.
505 	 *
506 	 * @param path
507 	 *            of the current node
508 	 * @param attributes
509 	 *            for the current node
510 	 * @throws IOException
511 	 *             if the smudge filter cannot be determined
512 	 * @since 5.1
513 	 */
514 	protected void addCheckoutMetadata(String path, Attributes attributes)
515 			throws IOException {
516 		if (checkoutMetadata != null) {
517 			EolStreamType eol = EolStreamTypeUtil.detectStreamType(
518 					OperationType.CHECKOUT_OP, workingTreeOptions, attributes);
519 			CheckoutMetadata data = new CheckoutMetadata(eol,
520 					tw.getFilterCommand(Constants.ATTR_FILTER_TYPE_SMUDGE));
521 			checkoutMetadata.put(path, data);
522 		}
523 	}
524 
525 	/**
526 	 * Adds a {@link DirCacheEntry} for direct checkout and remembers its
527 	 * {@link CheckoutMetadata}.
528 	 *
529 	 * @param path
530 	 *            of the entry
531 	 * @param entry
532 	 *            to add
533 	 * @param attributes
534 	 *            for the current entry
535 	 * @throws IOException
536 	 *             if the {@link CheckoutMetadata} cannot be determined
537 	 * @since 5.1
538 	 */
539 	protected void addToCheckout(String path, DirCacheEntry entry,
540 			Attributes attributes) throws IOException {
541 		toBeCheckedOut.put(path, entry);
542 		addCheckoutMetadata(path, attributes);
543 	}
544 
545 	/**
546 	 * Remember a path for deletion, and remember its {@link CheckoutMetadata}
547 	 * in case it has to be restored in {@link #cleanUp()}.
548 	 *
549 	 * @param path
550 	 *            of the entry
551 	 * @param isFile
552 	 *            whether it is a file
553 	 * @param attributes
554 	 *            for the entry
555 	 * @throws IOException
556 	 *             if the {@link CheckoutMetadata} cannot be determined
557 	 * @since 5.1
558 	 */
559 	protected void addDeletion(String path, boolean isFile,
560 			Attributes attributes) throws IOException {
561 		toBeDeleted.add(path);
562 		if (isFile) {
563 			addCheckoutMetadata(path, attributes);
564 		}
565 	}
566 
567 	/**
568 	 * Processes one path and tries to merge taking git attributes in account.
569 	 * This method will do all trivial (not content) merges and will also detect
570 	 * if a merge will fail. The merge will fail when one of the following is
571 	 * true
572 	 * <ul>
573 	 * <li>the index entry does not match the entry in ours. When merging one
574 	 * branch into the current HEAD, ours will point to HEAD and theirs will
575 	 * point to the other branch. It is assumed that the index matches the HEAD
576 	 * because it will only not match HEAD if it was populated before the merge
577 	 * operation. But the merge commit should not accidentally contain
578 	 * modifications done before the merge. Check the <a href=
579 	 * "http://www.kernel.org/pub/software/scm/git/docs/git-read-tree.html#_3_way_merge"
580 	 * >git read-tree</a> documentation for further explanations.</li>
581 	 * <li>A conflict was detected and the working-tree file is dirty. When a
582 	 * conflict is detected the content-merge algorithm will try to write a
583 	 * merged version into the working-tree. If the file is dirty we would
584 	 * override unsaved data.</li>
585 	 * </ul>
586 	 *
587 	 * @param base
588 	 *            the common base for ours and theirs
589 	 * @param ours
590 	 *            the ours side of the merge. When merging a branch into the
591 	 *            HEAD ours will point to HEAD
592 	 * @param theirs
593 	 *            the theirs side of the merge. When merging a branch into the
594 	 *            current HEAD theirs will point to the branch which is merged
595 	 *            into HEAD.
596 	 * @param index
597 	 *            the index entry
598 	 * @param work
599 	 *            the file in the working tree
600 	 * @param ignoreConflicts
601 	 *            see
602 	 *            {@link org.eclipse.jgit.merge.ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)}
603 	 * @param attributes
604 	 *            the attributes defined for this entry
605 	 * @return <code>false</code> if the merge will fail because the index entry
606 	 *         didn't match ours or the working-dir file was dirty and a
607 	 *         conflict occurred
608 	 * @throws org.eclipse.jgit.errors.MissingObjectException
609 	 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
610 	 * @throws org.eclipse.jgit.errors.CorruptObjectException
611 	 * @throws java.io.IOException
612 	 * @since 4.9
613 	 */
614 	protected boolean processEntry(CanonicalTreeParser base,
615 			CanonicalTreeParser ours, CanonicalTreeParser theirs,
616 			DirCacheBuildIterator index, WorkingTreeIterator work,
617 			boolean ignoreConflicts, Attributes attributes)
618 			throws MissingObjectException, IncorrectObjectTypeException,
619 			CorruptObjectException, IOException {
620 		enterSubtree = true;
621 		final int modeO = tw.getRawMode(T_OURS);
622 		final int modeT = tw.getRawMode(T_THEIRS);
623 		final int modeB = tw.getRawMode(T_BASE);
624 
625 		if (modeO == 0 && modeT == 0 && modeB == 0)
626 			// File is either untracked or new, staged but uncommitted
627 			return true;
628 
629 		if (isIndexDirty())
630 			return false;
631 
632 		DirCacheEntry ourDce = null;
633 
634 		if (index == null || index.getDirCacheEntry() == null) {
635 			// create a fake DCE, but only if ours is valid. ours is kept only
636 			// in case it is valid, so a null ourDce is ok in all other cases.
637 			if (nonTree(modeO)) {
638 				ourDce = new DirCacheEntry(tw.getRawPath());
639 				ourDce.setObjectId(tw.getObjectId(T_OURS));
640 				ourDce.setFileMode(tw.getFileMode(T_OURS));
641 			}
642 		} else {
643 			ourDce = index.getDirCacheEntry();
644 		}
645 
646 		if (nonTree(modeO) && nonTree(modeT) && tw.idEqual(T_OURS, T_THEIRS)) {
647 			// OURS and THEIRS have equal content. Check the file mode
648 			if (modeO == modeT) {
649 				// content and mode of OURS and THEIRS are equal: it doesn't
650 				// matter which one we choose. OURS is chosen. Since the index
651 				// is clean (the index matches already OURS) we can keep the existing one
652 				keep(ourDce);
653 				// no checkout needed!
654 				return true;
655 			}
656 			// same content but different mode on OURS and THEIRS.
657 			// Try to merge the mode and report an error if this is
658 			// not possible.
659 			int newMode = mergeFileModes(modeB, modeO, modeT);
660 			if (newMode != FileMode.MISSING.getBits()) {
661 				if (newMode == modeO) {
662 					// ours version is preferred
663 					keep(ourDce);
664 				} else {
665 					// the preferred version THEIRS has a different mode
666 					// than ours. Check it out!
667 					if (isWorktreeDirty(work, ourDce)) {
668 						return false;
669 					}
670 					// we know about length and lastMod only after we have
671 					// written the new content.
672 					// This will happen later. Set these values to 0 for know.
673 					DirCacheEntry e = add(tw.getRawPath(), theirs,
674 							DirCacheEntry.STAGE_0, EPOCH, 0);
675 					addToCheckout(tw.getPathString(), e, attributes);
676 				}
677 				return true;
678 			}
679 			// FileModes are not mergeable. We found a conflict on modes.
680 			// For conflicting entries we don't know lastModified and
681 			// length.
682 			add(tw.getRawPath(), base, DirCacheEntry.STAGE_1, EPOCH, 0);
683 			add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
684 			add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 0);
685 			unmergedPaths.add(tw.getPathString());
686 			mergeResults.put(tw.getPathString(),
687 					new MergeResult<>(Collections.<RawText> emptyList()));
688 			return true;
689 		}
690 
691 		if (modeB == modeT && tw.idEqual(T_BASE, T_THEIRS)) {
692 			// THEIRS was not changed compared to BASE. All changes must be in
693 			// OURS. OURS is chosen. We can keep the existing entry.
694 			if (ourDce != null)
695 				keep(ourDce);
696 			// no checkout needed!
697 			return true;
698 		}
699 
700 		if (modeB == modeO && tw.idEqual(T_BASE, T_OURS)) {
701 			// OURS was not changed compared to BASE. All changes must be in
702 			// THEIRS. THEIRS is chosen.
703 
704 			// Check worktree before checking out THEIRS
705 			if (isWorktreeDirty(work, ourDce))
706 				return false;
707 			if (nonTree(modeT)) {
708 				// we know about length and lastMod only after we have written
709 				// the new content.
710 				// This will happen later. Set these values to 0 for know.
711 				DirCacheEntry e = add(tw.getRawPath(), theirs,
712 						DirCacheEntry.STAGE_0, EPOCH, 0);
713 				if (e != null) {
714 					addToCheckout(tw.getPathString(), e, attributes);
715 				}
716 				return true;
717 			}
718 			// we want THEIRS ... but THEIRS contains a folder or the
719 			// deletion of the path. Delete what's in the working tree,
720 			// which we know to be clean.
721 			if (tw.getTreeCount() > T_FILE && tw.getRawMode(T_FILE) == 0) {
722 				// Not present in working tree, so nothing to delete
723 				return true;
724 			}
725 			if (modeT != 0 && modeT == modeB) {
726 				// Base, ours, and theirs all contain a folder: don't delete
727 				return true;
728 			}
729 			addDeletion(tw.getPathString(), nonTree(modeO), attributes);
730 			return true;
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, EPOCH, 0);
741 				add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 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, EPOCH, 0);
749 				add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 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, EPOCH, 0);
777 				add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
778 				add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 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, EPOCH, 0);
826 				add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
827 				DirCacheEntry e = add(tw.getRawPath(), theirs,
828 						DirCacheEntry.STAGE_3, EPOCH, 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, EPOCH, 0);
961 				add(tw.getRawPath(), ours, DirCacheEntry.STAGE_2, EPOCH, 0);
962 				add(tw.getRawPath(), theirs, DirCacheEntry.STAGE_3, EPOCH, 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().lastModifiedInstant(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 		boolean success = false;
1028 		try {
1029 			new MergeFormatter().formatMerge(buf, result,
1030 					Arrays.asList(commitNames), UTF_8);
1031 			buf.close();
1032 			success = true;
1033 		} finally {
1034 			if (!success) {
1035 				buf.destroy();
1036 			}
1037 		}
1038 		return buf;
1039 	}
1040 
1041 	private ObjectId insertMergeResult(TemporaryBuffer buf,
1042 			Attributes attributes) throws IOException {
1043 		InputStream in = buf.openInputStream();
1044 		try (LfsInputStream is = LfsFactory.getInstance().applyCleanFilter(
1045 				getRepository(), in,
1046 				buf.length(), attributes.get(Constants.ATTR_MERGE))) {
1047 			return getObjectInserter().insert(OBJ_BLOB, is.getLength(), is);
1048 		}
1049 	}
1050 
1051 	/**
1052 	 * Try to merge filemodes. If only ours or theirs have changed the mode
1053 	 * (compared to base) we choose that one. If ours and theirs have equal
1054 	 * modes return that one. If also that is not the case the modes are not
1055 	 * mergeable. Return {@link FileMode#MISSING} int that case.
1056 	 *
1057 	 * @param modeB
1058 	 *            filemode found in BASE
1059 	 * @param modeO
1060 	 *            filemode found in OURS
1061 	 * @param modeT
1062 	 *            filemode found in THEIRS
1063 	 *
1064 	 * @return the merged filemode or {@link FileMode#MISSING} in case of a
1065 	 *         conflict
1066 	 */
1067 	private int mergeFileModes(int modeB, int modeO, int modeT) {
1068 		if (modeO == modeT)
1069 			return modeO;
1070 		if (modeB == modeO)
1071 			// Base equal to Ours -> chooses Theirs if that is not missing
1072 			return (modeT == FileMode.MISSING.getBits()) ? modeO : modeT;
1073 		if (modeB == modeT)
1074 			// Base equal to Theirs -> chooses Ours if that is not missing
1075 			return (modeO == FileMode.MISSING.getBits()) ? modeT : modeO;
1076 		return FileMode.MISSING.getBits();
1077 	}
1078 
1079 	private RawText getRawText(ObjectId id,
1080 			Attributes attributes)
1081 			throws IOException, BinaryBlobException {
1082 		if (id.equals(ObjectId.zeroId()))
1083 			return new RawText(new byte[] {});
1084 
1085 		ObjectLoader loader = LfsFactory.getInstance().applySmudgeFilter(
1086 				getRepository(), reader.open(id, OBJ_BLOB),
1087 				attributes.get(Constants.ATTR_MERGE));
1088 		int threshold = PackConfig.DEFAULT_BIG_FILE_THRESHOLD;
1089 		return RawText.load(loader, threshold);
1090 	}
1091 
1092 	private static boolean nonTree(int mode) {
1093 		return mode != 0 && !FileMode.TREE.equals(mode);
1094 	}
1095 
1096 	private static boolean isGitLink(int mode) {
1097 		return FileMode.GITLINK.equals(mode);
1098 	}
1099 
1100 	/** {@inheritDoc} */
1101 	@Override
1102 	public ObjectId getResultTreeId() {
1103 		return (resultTree == null) ? null : resultTree.toObjectId();
1104 	}
1105 
1106 	/**
1107 	 * Set the names of the commits as they would appear in conflict markers
1108 	 *
1109 	 * @param commitNames
1110 	 *            the names of the commits as they would appear in conflict
1111 	 *            markers
1112 	 */
1113 	public void setCommitNames(String[] commitNames) {
1114 		this.commitNames = commitNames;
1115 	}
1116 
1117 	/**
1118 	 * Get the names of the commits as they would appear in conflict markers.
1119 	 *
1120 	 * @return the names of the commits as they would appear in conflict
1121 	 *         markers.
1122 	 */
1123 	public String[] getCommitNames() {
1124 		return commitNames;
1125 	}
1126 
1127 	/**
1128 	 * Get the paths with conflicts. This is a subset of the files listed by
1129 	 * {@link #getModifiedFiles()}
1130 	 *
1131 	 * @return the paths with conflicts. This is a subset of the files listed by
1132 	 *         {@link #getModifiedFiles()}
1133 	 */
1134 	public List<String> getUnmergedPaths() {
1135 		return unmergedPaths;
1136 	}
1137 
1138 	/**
1139 	 * Get the paths of files which have been modified by this merge.
1140 	 *
1141 	 * @return the paths of files which have been modified by this merge. A file
1142 	 *         will be modified if a content-merge works on this path or if the
1143 	 *         merge algorithm decides to take the theirs-version. This is a
1144 	 *         superset of the files listed by {@link #getUnmergedPaths()}.
1145 	 */
1146 	public List<String> getModifiedFiles() {
1147 		return modifiedFiles;
1148 	}
1149 
1150 	/**
1151 	 * Get a map which maps the paths of files which have to be checked out
1152 	 * because the merge created new fully-merged content for this file into the
1153 	 * index.
1154 	 *
1155 	 * @return a map which maps the paths of files which have to be checked out
1156 	 *         because the merge created new fully-merged content for this file
1157 	 *         into the index. This means: the merge wrote a new stage 0 entry
1158 	 *         for this path.
1159 	 */
1160 	public Map<String, DirCacheEntry> getToBeCheckedOut() {
1161 		return toBeCheckedOut;
1162 	}
1163 
1164 	/**
1165 	 * Get the mergeResults
1166 	 *
1167 	 * @return the mergeResults
1168 	 */
1169 	public Map<String, MergeResult<? extends Sequence>> getMergeResults() {
1170 		return mergeResults;
1171 	}
1172 
1173 	/**
1174 	 * Get list of paths causing this merge to fail (not stopped because of a
1175 	 * conflict).
1176 	 *
1177 	 * @return lists paths causing this merge to fail (not stopped because of a
1178 	 *         conflict). <code>null</code> is returned if this merge didn't
1179 	 *         fail.
1180 	 */
1181 	public Map<String, MergeFailureReason> getFailingPaths() {
1182 		return failingPaths.isEmpty() ? null : failingPaths;
1183 	}
1184 
1185 	/**
1186 	 * Returns whether this merge failed (i.e. not stopped because of a
1187 	 * conflict)
1188 	 *
1189 	 * @return <code>true</code> if a failure occurred, <code>false</code>
1190 	 *         otherwise
1191 	 */
1192 	public boolean failed() {
1193 		return !failingPaths.isEmpty();
1194 	}
1195 
1196 	/**
1197 	 * Sets the DirCache which shall be used by this merger. If the DirCache is
1198 	 * not set explicitly and if this merger doesn't work in-core, this merger
1199 	 * will implicitly get and lock a default DirCache. If the DirCache is
1200 	 * explicitly set the caller is responsible to lock it in advance. Finally
1201 	 * the merger will call {@link org.eclipse.jgit.dircache.DirCache#commit()}
1202 	 * which requires that the DirCache is locked. If the {@link #mergeImpl()}
1203 	 * returns without throwing an exception the lock will be released. In case
1204 	 * of exceptions the caller is responsible to release the lock.
1205 	 *
1206 	 * @param dc
1207 	 *            the DirCache to set
1208 	 */
1209 	public void setDirCache(DirCache dc) {
1210 		this.dircache = dc;
1211 		implicitDirCache = false;
1212 	}
1213 
1214 	/**
1215 	 * Sets the WorkingTreeIterator to be used by this merger. If no
1216 	 * WorkingTreeIterator is set this merger will ignore the working tree and
1217 	 * fail if a content merge is necessary.
1218 	 * <p>
1219 	 * TODO: enhance WorkingTreeIterator to support write operations. Then this
1220 	 * merger will be able to merge with a different working tree abstraction.
1221 	 *
1222 	 * @param workingTreeIterator
1223 	 *            the workingTreeIt to set
1224 	 */
1225 	public void setWorkingTreeIterator(WorkingTreeIterator workingTreeIterator) {
1226 		this.workingTreeIterator = workingTreeIterator;
1227 	}
1228 
1229 
1230 	/**
1231 	 * The resolve conflict way of three way merging
1232 	 *
1233 	 * @param baseTree
1234 	 *            a {@link org.eclipse.jgit.treewalk.AbstractTreeIterator}
1235 	 *            object.
1236 	 * @param headTree
1237 	 *            a {@link org.eclipse.jgit.revwalk.RevTree} object.
1238 	 * @param mergeTree
1239 	 *            a {@link org.eclipse.jgit.revwalk.RevTree} object.
1240 	 * @param ignoreConflicts
1241 	 *            Controls what to do in case a content-merge is done and a
1242 	 *            conflict is detected. The default setting for this should be
1243 	 *            <code>false</code>. In this case the working tree file is
1244 	 *            filled with new content (containing conflict markers) and the
1245 	 *            index is filled with multiple stages containing BASE, OURS and
1246 	 *            THEIRS content. Having such non-0 stages is the sign to git
1247 	 *            tools that there are still conflicts for that path.
1248 	 *            <p>
1249 	 *            If <code>true</code> is specified the behavior is different.
1250 	 *            In case a conflict is detected the working tree file is again
1251 	 *            filled with new content (containing conflict markers). But
1252 	 *            also stage 0 of the index is filled with that content. No
1253 	 *            other stages are filled. Means: there is no conflict on that
1254 	 *            path but the new content (including conflict markers) is
1255 	 *            stored as successful merge result. This is needed in the
1256 	 *            context of {@link org.eclipse.jgit.merge.RecursiveMerger}
1257 	 *            where when determining merge bases we don't want to deal with
1258 	 *            content-merge conflicts.
1259 	 * @return whether the trees merged cleanly
1260 	 * @throws java.io.IOException
1261 	 * @since 3.5
1262 	 */
1263 	protected boolean mergeTrees(AbstractTreeIterator baseTree,
1264 			RevTree headTree, RevTree mergeTree, boolean ignoreConflicts)
1265 			throws IOException {
1266 
1267 		builder = dircache.builder();
1268 		DirCacheBuildIterator buildIt = new DirCacheBuildIterator(builder);
1269 
1270 		tw = new NameConflictTreeWalk(db, reader);
1271 		tw.addTree(baseTree);
1272 		tw.addTree(headTree);
1273 		tw.addTree(mergeTree);
1274 		int dciPos = tw.addTree(buildIt);
1275 		if (workingTreeIterator != null) {
1276 			tw.addTree(workingTreeIterator);
1277 			workingTreeIterator.setDirCacheIterator(tw, dciPos);
1278 		} else {
1279 			tw.setFilter(TreeFilter.ANY_DIFF);
1280 		}
1281 
1282 		if (!mergeTreeWalk(tw, ignoreConflicts)) {
1283 			return false;
1284 		}
1285 
1286 		if (!inCore) {
1287 			// No problem found. The only thing left to be done is to
1288 			// checkout all files from "theirs" which have been selected to
1289 			// go into the new index.
1290 			checkout();
1291 
1292 			// All content-merges are successfully done. If we can now write the
1293 			// new index we are on quite safe ground. Even if the checkout of
1294 			// files coming from "theirs" fails the user can work around such
1295 			// failures by checking out the index again.
1296 			if (!builder.commit()) {
1297 				cleanUp();
1298 				throw new IndexWriteException();
1299 			}
1300 			builder = null;
1301 
1302 		} else {
1303 			builder.finish();
1304 			builder = null;
1305 		}
1306 
1307 		if (getUnmergedPaths().isEmpty() && !failed()) {
1308 			resultTree = dircache.writeTree(getObjectInserter());
1309 			return true;
1310 		}
1311 		resultTree = null;
1312 		return false;
1313 	}
1314 
1315 	/**
1316 	 * Process the given TreeWalk's entries.
1317 	 *
1318 	 * @param treeWalk
1319 	 *            The walk to iterate over.
1320 	 * @param ignoreConflicts
1321 	 *            see
1322 	 *            {@link org.eclipse.jgit.merge.ResolveMerger#mergeTrees(AbstractTreeIterator, RevTree, RevTree, boolean)}
1323 	 * @return Whether the trees merged cleanly.
1324 	 * @throws java.io.IOException
1325 	 * @since 3.5
1326 	 */
1327 	protected boolean mergeTreeWalk(TreeWalk treeWalk, boolean ignoreConflicts)
1328 			throws IOException {
1329 		boolean hasWorkingTreeIterator = tw.getTreeCount() > T_FILE;
1330 		boolean hasAttributeNodeProvider = treeWalk
1331 				.getAttributesNodeProvider() != null;
1332 		while (treeWalk.next()) {
1333 			if (!processEntry(
1334 					treeWalk.getTree(T_BASE, CanonicalTreeParser.class),
1335 					treeWalk.getTree(T_OURS, CanonicalTreeParser.class),
1336 					treeWalk.getTree(T_THEIRS, CanonicalTreeParser.class),
1337 					treeWalk.getTree(T_INDEX, DirCacheBuildIterator.class),
1338 					hasWorkingTreeIterator ? treeWalk.getTree(T_FILE,
1339 							WorkingTreeIterator.class) : null,
1340 					ignoreConflicts, hasAttributeNodeProvider
1341 							? treeWalk.getAttributes()
1342 							: NO_ATTRIBUTES)) {
1343 				cleanUp();
1344 				return false;
1345 			}
1346 			if (treeWalk.isSubtree() && enterSubtree)
1347 				treeWalk.enterSubtree();
1348 		}
1349 		return true;
1350 	}
1351 }