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