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