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