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