View Javadoc
1   /*
2    * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
3    * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
4    * Copyright (C) 2008, Roger C. Soares <rogersoares@intelinet.com.br>
5    * Copyright (C) 2006, Shawn O. Pearce <spearce@spearce.org>
6    * Copyright (C) 2010, Chrisian Halstrick <christian.halstrick@sap.com> and
7    * other copyright owners as documented in the project's IP log.
8    *
9    * This program and the accompanying materials are made available under the
10   * terms of the Eclipse Distribution License v1.0 which accompanies this
11   * distribution, is reproduced below, and is available at
12   * http://www.eclipse.org/org/documents/edl-v10.php
13   *
14   * All rights reserved.
15   *
16   * Redistribution and use in source and binary forms, with or without
17   * modification, are permitted provided that the following conditions are met:
18   *
19   * - Redistributions of source code must retain the above copyright notice, this
20   * list of conditions and the following disclaimer.
21   *
22   * - Redistributions in binary form must reproduce the above copyright notice,
23   * this list of conditions and the following disclaimer in the documentation
24   * and/or other materials provided with the distribution.
25   *
26   * - Neither the name of the Eclipse Foundation, Inc. nor the names of its
27   * contributors may be used to endorse or promote products derived from this
28   * software without specific prior written permission.
29   *
30   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
31   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
34   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
35   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
36   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
37   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
38   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40   * POSSIBILITY OF SUCH DAMAGE.
41   */
42  
43  package org.eclipse.jgit.dircache;
44  
45  import static org.eclipse.jgit.treewalk.TreeWalk.OperationType.CHECKOUT_OP;
46  
47  import java.io.File;
48  import java.io.FileOutputStream;
49  import java.io.IOException;
50  import java.io.OutputStream;
51  import java.nio.file.StandardCopyOption;
52  import java.text.MessageFormat;
53  import java.util.ArrayList;
54  import java.util.HashMap;
55  import java.util.Iterator;
56  import java.util.List;
57  import java.util.Map;
58  
59  import org.eclipse.jgit.api.errors.CanceledException;
60  import org.eclipse.jgit.api.errors.FilterFailedException;
61  import org.eclipse.jgit.attributes.FilterCommand;
62  import org.eclipse.jgit.attributes.FilterCommandRegistry;
63  import org.eclipse.jgit.errors.CheckoutConflictException;
64  import org.eclipse.jgit.errors.CorruptObjectException;
65  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
66  import org.eclipse.jgit.errors.IndexWriteException;
67  import org.eclipse.jgit.errors.MissingObjectException;
68  import org.eclipse.jgit.events.WorkingTreeModifiedEvent;
69  import org.eclipse.jgit.internal.JGitText;
70  import org.eclipse.jgit.lib.ConfigConstants;
71  import org.eclipse.jgit.lib.Constants;
72  import org.eclipse.jgit.lib.CoreConfig.AutoCRLF;
73  import org.eclipse.jgit.lib.CoreConfig.EolStreamType;
74  import org.eclipse.jgit.lib.CoreConfig.SymLinks;
75  import org.eclipse.jgit.lib.FileMode;
76  import org.eclipse.jgit.lib.NullProgressMonitor;
77  import org.eclipse.jgit.lib.ObjectChecker;
78  import org.eclipse.jgit.lib.ObjectId;
79  import org.eclipse.jgit.lib.ObjectLoader;
80  import org.eclipse.jgit.lib.ObjectReader;
81  import org.eclipse.jgit.lib.ProgressMonitor;
82  import org.eclipse.jgit.lib.Repository;
83  import org.eclipse.jgit.treewalk.AbstractTreeIterator;
84  import org.eclipse.jgit.treewalk.CanonicalTreeParser;
85  import org.eclipse.jgit.treewalk.EmptyTreeIterator;
86  import org.eclipse.jgit.treewalk.FileTreeIterator;
87  import org.eclipse.jgit.treewalk.NameConflictTreeWalk;
88  import org.eclipse.jgit.treewalk.TreeWalk;
89  import org.eclipse.jgit.treewalk.WorkingTreeIterator;
90  import org.eclipse.jgit.treewalk.WorkingTreeOptions;
91  import org.eclipse.jgit.treewalk.filter.PathFilter;
92  import org.eclipse.jgit.util.FS;
93  import org.eclipse.jgit.util.FS.ExecutionResult;
94  import org.eclipse.jgit.util.FileUtils;
95  import org.eclipse.jgit.util.IntList;
96  import org.eclipse.jgit.util.RawParseUtils;
97  import org.eclipse.jgit.util.SystemReader;
98  import org.eclipse.jgit.util.io.EolStreamTypeUtil;
99  import org.slf4j.Logger;
100 import org.slf4j.LoggerFactory;
101 
102 /**
103  * This class handles checking out one or two trees merging with the index.
104  */
105 public class DirCacheCheckout {
106 	private static Logger LOG = LoggerFactory.getLogger(DirCacheCheckout.class);
107 
108 	private static final int MAX_EXCEPTION_TEXT_SIZE = 10 * 1024;
109 
110 	/**
111 	 * Metadata used in checkout process
112 	 *
113 	 * @since 4.3
114 	 */
115 	public static class CheckoutMetadata {
116 		/** git attributes */
117 		public final EolStreamType eolStreamType;
118 
119 		/** filter command to apply */
120 		public final String smudgeFilterCommand;
121 
122 		/**
123 		 * @param eolStreamType
124 		 * @param smudgeFilterCommand
125 		 */
126 		public CheckoutMetadata(EolStreamType eolStreamType,
127 				String smudgeFilterCommand) {
128 			this.eolStreamType = eolStreamType;
129 			this.smudgeFilterCommand = smudgeFilterCommand;
130 		}
131 
132 		static CheckoutMetadata EMPTY = new CheckoutMetadata(
133 				EolStreamType.DIRECT, null);
134 	}
135 
136 	private Repository repo;
137 
138 	private HashMap<String, CheckoutMetadata> updated = new HashMap<>();
139 
140 	private ArrayList<String> conflicts = new ArrayList<>();
141 
142 	private ArrayList<String> removed = new ArrayList<>();
143 
144 	private ObjectId mergeCommitTree;
145 
146 	private DirCache dc;
147 
148 	private DirCacheBuilder builder;
149 
150 	private NameConflictTreeWalk walk;
151 
152 	private ObjectId headCommitTree;
153 
154 	private WorkingTreeIterator workingTree;
155 
156 	private boolean failOnConflict = true;
157 
158 	private ArrayList<String> toBeDeleted = new ArrayList<>();
159 
160 	private boolean emptyDirCache;
161 
162 	private boolean performingCheckout;
163 
164 	private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
165 
166 	/**
167 	 * Get list of updated paths and smudgeFilterCommands
168 	 *
169 	 * @return a list of updated paths and smudgeFilterCommands
170 	 */
171 	public Map<String, CheckoutMetadata> getUpdated() {
172 		return updated;
173 	}
174 
175 	/**
176 	 * Get a list of conflicts created by this checkout
177 	 *
178 	 * @return a list of conflicts created by this checkout
179 	 */
180 	public List<String> getConflicts() {
181 		return conflicts;
182 	}
183 
184 	/**
185 	 * Get list of paths of files which couldn't be deleted during last call to
186 	 * {@link #checkout()}
187 	 *
188 	 * @return a list of paths (relative to the start of the working tree) of
189 	 *         files which couldn't be deleted during last call to
190 	 *         {@link #checkout()} . {@link #checkout()} detected that these
191 	 *         files should be deleted but the deletion in the filesystem failed
192 	 *         (e.g. because a file was locked). To have a consistent state of
193 	 *         the working tree these files have to be deleted by the callers of
194 	 *         {@link org.eclipse.jgit.dircache.DirCacheCheckout}.
195 	 */
196 	public List<String> getToBeDeleted() {
197 		return toBeDeleted;
198 	}
199 
200 	/**
201 	 * Get list of all files removed by this checkout
202 	 *
203 	 * @return a list of all files removed by this checkout
204 	 */
205 	public List<String> getRemoved() {
206 		return removed;
207 	}
208 
209 	/**
210 	 * Constructs a DirCacheCeckout for merging and checking out two trees (HEAD
211 	 * and mergeCommitTree) and the index.
212 	 *
213 	 * @param repo
214 	 *            the repository in which we do the checkout
215 	 * @param headCommitTree
216 	 *            the id of the tree of the head commit
217 	 * @param dc
218 	 *            the (already locked) Dircache for this repo
219 	 * @param mergeCommitTree
220 	 *            the id of the tree we want to fast-forward to
221 	 * @param workingTree
222 	 *            an iterator over the repositories Working Tree
223 	 * @throws java.io.IOException
224 	 */
225 	public DirCacheCheckout(Repository repo, ObjectId headCommitTree, DirCache dc,
226 			ObjectId mergeCommitTree, WorkingTreeIterator workingTree)
227 			throws IOException {
228 		this.repo = repo;
229 		this.dc = dc;
230 		this.headCommitTree = headCommitTree;
231 		this.mergeCommitTree = mergeCommitTree;
232 		this.workingTree = workingTree;
233 		this.emptyDirCache = (dc == null) || (dc.getEntryCount() == 0);
234 	}
235 
236 	/**
237 	 * Constructs a DirCacheCeckout for merging and checking out two trees (HEAD
238 	 * and mergeCommitTree) and the index. As iterator over the working tree
239 	 * this constructor creates a standard
240 	 * {@link org.eclipse.jgit.treewalk.FileTreeIterator}
241 	 *
242 	 * @param repo
243 	 *            the repository in which we do the checkout
244 	 * @param headCommitTree
245 	 *            the id of the tree of the head commit
246 	 * @param dc
247 	 *            the (already locked) Dircache for this repo
248 	 * @param mergeCommitTree
249 	 *            the id of the tree we want to fast-forward to
250 	 * @throws java.io.IOException
251 	 */
252 	public DirCacheCheckout(Repository repo, ObjectId headCommitTree,
253 			DirCache dc, ObjectId mergeCommitTree) throws IOException {
254 		this(repo, headCommitTree, dc, mergeCommitTree, new FileTreeIterator(repo));
255 	}
256 
257 	/**
258 	 * Constructs a DirCacheCeckout for checking out one tree, merging with the
259 	 * index.
260 	 *
261 	 * @param repo
262 	 *            the repository in which we do the checkout
263 	 * @param dc
264 	 *            the (already locked) Dircache for this repo
265 	 * @param mergeCommitTree
266 	 *            the id of the tree we want to fast-forward to
267 	 * @param workingTree
268 	 *            an iterator over the repositories Working Tree
269 	 * @throws java.io.IOException
270 	 */
271 	public DirCacheCheckout(Repository repo, DirCache dc,
272 			ObjectId mergeCommitTree, WorkingTreeIterator workingTree)
273 			throws IOException {
274 		this(repo, null, dc, mergeCommitTree, workingTree);
275 	}
276 
277 	/**
278 	 * Constructs a DirCacheCeckout for checking out one tree, merging with the
279 	 * index. As iterator over the working tree this constructor creates a
280 	 * standard {@link org.eclipse.jgit.treewalk.FileTreeIterator}
281 	 *
282 	 * @param repo
283 	 *            the repository in which we do the checkout
284 	 * @param dc
285 	 *            the (already locked) Dircache for this repo
286 	 * @param mergeCommitTree
287 	 *            the id of the tree of the
288 	 * @throws java.io.IOException
289 	 */
290 	public DirCacheCheckout(Repository repo, DirCache dc,
291 			ObjectId mergeCommitTree) throws IOException {
292 		this(repo, null, dc, mergeCommitTree, new FileTreeIterator(repo));
293 	}
294 
295 	/**
296 	 * Set a progress monitor which can be passed to built-in filter commands,
297 	 * providing progress information for long running tasks.
298 	 *
299 	 * @param monitor
300 	 *            the {@link ProgressMonitor}
301 	 * @since 4.11
302 	 */
303 	public void setProgressMonitor(ProgressMonitor monitor) {
304 		this.monitor = monitor != null ? monitor : NullProgressMonitor.INSTANCE;
305 	}
306 
307 	/**
308 	 * Scan head, index and merge tree. Used during normal checkout or merge
309 	 * operations.
310 	 *
311 	 * @throws org.eclipse.jgit.errors.CorruptObjectException
312 	 * @throws java.io.IOException
313 	 */
314 	public void preScanTwoTrees() throws CorruptObjectException, IOException {
315 		removed.clear();
316 		updated.clear();
317 		conflicts.clear();
318 		walk = new NameConflictTreeWalk(repo);
319 		builder = dc.builder();
320 
321 		addTree(walk, headCommitTree);
322 		addTree(walk, mergeCommitTree);
323 		int dciPos = walk.addTree(new DirCacheBuildIterator(builder));
324 		walk.addTree(workingTree);
325 		workingTree.setDirCacheIterator(walk, dciPos);
326 
327 		while (walk.next()) {
328 			processEntry(walk.getTree(0, CanonicalTreeParser.class),
329 					walk.getTree(1, CanonicalTreeParser.class),
330 					walk.getTree(2, DirCacheBuildIterator.class),
331 					walk.getTree(3, WorkingTreeIterator.class));
332 			if (walk.isSubtree())
333 				walk.enterSubtree();
334 		}
335 	}
336 
337 	private void addTree(TreeWalk tw, ObjectId id) throws MissingObjectException, IncorrectObjectTypeException, IOException {
338 		if (id == null)
339 			tw.addTree(new EmptyTreeIterator());
340 		else
341 			tw.addTree(id);
342 	}
343 
344 	/**
345 	 * Scan index and merge tree (no HEAD). Used e.g. for initial checkout when
346 	 * there is no head yet.
347 	 *
348 	 * @throws org.eclipse.jgit.errors.MissingObjectException
349 	 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
350 	 * @throws org.eclipse.jgit.errors.CorruptObjectException
351 	 * @throws java.io.IOException
352 	 */
353 	public void prescanOneTree()
354 			throws MissingObjectException, IncorrectObjectTypeException,
355 			CorruptObjectException, IOException {
356 		removed.clear();
357 		updated.clear();
358 		conflicts.clear();
359 
360 		builder = dc.builder();
361 
362 		walk = new NameConflictTreeWalk(repo);
363 		addTree(walk, mergeCommitTree);
364 		int dciPos = walk.addTree(new DirCacheBuildIterator(builder));
365 		walk.addTree(workingTree);
366 		workingTree.setDirCacheIterator(walk, dciPos);
367 
368 		while (walk.next()) {
369 			processEntry(walk.getTree(0, CanonicalTreeParser.class),
370 					walk.getTree(1, DirCacheBuildIterator.class),
371 					walk.getTree(2, WorkingTreeIterator.class));
372 			if (walk.isSubtree())
373 				walk.enterSubtree();
374 		}
375 		conflicts.removeAll(removed);
376 	}
377 
378 	/**
379 	 * Processing an entry in the context of {@link #prescanOneTree()} when only
380 	 * one tree is given
381 	 *
382 	 * @param m the tree to merge
383 	 * @param i the index
384 	 * @param f the working tree
385 	 * @throws IOException
386 	 */
387 	void processEntry(CanonicalTreeParser m, DirCacheBuildIterator i,
388 			WorkingTreeIterator f) throws IOException {
389 		if (m != null) {
390 			checkValidPath(m);
391 			// There is an entry in the merge commit. Means: we want to update
392 			// what's currently in the index and working-tree to that one
393 			if (i == null) {
394 				// The index entry is missing
395 				if (f != null && !FileMode.TREE.equals(f.getEntryFileMode())
396 						&& !f.isEntryIgnored()) {
397 					if (failOnConflict) {
398 						// don't overwrite an untracked and not ignored file
399 						conflicts.add(walk.getPathString());
400 					} else {
401 						// failOnConflict is false. Putting something to conflicts
402 						// would mean we delete it. Instead we want the mergeCommit
403 						// content to be checked out.
404 						update(m.getEntryPathString(), m.getEntryObjectId(),
405 								m.getEntryFileMode());
406 					}
407 				} else
408 					update(m.getEntryPathString(), m.getEntryObjectId(),
409 						m.getEntryFileMode());
410 			} else if (f == null || !m.idEqual(i)) {
411 				// The working tree file is missing or the merge content differs
412 				// from index content
413 				update(m.getEntryPathString(), m.getEntryObjectId(),
414 						m.getEntryFileMode());
415 			} else if (i.getDirCacheEntry() != null) {
416 				// The index contains a file (and not a folder)
417 				if (f.isModified(i.getDirCacheEntry(), true,
418 						this.walk.getObjectReader())
419 						|| i.getDirCacheEntry().getStage() != 0)
420 					// The working tree file is dirty or the index contains a
421 					// conflict
422 					update(m.getEntryPathString(), m.getEntryObjectId(),
423 							m.getEntryFileMode());
424 				else {
425 					// update the timestamp of the index with the one from the
426 					// file if not set, as we are sure to be in sync here.
427 					DirCacheEntry entry = i.getDirCacheEntry();
428 					if (entry.getLastModified() == 0)
429 						entry.setLastModified(f.getEntryLastModified());
430 					keep(entry);
431 				}
432 			} else
433 				// The index contains a folder
434 				keep(i.getDirCacheEntry());
435 		} else {
436 			// There is no entry in the merge commit. Means: we want to delete
437 			// what's currently in the index and working tree
438 			if (f != null) {
439 				// There is a file/folder for that path in the working tree
440 				if (walk.isDirectoryFileConflict()) {
441 					// We put it in conflicts. Even if failOnConflict is false
442 					// this would cause the path to be deleted. Thats exactly what
443 					// we want in this situation
444 					conflicts.add(walk.getPathString());
445 				} else {
446 					// No file/folder conflict exists. All entries are files or
447 					// all entries are folders
448 					if (i != null) {
449 						// ... and the working tree contained a file or folder
450 						// -> add it to the removed set and remove it from
451 						// conflicts set
452 						remove(i.getEntryPathString());
453 						conflicts.remove(i.getEntryPathString());
454 					} else {
455 						// untracked file, neither contained in tree to merge
456 						// nor in index
457 					}
458 				}
459 			} else {
460 				// There is no file/folder for that path in the working tree,
461 				// nor in the merge head.
462 				// The only entry we have is the index entry. Like the case
463 				// where there is a file with the same name, remove it,
464 			}
465 		}
466 	}
467 
468 	/**
469 	 * Execute this checkout. A
470 	 * {@link org.eclipse.jgit.events.WorkingTreeModifiedEvent} is fired if the
471 	 * working tree was modified; even if the checkout fails.
472 	 *
473 	 * @return <code>false</code> if this method could not delete all the files
474 	 *         which should be deleted (e.g. because one of the files was
475 	 *         locked). In this case {@link #getToBeDeleted()} lists the files
476 	 *         which should be tried to be deleted outside of this method.
477 	 *         Although <code>false</code> is returned the checkout was
478 	 *         successful and the working tree was updated for all other files.
479 	 *         <code>true</code> is returned when no such problem occurred
480 	 * @throws java.io.IOException
481 	 */
482 	public boolean checkout() throws IOException {
483 		try {
484 			return doCheckout();
485 		} catch (CanceledException ce) {
486 			// should actually be propagated, but this would change a LOT of
487 			// APIs
488 			throw new IOException(ce);
489 		} finally {
490 			try {
491 				dc.unlock();
492 			} finally {
493 				if (performingCheckout) {
494 					WorkingTreeModifiedEvent event = new WorkingTreeModifiedEvent(
495 							getUpdated().keySet(), getRemoved());
496 					if (!event.isEmpty()) {
497 						repo.fireEvent(event);
498 					}
499 				}
500 			}
501 		}
502 	}
503 
504 	private boolean doCheckout() throws CorruptObjectException, IOException,
505 			MissingObjectException, IncorrectObjectTypeException,
506 			CheckoutConflictException, IndexWriteException, CanceledException {
507 		toBeDeleted.clear();
508 		try (ObjectReader objectReader = repo.getObjectDatabase().newReader()) {
509 			if (headCommitTree != null)
510 				preScanTwoTrees();
511 			else
512 				prescanOneTree();
513 
514 			if (!conflicts.isEmpty()) {
515 				if (failOnConflict)
516 					throw new CheckoutConflictException(conflicts.toArray(new String[0]));
517 				else
518 					cleanUpConflicts();
519 			}
520 
521 			// update our index
522 			builder.finish();
523 
524 			// init progress reporting
525 			int numTotal = removed.size() + updated.size() + conflicts.size();
526 			monitor.beginTask(JGitText.get().checkingOutFiles, numTotal);
527 
528 			performingCheckout = true;
529 			File file = null;
530 			String last = null;
531 			// when deleting files process them in the opposite order as they have
532 			// been reported. This ensures the files are deleted before we delete
533 			// their parent folders
534 			IntList nonDeleted = new IntList();
535 			for (int i = removed.size() - 1; i >= 0; i--) {
536 				String r = removed.get(i);
537 				file = new File(repo.getWorkTree(), r);
538 				if (!file.delete() && repo.getFS().exists(file)) {
539 					// The list of stuff to delete comes from the index
540 					// which will only contain a directory if it is
541 					// a submodule, in which case we shall not attempt
542 					// to delete it. A submodule is not empty, so it
543 					// is safe to check this after a failed delete.
544 					if (!repo.getFS().isDirectory(file)) {
545 						nonDeleted.add(i);
546 						toBeDeleted.add(r);
547 					}
548 				} else {
549 					if (last != null && !isSamePrefix(r, last))
550 						removeEmptyParents(new File(repo.getWorkTree(), last));
551 					last = r;
552 				}
553 				monitor.update(1);
554 				if (monitor.isCancelled()) {
555 					throw new CanceledException(MessageFormat.format(
556 							JGitText.get().operationCanceled,
557 							JGitText.get().checkingOutFiles));
558 				}
559 			}
560 			if (file != null) {
561 				removeEmptyParents(file);
562 			}
563 			removed = filterOut(removed, nonDeleted);
564 			nonDeleted = null;
565 			Iterator<Map.Entry<String, CheckoutMetadata>> toUpdate = updated
566 					.entrySet().iterator();
567 			Map.Entry<String, CheckoutMetadata> e = null;
568 			try {
569 				while (toUpdate.hasNext()) {
570 					e = toUpdate.next();
571 					String path = e.getKey();
572 					CheckoutMetadata meta = e.getValue();
573 					DirCacheEntry entry = dc.getEntry(path);
574 					if (FileMode.GITLINK.equals(entry.getRawMode())) {
575 						checkoutGitlink(path, entry);
576 					} else {
577 						checkoutEntry(repo, entry, objectReader, false, meta);
578 					}
579 					e = null;
580 
581 					monitor.update(1);
582 					if (monitor.isCancelled()) {
583 						throw new CanceledException(MessageFormat.format(
584 								JGitText.get().operationCanceled,
585 								JGitText.get().checkingOutFiles));
586 					}
587 				}
588 			} catch (Exception ex) {
589 				// We didn't actually modify the current entry nor any that
590 				// might follow.
591 				if (e != null) {
592 					toUpdate.remove();
593 				}
594 				while (toUpdate.hasNext()) {
595 					e = toUpdate.next();
596 					toUpdate.remove();
597 				}
598 				throw ex;
599 			}
600 			for (String conflict : conflicts) {
601 				// the conflicts are likely to have multiple entries in the
602 				// dircache, we only want to check out the one for the "theirs"
603 				// tree
604 				int entryIdx = dc.findEntry(conflict);
605 				if (entryIdx >= 0) {
606 					while (entryIdx < dc.getEntryCount()) {
607 						DirCacheEntry entry = dc.getEntry(entryIdx);
608 						if (!entry.getPathString().equals(conflict)) {
609 							break;
610 						}
611 						if (entry.getStage() == DirCacheEntry.STAGE_3) {
612 							checkoutEntry(repo, entry, objectReader, false,
613 									null);
614 							break;
615 						}
616 						++entryIdx;
617 					}
618 				}
619 
620 				monitor.update(1);
621 				if (monitor.isCancelled()) {
622 					throw new CanceledException(MessageFormat.format(
623 							JGitText.get().operationCanceled,
624 							JGitText.get().checkingOutFiles));
625 				}
626 			}
627 			monitor.endTask();
628 
629 			// commit the index builder - a new index is persisted
630 			if (!builder.commit())
631 				throw new IndexWriteException();
632 		}
633 		return toBeDeleted.size() == 0;
634 	}
635 
636 	private void checkoutGitlink(String path, DirCacheEntry entry)
637 			throws IOException {
638 		File gitlinkDir = new File(repo.getWorkTree(), path);
639 		FileUtils.mkdirs(gitlinkDir, true);
640 		FS fs = repo.getFS();
641 		entry.setLastModified(fs.lastModified(gitlinkDir));
642 	}
643 
644 	private static ArrayList<String> filterOut(ArrayList<String> strings,
645 			IntList indicesToRemove) {
646 		int n = indicesToRemove.size();
647 		if (n == strings.size()) {
648 			return new ArrayList<>(0);
649 		}
650 		switch (n) {
651 		case 0:
652 			return strings;
653 		case 1:
654 			strings.remove(indicesToRemove.get(0));
655 			return strings;
656 		default:
657 			int length = strings.size();
658 			ArrayList<String> result = new ArrayList<>(length - n);
659 			// Process indicesToRemove from the back; we know that it
660 			// contains indices in descending order.
661 			int j = n - 1;
662 			int idx = indicesToRemove.get(j);
663 			for (int i = 0; i < length; i++) {
664 				if (i == idx) {
665 					idx = (--j >= 0) ? indicesToRemove.get(j) : -1;
666 				} else {
667 					result.add(strings.get(i));
668 				}
669 			}
670 			return result;
671 		}
672 	}
673 
674 	private static boolean isSamePrefix(String a, String b) {
675 		int as = a.lastIndexOf('/');
676 		int bs = b.lastIndexOf('/');
677 		return a.substring(0, as + 1).equals(b.substring(0, bs + 1));
678 	}
679 
680 	 private void removeEmptyParents(File f) {
681 		File parentFile = f.getParentFile();
682 
683 		while (parentFile != null && !parentFile.equals(repo.getWorkTree())) {
684 			if (!parentFile.delete())
685 				break;
686 			parentFile = parentFile.getParentFile();
687 		}
688 	}
689 
690 	/**
691 	 * Compares whether two pairs of ObjectId and FileMode are equal.
692 	 *
693 	 * @param id1
694 	 * @param mode1
695 	 * @param id2
696 	 * @param mode2
697 	 * @return <code>true</code> if FileModes and ObjectIds are equal.
698 	 *         <code>false</code> otherwise
699 	 */
700 	private boolean equalIdAndMode(ObjectIdrg/eclipse/jgit/lib/ObjectId.html#ObjectId">ObjectId id1, FileMode mode1, ObjectId id2,
701 			FileMode mode2) {
702 		if (!mode1.equals(mode2))
703 			return false;
704 		return id1 != null ? id1.equals(id2) : id2 == null;
705 	}
706 
707 	/**
708 	 * Here the main work is done. This method is called for each existing path
709 	 * in head, index and merge. This method decides what to do with the
710 	 * corresponding index entry: keep it, update it, remove it or mark a
711 	 * conflict.
712 	 *
713 	 * @param h
714 	 *            the entry for the head
715 	 * @param m
716 	 *            the entry for the merge
717 	 * @param i
718 	 *            the entry for the index
719 	 * @param f
720 	 *            the file in the working tree
721 	 * @throws IOException
722 	 */
723 
724 	void processEntry(CanonicalTreeParser../../org/eclipse/jgit/treewalk/CanonicalTreeParser.html#CanonicalTreeParser">CanonicalTreeParser h, CanonicalTreeParser m,
725 			DirCacheBuildIterator i, WorkingTreeIterator f) throws IOException {
726 		DirCacheEntry dce = i != null ? i.getDirCacheEntry() : null;
727 
728 		String name = walk.getPathString();
729 
730 		if (m != null)
731 			checkValidPath(m);
732 
733 		if (i == null && m == null && h == null) {
734 			// File/Directory conflict case #20
735 			if (walk.isDirectoryFileConflict())
736 				// TODO: check whether it is always correct to report a conflict here
737 				conflict(name, null, null, null);
738 
739 			// file only exists in working tree -> ignore it
740 			return;
741 		}
742 
743 		ObjectId iId = (i == null ? null : i.getEntryObjectId());
744 		ObjectId mId = (m == null ? null : m.getEntryObjectId());
745 		ObjectId hId = (h == null ? null : h.getEntryObjectId());
746 		FileMode iMode = (i == null ? null : i.getEntryFileMode());
747 		FileMode mMode = (m == null ? null : m.getEntryFileMode());
748 		FileMode hMode = (h == null ? null : h.getEntryFileMode());
749 
750 		/**
751 		 * <pre>
752 		 *  File/Directory conflicts:
753 		 *  the following table from ReadTreeTest tells what to do in case of directory/file
754 		 *  conflicts. I give comments here
755 		 *
756 		 *      H        I       M     Clean     H==M     H==I    I==M         Result
757 		 *      ------------------------------------------------------------------
758 		 * 1    D        D       F       Y         N       Y       N           Update
759 		 * 2    D        D       F       N         N       Y       N           Conflict
760 		 * 3    D        F       D                 Y       N       N           Keep
761 		 * 4    D        F       D                 N       N       N           Conflict
762 		 * 5    D        F       F       Y         N       N       Y           Keep
763 		 * 5b   D        F       F       Y         N       N       N           Conflict
764 		 * 6    D        F       F       N         N       N       Y           Keep
765 		 * 6b   D        F       F       N         N       N       N           Conflict
766 		 * 7    F        D       F       Y         Y       N       N           Update
767 		 * 8    F        D       F       N         Y       N       N           Conflict
768 		 * 9    F        D       F                 N       N       N           Conflict
769 		 * 10   F        D       D                 N       N       Y           Keep
770 		 * 11   F        D       D                 N       N       N           Conflict
771 		 * 12   F        F       D       Y         N       Y       N           Update
772 		 * 13   F        F       D       N         N       Y       N           Conflict
773 		 * 14   F        F       D                 N       N       N           Conflict
774 		 * 15   0        F       D                 N       N       N           Conflict
775 		 * 16   0        D       F       Y         N       N       N           Update
776 		 * 17   0        D       F                 N       N       N           Conflict
777 		 * 18   F        0       D                                             Update
778 		 * 19   D        0       F                                             Update
779 		 * 20   0        0       F       N (worktree=dir)                      Conflict
780 		 * </pre>
781 		 */
782 
783 		// The information whether head,index,merge iterators are currently
784 		// pointing to file/folder/non-existing is encoded into this variable.
785 		//
786 		// To decode write down ffMask in hexadecimal form. The last digit
787 		// represents the state for the merge iterator, the second last the
788 		// state for the index iterator and the third last represents the state
789 		// for the head iterator. The hexadecimal constant "F" stands for
790 		// "file", a "D" stands for "directory" (tree), and a "0" stands for
791 		// non-existing. Symbolic links and git links are treated as File here.
792 		//
793 		// Examples:
794 		// ffMask == 0xFFD -> Head=File, Index=File, Merge=Tree
795 		// ffMask == 0xDD0 -> Head=Tree, Index=Tree, Merge=Non-Existing
796 
797 		int ffMask = 0;
798 		if (h != null)
799 			ffMask = FileMode.TREE.equals(hMode) ? 0xD00 : 0xF00;
800 		if (i != null)
801 			ffMask |= FileMode.TREE.equals(iMode) ? 0x0D0 : 0x0F0;
802 		if (m != null)
803 			ffMask |= FileMode.TREE.equals(mMode) ? 0x00D : 0x00F;
804 
805 		// Check whether we have a possible file/folder conflict. Therefore we
806 		// need a least one file and one folder.
807 		if (((ffMask & 0x222) != 0x000)
808 				&& (((ffMask & 0x00F) == 0x00D) || ((ffMask & 0x0F0) == 0x0D0) || ((ffMask & 0xF00) == 0xD00))) {
809 
810 			// There are 3*3*3=27 possible combinations of file/folder
811 			// conflicts. Some of them are not-relevant because
812 			// they represent no conflict, e.g. 0xFFF, 0xDDD, ... The following
813 			// switch processes all relevant cases.
814 			switch (ffMask) {
815 			case 0xDDF: // 1 2
816 				if (f != null && isModifiedSubtree_IndexWorkingtree(name)) {
817 					conflict(name, dce, h, m); // 1
818 				} else {
819 					update(name, mId, mMode); // 2
820 				}
821 
822 				break;
823 			case 0xDFD: // 3 4
824 				keep(dce);
825 				break;
826 			case 0xF0D: // 18
827 				remove(name);
828 				break;
829 			case 0xDFF: // 5 5b 6 6b
830 				if (equalIdAndMode(iId, iMode, mId, mMode))
831 					keep(dce); // 5 6
832 				else
833 					conflict(name, dce, h, m); // 5b 6b
834 				break;
835 			case 0xFDD: // 10 11
836 				// TODO: make use of tree extension as soon as available in jgit
837 				// we would like to do something like
838 				// if (!equalIdAndMode(iId, iMode, mId, mMode)
839 				//   conflict(name, i.getDirCacheEntry(), h, m);
840 				// But since we don't know the id of a tree in the index we do
841 				// nothing here and wait that conflicts between index and merge
842 				// are found later
843 				break;
844 			case 0xD0F: // 19
845 				update(name, mId, mMode);
846 				break;
847 			case 0xDF0: // conflict without a rule
848 			case 0x0FD: // 15
849 				conflict(name, dce, h, m);
850 				break;
851 			case 0xFDF: // 7 8 9
852 				if (equalIdAndMode(hId, hMode, mId, mMode)) {
853 					if (isModifiedSubtree_IndexWorkingtree(name))
854 						conflict(name, dce, h, m); // 8
855 					else
856 						update(name, mId, mMode); // 7
857 				} else
858 					conflict(name, dce, h, m); // 9
859 				break;
860 			case 0xFD0: // keep without a rule
861 				keep(dce);
862 				break;
863 			case 0xFFD: // 12 13 14
864 				if (equalIdAndMode(hId, hMode, iId, iMode))
865 					if (f != null
866 							&& f.isModified(dce, true,
867 									this.walk.getObjectReader()))
868 						conflict(name, dce, h, m); // 13
869 					else
870 						remove(name); // 12
871 				else
872 					conflict(name, dce, h, m); // 14
873 				break;
874 			case 0x0DF: // 16 17
875 				if (!isModifiedSubtree_IndexWorkingtree(name))
876 					update(name, mId, mMode);
877 				else
878 					conflict(name, dce, h, m);
879 				break;
880 			default:
881 				keep(dce);
882 			}
883 			return;
884 		}
885 
886 		if ((ffMask & 0x222) == 0) {
887 			// HEAD, MERGE and index don't contain a file (e.g. all contain a
888 			// folder)
889 			if (f == null || FileMode.TREE.equals(f.getEntryFileMode())) {
890 				// the workingtree entry doesn't exist or also contains a folder
891 				// -> no problem
892 				return;
893 			} else {
894 				// the workingtree entry exists and is not a folder
895 				if (!idEqual(h, m)) {
896 					// Because HEAD and MERGE differ we will try to update the
897 					// workingtree with a folder -> return a conflict
898 					conflict(name, null, null, null);
899 				}
900 				return;
901 			}
902 		}
903 
904 		if ((ffMask == 0x00F) && f != null && FileMode.TREE.equals(f.getEntryFileMode())) {
905 			// File/Directory conflict case #20
906 			conflict(name, null, h, m);
907 			return;
908 		}
909 
910 		if (i == null) {
911 			// Nothing in Index
912 			// At least one of Head, Index, Merge is not empty
913 			// make sure not to overwrite untracked files
914 			if (f != null && !f.isEntryIgnored()) {
915 				// A submodule is not a file. We should ignore it
916 				if (!FileMode.GITLINK.equals(mMode)) {
917 					// a dirty worktree: the index is empty but we have a
918 					// workingtree-file
919 					if (mId == null
920 							|| !equalIdAndMode(mId, mMode,
921 									f.getEntryObjectId(), f.getEntryFileMode())) {
922 						conflict(name, null, h, m);
923 						return;
924 					}
925 				}
926 			}
927 
928 			/**
929 			 * <pre>
930 			 * 	          I (index)     H        M     H==M  Result
931 			 * 	        -------------------------------------------
932 			 * 	        0 nothing    nothing  nothing        (does not happen)
933 			 * 	        1 nothing    nothing  exists         use M
934 			 * 	        2 nothing    exists   nothing        remove path from index
935 			 * 	        3 nothing    exists   exists   yes   keep index if not in initial checkout
936 			 *                                               , otherwise use M
937 			 * 	          nothing    exists   exists   no    fail
938 			 * </pre>
939 			 */
940 
941 			if (h == null)
942 				// Nothing in Head
943 				// Nothing in Index
944 				// At least one of Head, Index, Merge is not empty
945 				// -> only Merge contains something for this path. Use it!
946 				// Potentially update the file
947 				update(name, mId, mMode); // 1
948 			else if (m == null)
949 				// Nothing in Merge
950 				// Something in Head
951 				// Nothing in Index
952 				// -> only Head contains something for this path and it should
953 				// be deleted. Potentially removes the file!
954 				remove(name); // 2
955 			else { // 3
956 				// Something in Merge
957 				// Something in Head
958 				// Nothing in Index
959 				// -> Head and Merge contain something (maybe not the same) and
960 				// in the index there is nothing (e.g. 'git rm ...' was
961 				// called before). Ignore the cached deletion and use what we
962 				// find in Merge. Potentially updates the file.
963 				if (equalIdAndMode(hId, hMode, mId, mMode)) {
964 					if (emptyDirCache)
965 						update(name, mId, mMode);
966 					else
967 						keep(dce);
968 				} else
969 					conflict(name, dce, h, m);
970 			}
971 		} else {
972 			// Something in Index
973 			if (h == null) {
974 				// Nothing in Head
975 				// Something in Index
976 				/**
977 				 * <pre>
978 				 * 	          clean I==H  I==M       H        M        Result
979 				 * 	         -----------------------------------------------------
980 				 * 	        4 yes   N/A   N/A     nothing  nothing  keep index
981 				 * 	        5 no    N/A   N/A     nothing  nothing  keep index
982 				 *
983 				 * 	        6 yes   N/A   yes     nothing  exists   keep index
984 				 * 	        7 no    N/A   yes     nothing  exists   keep index
985 				 * 	        8 yes   N/A   no      nothing  exists   fail
986 				 * 	        9 no    N/A   no      nothing  exists   fail
987 				 * </pre>
988 				 */
989 
990 				if (m == null
991 						|| !isModified_IndexTree(name, iId, iMode, mId, mMode,
992 								mergeCommitTree)) {
993 					// Merge contains nothing or the same as Index
994 					// Nothing in Head
995 					// Something in Index
996 					if (m==null && walk.isDirectoryFileConflict()) {
997 						// Nothing in Merge and current path is part of
998 						// File/Folder conflict
999 						// Nothing in Head
1000 						// Something in Index
1001 						if (dce != null
1002 								&& (f == null || f.isModified(dce, true,
1003 										this.walk.getObjectReader())))
1004 							// No file or file is dirty
1005 							// Nothing in Merge and current path is part of
1006 							// File/Folder conflict
1007 							// Nothing in Head
1008 							// Something in Index
1009 							// -> File folder conflict and Merge wants this
1010 							// path to be removed. Since the file is dirty
1011 							// report a conflict
1012 							conflict(name, dce, h, m);
1013 						else
1014 							// A file is present and file is not dirty
1015 							// Nothing in Merge and current path is part of
1016 							// File/Folder conflict
1017 							// Nothing in Head
1018 							// Something in Index
1019 							// -> File folder conflict and Merge wants this path
1020 							// to be removed. Since the file is not dirty remove
1021 							// file and index entry
1022 							remove(name);
1023 					} else
1024 						// Something in Merge or current path is not part of
1025 						// File/Folder conflict
1026 						// Merge contains nothing or the same as Index
1027 						// Nothing in Head
1028 						// Something in Index
1029 						// -> Merge contains nothing new. Keep the index.
1030 						keep(dce);
1031 				} else
1032 					// Merge contains something and it is not the same as Index
1033 					// Nothing in Head
1034 					// Something in Index
1035 					// -> Index contains something new (different from Head)
1036 					// and Merge is different from Index. Report a conflict
1037 					conflict(name, dce, h, m);
1038 			} else if (m == null) {
1039 				// Nothing in Merge
1040 				// Something in Head
1041 				// Something in Index
1042 
1043 				/**
1044 				 * <pre>
1045 				 * 	           clean I==H  I==M       H        M        Result
1046 				 * 	         -----------------------------------------------------
1047 				 * 	        10 yes   yes   N/A     exists   nothing  remove path from index
1048 				 * 	        11 no    yes   N/A     exists   nothing  keep file
1049 				 * 	        12 yes   no    N/A     exists   nothing  fail
1050 				 * 	        13 no    no    N/A     exists   nothing  fail
1051 				 * </pre>
1052 				 */
1053 
1054 				if (iMode == FileMode.GITLINK) {
1055 					// A submodule in Index
1056 					// Nothing in Merge
1057 					// Something in Head
1058 					// Submodules that disappear from the checkout must
1059 					// be removed from the index, but not deleted from disk.
1060 					remove(name);
1061 				} else {
1062 					// Something different from a submodule in Index
1063 					// Nothing in Merge
1064 					// Something in Head
1065 					if (!isModified_IndexTree(name, iId, iMode, hId, hMode,
1066 							headCommitTree)) {
1067 						// Index contains the same as Head
1068 						// Something different from a submodule in Index
1069 						// Nothing in Merge
1070 						// Something in Head
1071 						if (f != null
1072 								&& f.isModified(dce, true,
1073 										this.walk.getObjectReader())) {
1074 							// file is dirty
1075 							// Index contains the same as Head
1076 							// Something different from a submodule in Index
1077 							// Nothing in Merge
1078 							// Something in Head
1079 
1080 							if (!FileMode.TREE.equals(f.getEntryFileMode())
1081 									&& FileMode.TREE.equals(iMode))
1082 								// The workingtree contains a file and the index semantically contains a folder.
1083 								// Git considers the workingtree file as untracked. Just keep the untracked file.
1084 								return;
1085 							else
1086 								// -> file is dirty and tracked but is should be
1087 								// removed. That's a conflict
1088 								conflict(name, dce, h, m);
1089 						} else
1090 							// file doesn't exist or is clean
1091 							// Index contains the same as Head
1092 							// Something different from a submodule in Index
1093 							// Nothing in Merge
1094 							// Something in Head
1095 							// -> Remove from index and delete the file
1096 							remove(name);
1097 					} else
1098 						// Index contains something different from Head
1099 						// Something different from a submodule in Index
1100 						// Nothing in Merge
1101 						// Something in Head
1102 						// -> Something new is in index (and maybe even on the
1103 						// filesystem). But Merge wants the path to be removed.
1104 						// Report a conflict
1105 						conflict(name, dce, h, m);
1106 				}
1107 			} else {
1108 				// Something in Merge
1109 				// Something in Head
1110 				// Something in Index
1111 				if (!equalIdAndMode(hId, hMode, mId, mMode)
1112 						&& isModified_IndexTree(name, iId, iMode, hId, hMode,
1113 								headCommitTree)
1114 						&& isModified_IndexTree(name, iId, iMode, mId, mMode,
1115 								mergeCommitTree))
1116 					// All three contents in Head, Merge, Index differ from each
1117 					// other
1118 					// -> All contents differ. Report a conflict.
1119 					conflict(name, dce, h, m);
1120 				else
1121 					// At least two of the contents of Head, Index, Merge
1122 					// are the same
1123 					// Something in Merge
1124 					// Something in Head
1125 					// Something in Index
1126 
1127 				if (!isModified_IndexTree(name, iId, iMode, hId, hMode,
1128 						headCommitTree)
1129 						&& isModified_IndexTree(name, iId, iMode, mId, mMode,
1130 								mergeCommitTree)) {
1131 						// Head contains the same as Index. Merge differs
1132 						// Something in Merge
1133 
1134 					// For submodules just update the index with the new SHA-1
1135 					if (dce != null
1136 							&& FileMode.GITLINK.equals(dce.getFileMode())) {
1137 						// Index and Head contain the same submodule. Merge
1138 						// differs
1139 						// Something in Merge
1140 						// -> Nothing new in index. Move to merge.
1141 						// Potentially updates the file
1142 
1143 						// TODO check that we don't overwrite some unsaved
1144 						// file content
1145 						update(name, mId, mMode);
1146 					} else if (dce != null
1147 							&& (f != null && f.isModified(dce, true,
1148 									this.walk.getObjectReader()))) {
1149 						// File exists and is dirty
1150 						// Head and Index don't contain a submodule
1151 						// Head contains the same as Index. Merge differs
1152 						// Something in Merge
1153 						// -> Merge wants the index and file to be updated
1154 						// but the file is dirty. Report a conflict
1155 						conflict(name, dce, h, m);
1156 					} else {
1157 						// File doesn't exist or is clean
1158 						// Head and Index don't contain a submodule
1159 						// Head contains the same as Index. Merge differs
1160 						// Something in Merge
1161 						// -> Standard case when switching between branches:
1162 						// Nothing new in index but something different in
1163 						// Merge. Update index and file
1164 						update(name, mId, mMode);
1165 					}
1166 				} else {
1167 					// Head differs from index or merge is same as index
1168 					// At least two of the contents of Head, Index, Merge
1169 					// are the same
1170 					// Something in Merge
1171 					// Something in Head
1172 					// Something in Index
1173 
1174 					// Can be formulated as: Either all three states are
1175 					// equal or Merge is equal to Head or Index and differs
1176 					// to the other one.
1177 					// -> In all three cases we don't touch index and file.
1178 
1179 					keep(dce);
1180 				}
1181 			}
1182 		}
1183 	}
1184 
1185 	private static boolean idEqual(AbstractTreeIterator a,
1186 			AbstractTreeIterator b) {
1187 		if (a == b) {
1188 			return true;
1189 		}
1190 		if (a == null || b == null) {
1191 			return false;
1192 		}
1193 		return a.getEntryObjectId().equals(b.getEntryObjectId());
1194 	}
1195 
1196 	/**
1197 	 * A conflict is detected - add the three different stages to the index
1198 	 * @param path the path of the conflicting entry
1199 	 * @param e the previous index entry
1200 	 * @param h the first tree you want to merge (the HEAD)
1201 	 * @param m the second tree you want to merge
1202 	 */
1203 	private void conflict(String path, DirCacheEntry e, AbstractTreeIterator./../org/eclipse/jgit/treewalk/AbstractTreeIterator.html#AbstractTreeIterator">AbstractTreeIterator h, AbstractTreeIterator m) {
1204 		conflicts.add(path);
1205 
1206 		DirCacheEntry entry;
1207 		if (e != null) {
1208 			entry = new DirCacheEntry(e.getPathString(), DirCacheEntry.STAGE_1);
1209 			entry.copyMetaData(e, true);
1210 			builder.add(entry);
1211 		}
1212 
1213 		if (h != null && !FileMode.TREE.equals(h.getEntryFileMode())) {
1214 			entry = new DirCacheEntry(h.getEntryPathString(), DirCacheEntry.STAGE_2);
1215 			entry.setFileMode(h.getEntryFileMode());
1216 			entry.setObjectId(h.getEntryObjectId());
1217 			builder.add(entry);
1218 		}
1219 
1220 		if (m != null && !FileMode.TREE.equals(m.getEntryFileMode())) {
1221 			entry = new DirCacheEntry(m.getEntryPathString(), DirCacheEntry.STAGE_3);
1222 			entry.setFileMode(m.getEntryFileMode());
1223 			entry.setObjectId(m.getEntryObjectId());
1224 			builder.add(entry);
1225 		}
1226 	}
1227 
1228 	private void keep(DirCacheEntry e) {
1229 		if (e != null && !FileMode.TREE.equals(e.getFileMode()))
1230 			builder.add(e);
1231 	}
1232 
1233 	private void remove(String path) {
1234 		removed.add(path);
1235 	}
1236 
1237 	private void update(String path, ObjectId mId, FileMode mode)
1238 			throws IOException {
1239 		if (!FileMode.TREE.equals(mode)) {
1240 			updated.put(path, new CheckoutMetadata(
1241 					walk.getEolStreamType(CHECKOUT_OP),
1242 					walk.getFilterCommand(Constants.ATTR_FILTER_TYPE_SMUDGE)));
1243 
1244 			DirCacheEntry entry = new DirCacheEntry(path, DirCacheEntry.STAGE_0);
1245 			entry.setObjectId(mId);
1246 			entry.setFileMode(mode);
1247 			builder.add(entry);
1248 		}
1249 	}
1250 
1251 	/**
1252 	 * If <code>true</code>, will scan first to see if it's possible to check
1253 	 * out, otherwise throw
1254 	 * {@link org.eclipse.jgit.errors.CheckoutConflictException}. If
1255 	 * <code>false</code>, it will silently deal with the problem.
1256 	 *
1257 	 * @param failOnConflict
1258 	 *            a boolean.
1259 	 */
1260 	public void setFailOnConflict(boolean failOnConflict) {
1261 		this.failOnConflict = failOnConflict;
1262 	}
1263 
1264 	/**
1265 	 * This method implements how to handle conflicts when
1266 	 * {@link #failOnConflict} is false
1267 	 *
1268 	 * @throws CheckoutConflictException
1269 	 */
1270 	private void cleanUpConflicts() throws CheckoutConflictException {
1271 		// TODO: couldn't we delete unsaved worktree content here?
1272 		for (String c : conflicts) {
1273 			File conflict = new File(repo.getWorkTree(), c);
1274 			if (!conflict.delete())
1275 				throw new CheckoutConflictException(MessageFormat.format(
1276 						JGitText.get().cannotDeleteFile, c));
1277 			removeEmptyParents(conflict);
1278 		}
1279 		for (String r : removed) {
1280 			File file = new File(repo.getWorkTree(), r);
1281 			if (!file.delete())
1282 				throw new CheckoutConflictException(
1283 						MessageFormat.format(JGitText.get().cannotDeleteFile,
1284 								file.getAbsolutePath()));
1285 			removeEmptyParents(file);
1286 		}
1287 	}
1288 
1289 	/**
1290 	 * Checks whether the subtree starting at a given path differs between Index and
1291 	 * workingtree.
1292 	 *
1293 	 * @param path
1294 	 * @return true if the subtrees differ
1295 	 * @throws CorruptObjectException
1296 	 * @throws IOException
1297 	 */
1298 	private boolean isModifiedSubtree_IndexWorkingtree(String path)
1299 			throws CorruptObjectException, IOException {
1300 		try (NameConflictTreeWalkTreeWalk.html#NameConflictTreeWalk">NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
1301 			int dciPos = tw.addTree(new DirCacheIterator(dc));
1302 			FileTreeIterator fti = new FileTreeIterator(repo);
1303 			tw.addTree(fti);
1304 			fti.setDirCacheIterator(tw, dciPos);
1305 			tw.setRecursive(true);
1306 			tw.setFilter(PathFilter.create(path));
1307 			DirCacheIterator dcIt;
1308 			WorkingTreeIterator wtIt;
1309 			while (tw.next()) {
1310 				dcIt = tw.getTree(0, DirCacheIterator.class);
1311 				wtIt = tw.getTree(1, WorkingTreeIterator.class);
1312 				if (dcIt == null || wtIt == null)
1313 					return true;
1314 				if (wtIt.isModified(dcIt.getDirCacheEntry(), true,
1315 						this.walk.getObjectReader())) {
1316 					return true;
1317 				}
1318 			}
1319 			return false;
1320 		}
1321 	}
1322 
1323 	private boolean isModified_IndexTree(String path, ObjectId iId,
1324 			FileMode iMode, ObjectIdrg/eclipse/jgit/lib/ObjectId.html#ObjectId">ObjectId tId, FileMode tMode, ObjectId rootTree)
1325 			throws CorruptObjectException, IOException {
1326 		if (iMode != tMode)
1327 			return true;
1328 		if (FileMode.TREE.equals(iMode)
1329 				&& (iId == null || ObjectId.zeroId().equals(iId)))
1330 			return isModifiedSubtree_IndexTree(path, rootTree);
1331 		else
1332 			return !equalIdAndMode(iId, iMode, tId, tMode);
1333 	}
1334 
1335 	/**
1336 	 * Checks whether the subtree starting at a given path differs between Index and
1337 	 * some tree.
1338 	 *
1339 	 * @param path
1340 	 * @param tree
1341 	 *            the tree to compare
1342 	 * @return true if the subtrees differ
1343 	 * @throws CorruptObjectException
1344 	 * @throws IOException
1345 	 */
1346 	private boolean isModifiedSubtree_IndexTree(String path, ObjectId tree)
1347 			throws CorruptObjectException, IOException {
1348 		try (NameConflictTreeWalkTreeWalk.html#NameConflictTreeWalk">NameConflictTreeWalk tw = new NameConflictTreeWalk(repo)) {
1349 			tw.addTree(new DirCacheIterator(dc));
1350 			tw.addTree(tree);
1351 			tw.setRecursive(true);
1352 			tw.setFilter(PathFilter.create(path));
1353 			while (tw.next()) {
1354 				AbstractTreeIterator dcIt = tw.getTree(0,
1355 						DirCacheIterator.class);
1356 				AbstractTreeIterator treeIt = tw.getTree(1,
1357 						AbstractTreeIterator.class);
1358 				if (dcIt == null || treeIt == null)
1359 					return true;
1360 				if (dcIt.getEntryRawMode() != treeIt.getEntryRawMode())
1361 					return true;
1362 				if (!dcIt.getEntryObjectId().equals(treeIt.getEntryObjectId()))
1363 					return true;
1364 			}
1365 			return false;
1366 		}
1367 	}
1368 
1369 	/**
1370 	 * Updates the file in the working tree with content and mode from an entry
1371 	 * in the index. The new content is first written to a new temporary file in
1372 	 * the same directory as the real file. Then that new file is renamed to the
1373 	 * final filename.
1374 	 *
1375 	 * <p>
1376 	 * <b>Note:</b> if the entry path on local file system exists as a non-empty
1377 	 * directory, and the target entry type is a link or file, the checkout will
1378 	 * fail with {@link java.io.IOException} since existing non-empty directory
1379 	 * cannot be renamed to file or link without deleting it recursively.
1380 	 * </p>
1381 	 *
1382 	 * <p>
1383 	 * TODO: this method works directly on File IO, we may need another
1384 	 * abstraction (like WorkingTreeIterator). This way we could tell e.g.
1385 	 * Eclipse that Files in the workspace got changed
1386 	 * </p>
1387 	 *
1388 	 * @param repo
1389 	 *            repository managing the destination work tree.
1390 	 * @param entry
1391 	 *            the entry containing new mode and content
1392 	 * @param or
1393 	 *            object reader to use for checkout
1394 	 * @throws java.io.IOException
1395 	 * @since 3.6
1396 	 * @deprecated since 5.1, use
1397 	 *             {@link #checkoutEntry(Repository, DirCacheEntry, ObjectReader, boolean, CheckoutMetadata)}
1398 	 *             instead
1399 	 */
1400 	@Deprecated
1401 	public static void checkoutEntry(Repository repo, DirCacheEntry entry,
1402 			ObjectReader or) throws IOException {
1403 		checkoutEntry(repo, entry, or, false, null);
1404 	}
1405 
1406 	/**
1407 	 * Updates the file in the working tree with content and mode from an entry
1408 	 * in the index. The new content is first written to a new temporary file in
1409 	 * the same directory as the real file. Then that new file is renamed to the
1410 	 * final filename.
1411 	 *
1412 	 * <p>
1413 	 * <b>Note:</b> if the entry path on local file system exists as a file, it
1414 	 * will be deleted and if it exists as a directory, it will be deleted
1415 	 * recursively, independently if has any content.
1416 	 * </p>
1417 	 *
1418 	 * <p>
1419 	 * TODO: this method works directly on File IO, we may need another
1420 	 * abstraction (like WorkingTreeIterator). This way we could tell e.g.
1421 	 * Eclipse that Files in the workspace got changed
1422 	 * </p>
1423 	 *
1424 	 * @param repo
1425 	 *            repository managing the destination work tree.
1426 	 * @param entry
1427 	 *            the entry containing new mode and content
1428 	 * @param or
1429 	 *            object reader to use for checkout
1430 	 * @param deleteRecursive
1431 	 *            true to recursively delete final path if it exists on the file
1432 	 *            system
1433 	 * @param checkoutMetadata
1434 	 *            containing
1435 	 *            <ul>
1436 	 *            <li>smudgeFilterCommand to be run for smudging the entry to be
1437 	 *            checked out</li>
1438 	 *            <li>eolStreamType used for stream conversion</li>
1439 	 *            </ul>
1440 	 * @throws java.io.IOException
1441 	 * @since 4.2
1442 	 */
1443 	public static void checkoutEntry(Repository repo, DirCacheEntry entry,
1444 			ObjectReader or, boolean deleteRecursive,
1445 			CheckoutMetadata checkoutMetadata) throws IOException {
1446 		if (checkoutMetadata == null)
1447 			checkoutMetadata = CheckoutMetadata.EMPTY;
1448 		ObjectLoader ol = or.open(entry.getObjectId());
1449 		File f = new File(repo.getWorkTree(), entry.getPathString());
1450 		File parentDir = f.getParentFile();
1451 		FileUtils.mkdirs(parentDir, true);
1452 		FS fs = repo.getFS();
1453 		WorkingTreeOptions opt = repo.getConfig().get(WorkingTreeOptions.KEY);
1454 		if (entry.getFileMode() == FileMode.SYMLINK
1455 				&& opt.getSymLinks() == SymLinks.TRUE) {
1456 			byte[] bytes = ol.getBytes();
1457 			String target = RawParseUtils.decode(bytes);
1458 			if (deleteRecursive && f.isDirectory()) {
1459 				FileUtils.delete(f, FileUtils.RECURSIVE);
1460 			}
1461 			fs.createSymLink(f, target);
1462 			entry.setLength(bytes.length);
1463 			entry.setLastModified(fs.lastModified(f));
1464 			return;
1465 		}
1466 
1467 		String name = f.getName();
1468 		if (name.length() > 200) {
1469 			name = name.substring(0, 200);
1470 		}
1471 		File tmpFile = File.createTempFile(
1472 				"._" + name, null, parentDir); //$NON-NLS-1$
1473 
1474 		EolStreamType nonNullEolStreamType;
1475 		if (checkoutMetadata.eolStreamType != null) {
1476 			nonNullEolStreamType = checkoutMetadata.eolStreamType;
1477 		} else if (opt.getAutoCRLF() == AutoCRLF.TRUE) {
1478 			nonNullEolStreamType = EolStreamType.AUTO_CRLF;
1479 		} else {
1480 			nonNullEolStreamType = EolStreamType.DIRECT;
1481 		}
1482 		try (OutputStream channel = EolStreamTypeUtil.wrapOutputStream(
1483 				new FileOutputStream(tmpFile), nonNullEolStreamType)) {
1484 			if (checkoutMetadata.smudgeFilterCommand != null) {
1485 				if (FilterCommandRegistry
1486 						.isRegistered(checkoutMetadata.smudgeFilterCommand)) {
1487 					runBuiltinFilterCommand(repo, checkoutMetadata, ol,
1488 							channel);
1489 				} else {
1490 					runExternalFilterCommand(repo, entry, checkoutMetadata, ol,
1491 							fs, channel);
1492 				}
1493 			} else {
1494 				ol.copyTo(channel);
1495 			}
1496 		}
1497 		// The entry needs to correspond to the on-disk filesize. If the content
1498 		// was filtered (either by autocrlf handling or smudge filters) ask the
1499 		// filesystem again for the length. Otherwise the objectloader knows the
1500 		// size
1501 		if (checkoutMetadata.eolStreamType == EolStreamType.DIRECT
1502 				&& checkoutMetadata.smudgeFilterCommand == null) {
1503 			entry.setLength(ol.getSize());
1504 		} else {
1505 			entry.setLength(tmpFile.length());
1506 		}
1507 
1508 		if (opt.isFileMode() && fs.supportsExecute()) {
1509 			if (FileMode.EXECUTABLE_FILE.equals(entry.getRawMode())) {
1510 				if (!fs.canExecute(tmpFile))
1511 					fs.setExecute(tmpFile, true);
1512 			} else {
1513 				if (fs.canExecute(tmpFile))
1514 					fs.setExecute(tmpFile, false);
1515 			}
1516 		}
1517 		try {
1518 			if (deleteRecursive && f.isDirectory()) {
1519 				FileUtils.delete(f, FileUtils.RECURSIVE);
1520 			}
1521 			FileUtils.rename(tmpFile, f, StandardCopyOption.ATOMIC_MOVE);
1522 		} catch (IOException e) {
1523 			throw new IOException(
1524 					MessageFormat.format(JGitText.get().renameFileFailed,
1525 							tmpFile.getPath(), f.getPath()),
1526 					e);
1527 		} finally {
1528 			if (tmpFile.exists()) {
1529 				FileUtils.delete(tmpFile);
1530 			}
1531 		}
1532 		entry.setLastModified(fs.lastModified(f));
1533 	}
1534 
1535 	// Run an external filter command
1536 	private static void runExternalFilterCommand(Repository repo,
1537 			DirCacheEntry entry,
1538 			CheckoutMetadata checkoutMetadata, ObjectLoader ol, FS fs,
1539 			OutputStream channel) throws IOException {
1540 		ProcessBuilder filterProcessBuilder = fs.runInShell(
1541 				checkoutMetadata.smudgeFilterCommand, new String[0]);
1542 		filterProcessBuilder.directory(repo.getWorkTree());
1543 		filterProcessBuilder.environment().put(Constants.GIT_DIR_KEY,
1544 				repo.getDirectory().getAbsolutePath());
1545 		ExecutionResult result;
1546 		int rc;
1547 		try {
1548 			// TODO: wire correctly with AUTOCRLF
1549 			result = fs.execute(filterProcessBuilder, ol.openStream());
1550 			rc = result.getRc();
1551 			if (rc == 0) {
1552 				result.getStdout().writeTo(channel,
1553 						NullProgressMonitor.INSTANCE);
1554 			}
1555 		} catch (IOException | InterruptedException e) {
1556 			throw new IOException(new FilterFailedException(e,
1557 					checkoutMetadata.smudgeFilterCommand,
1558 					entry.getPathString()));
1559 		}
1560 		if (rc != 0) {
1561 			throw new IOException(new FilterFailedException(rc,
1562 					checkoutMetadata.smudgeFilterCommand,
1563 					entry.getPathString(),
1564 					result.getStdout().toByteArray(MAX_EXCEPTION_TEXT_SIZE),
1565 					RawParseUtils.decode(result.getStderr()
1566 							.toByteArray(MAX_EXCEPTION_TEXT_SIZE))));
1567 		}
1568 	}
1569 
1570 	// Run a builtin filter command
1571 	private static void runBuiltinFilterCommand(Repository repo,
1572 			CheckoutMetadata checkoutMetadata, ObjectLoader ol,
1573 			OutputStream channel) throws MissingObjectException, IOException {
1574 		boolean isMandatory = repo.getConfig().getBoolean(
1575 				ConfigConstants.CONFIG_FILTER_SECTION,
1576 				ConfigConstants.CONFIG_SECTION_LFS,
1577 				ConfigConstants.CONFIG_KEY_REQUIRED, false);
1578 		FilterCommand command = null;
1579 		try {
1580 			command = FilterCommandRegistry.createFilterCommand(
1581 					checkoutMetadata.smudgeFilterCommand, repo, ol.openStream(),
1582 					channel);
1583 		} catch (IOException e) {
1584 			LOG.error(JGitText.get().failedToDetermineFilterDefinition, e);
1585 			if (!isMandatory) {
1586 				// In case an IOException occurred during creating of the
1587 				// command then proceed as if there would not have been a
1588 				// builtin filter (only if the filter is not mandatory).
1589 				ol.copyTo(channel);
1590 			} else {
1591 				throw e;
1592 			}
1593 		}
1594 		if (command != null) {
1595 			while (command.run() != -1) {
1596 				// loop as long as command.run() tells there is work to do
1597 			}
1598 		}
1599 	}
1600 
1601 	@SuppressWarnings("deprecation")
1602 	private static void checkValidPath(CanonicalTreeParser t)
1603 			throws InvalidPathException {
1604 		ObjectChecker chk = new ObjectChecker()
1605 			.setSafeForWindows(SystemReader.getInstance().isWindows())
1606 			.setSafeForMacOS(SystemReader.getInstance().isMacOS());
1607 		for (CanonicalTreeParser i = t; i != null; i = i.getParent())
1608 			checkValidPathSegment(chk, i);
1609 	}
1610 
1611 	private static void checkValidPathSegment(ObjectChecker chk,
1612 			CanonicalTreeParser t) throws InvalidPathException {
1613 		try {
1614 			int ptr = t.getNameOffset();
1615 			int end = ptr + t.getNameLength();
1616 			chk.checkPathSegment(t.getEntryPathBuffer(), ptr, end);
1617 		} catch (CorruptObjectException err) {
1618 			String path = t.getEntryPathString();
1619 			InvalidPathException i = new InvalidPathException(path);
1620 			i.initCause(err);
1621 			throw i;
1622 		}
1623 	}
1624 }