View Javadoc
1   /*
2    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
3    * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
4    * Copyright (C) 2010, Matthias Sohn <matthias.sohn@sap.com>
5    * Copyright (C) 2012-2013, Robin Rosenberg and others
6    *
7    * This program and the accompanying materials are made available under the
8    * terms of the Eclipse Distribution License v. 1.0 which is available at
9    * https://www.eclipse.org/org/documents/edl-v10.php.
10   *
11   * SPDX-License-Identifier: BSD-3-Clause
12   */
13  
14  package org.eclipse.jgit.treewalk;
15  
16  import static java.nio.charset.StandardCharsets.UTF_8;
17  
18  import java.io.ByteArrayInputStream;
19  import java.io.File;
20  import java.io.FileInputStream;
21  import java.io.FileNotFoundException;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.nio.ByteBuffer;
25  import java.nio.CharBuffer;
26  import java.nio.charset.CharacterCodingException;
27  import java.nio.charset.CharsetEncoder;
28  import java.text.MessageFormat;
29  import java.time.Instant;
30  import java.util.Arrays;
31  import java.util.Collections;
32  import java.util.Comparator;
33  import java.util.HashMap;
34  import java.util.Map;
35  
36  import org.eclipse.jgit.api.errors.FilterFailedException;
37  import org.eclipse.jgit.attributes.AttributesNode;
38  import org.eclipse.jgit.attributes.AttributesRule;
39  import org.eclipse.jgit.attributes.FilterCommand;
40  import org.eclipse.jgit.attributes.FilterCommandRegistry;
41  import org.eclipse.jgit.diff.RawText;
42  import org.eclipse.jgit.dircache.DirCacheEntry;
43  import org.eclipse.jgit.dircache.DirCacheIterator;
44  import org.eclipse.jgit.errors.CorruptObjectException;
45  import org.eclipse.jgit.errors.LargeObjectException;
46  import org.eclipse.jgit.errors.MissingObjectException;
47  import org.eclipse.jgit.errors.NoWorkTreeException;
48  import org.eclipse.jgit.ignore.FastIgnoreRule;
49  import org.eclipse.jgit.ignore.IgnoreNode;
50  import org.eclipse.jgit.internal.JGitText;
51  import org.eclipse.jgit.lib.Constants;
52  import org.eclipse.jgit.lib.CoreConfig;
53  import org.eclipse.jgit.lib.CoreConfig.CheckStat;
54  import org.eclipse.jgit.lib.CoreConfig.EolStreamType;
55  import org.eclipse.jgit.lib.CoreConfig.SymLinks;
56  import org.eclipse.jgit.lib.FileMode;
57  import org.eclipse.jgit.lib.ObjectId;
58  import org.eclipse.jgit.lib.ObjectLoader;
59  import org.eclipse.jgit.lib.ObjectReader;
60  import org.eclipse.jgit.lib.Repository;
61  import org.eclipse.jgit.submodule.SubmoduleWalk;
62  import org.eclipse.jgit.treewalk.TreeWalk.OperationType;
63  import org.eclipse.jgit.util.FS;
64  import org.eclipse.jgit.util.FS.ExecutionResult;
65  import org.eclipse.jgit.util.Holder;
66  import org.eclipse.jgit.util.IO;
67  import org.eclipse.jgit.util.Paths;
68  import org.eclipse.jgit.util.RawParseUtils;
69  import org.eclipse.jgit.util.TemporaryBuffer;
70  import org.eclipse.jgit.util.TemporaryBuffer.LocalFile;
71  import org.eclipse.jgit.util.io.EolStreamTypeUtil;
72  import org.eclipse.jgit.util.sha1.SHA1;
73  
74  /**
75   * Walks a working directory tree as part of a
76   * {@link org.eclipse.jgit.treewalk.TreeWalk}.
77   * <p>
78   * Most applications will want to use the standard implementation of this
79   * iterator, {@link org.eclipse.jgit.treewalk.FileTreeIterator}, as that does
80   * all IO through the standard <code>java.io</code> package. Plugins for a Java
81   * based IDE may however wish to create their own implementations of this class
82   * to allow traversal of the IDE's project space, as well as benefit from any
83   * caching the IDE may have.
84   *
85   * @see FileTreeIterator
86   */
87  public abstract class WorkingTreeIterator extends AbstractTreeIterator {
88  	private static final int MAX_EXCEPTION_TEXT_SIZE = 10 * 1024;
89  
90  	/** An empty entry array, suitable for {@link #init(Entry[])}. */
91  	protected static final Entry[] EOF = {};
92  
93  	/** Size we perform file IO in if we have to read and hash a file. */
94  	static final int BUFFER_SIZE = 2048;
95  
96  	/**
97  	 * Maximum size of files which may be read fully into memory for performance
98  	 * reasons.
99  	 */
100 	private static final long MAXIMUM_FILE_SIZE_TO_READ_FULLY = 65536;
101 
102 	/** Inherited state of this iterator, describing working tree, etc. */
103 	private final IteratorState state;
104 
105 	/** The {@link #idBuffer()} for the current entry. */
106 	private byte[] contentId;
107 
108 	/** Index within {@link #entries} that {@link #contentId} came from. */
109 	private int contentIdFromPtr;
110 
111 	/** List of entries obtained from the subclass. */
112 	private Entry[] entries;
113 
114 	/** Total number of entries in {@link #entries} that are valid. */
115 	private int entryCnt;
116 
117 	/** Current position within {@link #entries}. */
118 	private int ptr;
119 
120 	/** If there is a .gitignore file present, the parsed rules from it. */
121 	private IgnoreNode ignoreNode;
122 
123 	/**
124 	 * cached clean filter command. Use a Ref in order to distinguish between
125 	 * the ref not cached yet and the value null
126 	 */
127 	private Holder<String> cleanFilterCommandHolder;
128 
129 	/**
130 	 * cached eol stream type. Use a Ref in order to distinguish between the ref
131 	 * not cached yet and the value null
132 	 */
133 	private Holder<EolStreamType> eolStreamTypeHolder;
134 
135 	/** Repository that is the root level being iterated over */
136 	protected Repository repository;
137 
138 	/** Cached canonical length, initialized from {@link #idBuffer()} */
139 	private long canonLen = -1;
140 
141 	/** The offset of the content id in {@link #idBuffer()} */
142 	private int contentIdOffset;
143 
144 	/** A comparator for {@link Instant}s. */
145 	private final InstantComparatortantComparator">InstantComparator timestampComparator = new InstantComparator();
146 
147 	/**
148 	 * Create a new iterator with no parent.
149 	 *
150 	 * @param options
151 	 *            working tree options to be used
152 	 */
153 	protected WorkingTreeIterator(WorkingTreeOptions options) {
154 		super();
155 		state = new IteratorState(options);
156 	}
157 
158 	/**
159 	 * Create a new iterator with no parent and a prefix.
160 	 * <p>
161 	 * The prefix path supplied is inserted in front of all paths generated by
162 	 * this iterator. It is intended to be used when an iterator is being
163 	 * created for a subsection of an overall repository and needs to be
164 	 * combined with other iterators that are created to run over the entire
165 	 * repository namespace.
166 	 *
167 	 * @param prefix
168 	 *            position of this iterator in the repository tree. The value
169 	 *            may be null or the empty string to indicate the prefix is the
170 	 *            root of the repository. A trailing slash ('/') is
171 	 *            automatically appended if the prefix does not end in '/'.
172 	 * @param options
173 	 *            working tree options to be used
174 	 */
175 	protected WorkingTreeIterator(final String prefix,
176 			WorkingTreeOptions options) {
177 		super(prefix);
178 		state = new IteratorState(options);
179 	}
180 
181 	/**
182 	 * Create an iterator for a subtree of an existing iterator.
183 	 *
184 	 * @param p
185 	 *            parent tree iterator.
186 	 */
187 	protected WorkingTreeIterator../../../org/eclipse/jgit/treewalk/WorkingTreeIterator.html#WorkingTreeIterator">WorkingTreeIterator(WorkingTreeIterator p) {
188 		super(p);
189 		state = p.state;
190 		repository = p.repository;
191 	}
192 
193 	/**
194 	 * Initialize this iterator for the root level of a repository.
195 	 * <p>
196 	 * This method should only be invoked after calling {@link #init(Entry[])},
197 	 * and only for the root iterator.
198 	 *
199 	 * @param repo
200 	 *            the repository.
201 	 */
202 	protected void initRootIterator(Repository repo) {
203 		repository = repo;
204 		Entry entry;
205 		if (ignoreNode instanceof PerDirectoryIgnoreNode)
206 			entry = ((PerDirectoryIgnoreNode) ignoreNode).entry;
207 		else
208 			entry = null;
209 		ignoreNode = new RootIgnoreNode(entry, repo);
210 	}
211 
212 	/**
213 	 * Define the matching {@link org.eclipse.jgit.dircache.DirCacheIterator},
214 	 * to optimize ObjectIds.
215 	 *
216 	 * Once the DirCacheIterator has been set this iterator must only be
217 	 * advanced by the TreeWalk that is supplied, as it assumes that itself and
218 	 * the corresponding DirCacheIterator are positioned on the same file path
219 	 * whenever {@link #idBuffer()} is invoked.
220 	 *
221 	 * @param walk
222 	 *            the walk that will be advancing this iterator.
223 	 * @param treeId
224 	 *            index of the matching
225 	 *            {@link org.eclipse.jgit.dircache.DirCacheIterator}.
226 	 */
227 	public void setDirCacheIterator(TreeWalk walk, int treeId) {
228 		state.walk = walk;
229 		state.dirCacheTree = treeId;
230 	}
231 
232 	/**
233 	 * Retrieves the {@link DirCacheIterator} at the current entry if
234 	 * {@link #setDirCacheIterator(TreeWalk, int)} was called.
235 	 *
236 	 * @return the DirCacheIterator, or {@code null} if not set or not at the
237 	 *         current entry
238 	 * @since 5.0
239 	 */
240 	protected DirCacheIterator getDirCacheIterator() {
241 		if (state.dirCacheTree >= 0 && state.walk != null) {
242 			return state.walk.getTree(state.dirCacheTree,
243 					DirCacheIterator.class);
244 		}
245 		return null;
246 	}
247 
248 	/**
249 	 * Defines whether this {@link WorkingTreeIterator} walks ignored
250 	 * directories.
251 	 *
252 	 * @param includeIgnored
253 	 *            {@code false} to skip ignored directories, if possible;
254 	 *            {@code true} to always include them in the walk
255 	 * @since 5.0
256 	 */
257 	public void setWalkIgnoredDirectories(boolean includeIgnored) {
258 		state.walkIgnored = includeIgnored;
259 	}
260 
261 	/**
262 	 * Tells whether this {@link WorkingTreeIterator} walks ignored directories.
263 	 *
264 	 * @return {@code true} if it does, {@code false} otherwise
265 	 * @since 5.0
266 	 */
267 	public boolean walksIgnoredDirectories() {
268 		return state.walkIgnored;
269 	}
270 
271 	/** {@inheritDoc} */
272 	@Override
273 	public boolean hasId() {
274 		if (contentIdFromPtr == ptr)
275 			return true;
276 		return (mode & FileMode.TYPE_MASK) == FileMode.TYPE_FILE;
277 	}
278 
279 	/** {@inheritDoc} */
280 	@Override
281 	public byte[] idBuffer() {
282 		if (contentIdFromPtr == ptr)
283 			return contentId;
284 
285 		if (state.walk != null) {
286 			// If there is a matching DirCacheIterator, we can reuse
287 			// its idBuffer, but only if we appear to be clean against
288 			// the cached index information for the path.
289 			DirCacheIterator i = state.walk.getTree(state.dirCacheTree,
290 							DirCacheIterator.class);
291 			if (i != null) {
292 				DirCacheEntry ent = i.getDirCacheEntry();
293 				if (ent != null && compareMetadata(ent) == MetadataDiff.EQUAL
294 						&& ((ent.getFileMode().getBits()
295 								& FileMode.TYPE_MASK) != FileMode.TYPE_GITLINK)) {
296 					contentIdOffset = i.idOffset();
297 					contentIdFromPtr = ptr;
298 					return contentId = i.idBuffer();
299 				}
300 				contentIdOffset = 0;
301 			} else {
302 				contentIdOffset = 0;
303 			}
304 		}
305 		switch (mode & FileMode.TYPE_MASK) {
306 		case FileMode.TYPE_SYMLINK:
307 		case FileMode.TYPE_FILE:
308 			contentIdFromPtr = ptr;
309 			return contentId = idBufferBlob(entries[ptr]);
310 		case FileMode.TYPE_GITLINK:
311 			contentIdFromPtr = ptr;
312 			return contentId = idSubmodule(entries[ptr]);
313 		}
314 		return zeroid;
315 	}
316 
317 	/** {@inheritDoc} */
318 	@Override
319 	public boolean isWorkTree() {
320 		return true;
321 	}
322 
323 	/**
324 	 * Get submodule id for given entry.
325 	 *
326 	 * @param e
327 	 *            a {@link org.eclipse.jgit.treewalk.WorkingTreeIterator.Entry}
328 	 *            object.
329 	 * @return non-null submodule id
330 	 */
331 	protected byte[] idSubmodule(Entry e) {
332 		if (repository == null)
333 			return zeroid;
334 		File directory;
335 		try {
336 			directory = repository.getWorkTree();
337 		} catch (NoWorkTreeException nwte) {
338 			return zeroid;
339 		}
340 		return idSubmodule(directory, e);
341 	}
342 
343 	/**
344 	 * Get submodule id using the repository at the location of the entry
345 	 * relative to the directory.
346 	 *
347 	 * @param directory
348 	 *            a {@link java.io.File} object.
349 	 * @param e
350 	 *            a {@link org.eclipse.jgit.treewalk.WorkingTreeIterator.Entry}
351 	 *            object.
352 	 * @return non-null submodule id
353 	 */
354 	protected byte[] idSubmodule(File directory, Entry e) {
355 		try (Repository submoduleRepo = SubmoduleWalk.getSubmoduleRepository(
356 				directory, e.getName(),
357 				repository != null ? repository.getFS() : FS.DETECTED)) {
358 			if (submoduleRepo == null) {
359 				return zeroid;
360 			}
361 			ObjectId head = submoduleRepo.resolve(Constants.HEAD);
362 			if (head == null) {
363 				return zeroid;
364 			}
365 			byte[] id = new byte[Constants.OBJECT_ID_LENGTH];
366 			head.copyRawTo(id, 0);
367 			return id;
368 		} catch (IOException exception) {
369 			return zeroid;
370 		}
371 	}
372 
373 	private static final byte[] digits = { '0', '1', '2', '3', '4', '5', '6',
374 			'7', '8', '9' };
375 
376 	private static final byte[] hblob = Constants
377 			.encodedTypeString(Constants.OBJ_BLOB);
378 
379 	private byte[] idBufferBlob(Entry e) {
380 		try {
381 			final InputStream is = e.openInputStream();
382 			if (is == null)
383 				return zeroid;
384 			try {
385 				state.initializeReadBuffer();
386 
387 				final long len = e.getLength();
388 				InputStream filteredIs = possiblyFilteredInputStream(e, is, len,
389 						OperationType.CHECKIN_OP);
390 				return computeHash(filteredIs, canonLen);
391 			} finally {
392 				safeClose(is);
393 			}
394 		} catch (IOException err) {
395 			// Can't read the file? Don't report the failure either.
396 			return zeroid;
397 		}
398 	}
399 
400 	private InputStream possiblyFilteredInputStream(final Entry e,
401 			final InputStream is, final long len) throws IOException {
402 		return possiblyFilteredInputStream(e, is, len, null);
403 
404 	}
405 
406 	private InputStream possiblyFilteredInputStream(final Entry e,
407 			final InputStream is, final long len, OperationType opType)
408 			throws IOException {
409 		if (getCleanFilterCommand() == null
410 				&& getEolStreamType(opType) == EolStreamType.DIRECT) {
411 			canonLen = len;
412 			return is;
413 		}
414 
415 		if (len <= MAXIMUM_FILE_SIZE_TO_READ_FULLY) {
416 			ByteBuffer rawbuf = IO.readWholeStream(is, (int) len);
417 			rawbuf = filterClean(rawbuf.array(), rawbuf.limit(), opType);
418 			canonLen = rawbuf.limit();
419 			return new ByteArrayInputStream(rawbuf.array(), 0, (int) canonLen);
420 		}
421 
422 		if (getCleanFilterCommand() == null && isBinary(e)) {
423 				canonLen = len;
424 				return is;
425 			}
426 
427 		final InputStream lenIs = filterClean(e.openInputStream(),
428 				opType);
429 		try {
430 			canonLen = computeLength(lenIs);
431 		} finally {
432 			safeClose(lenIs);
433 		}
434 		return filterClean(is, opType);
435 	}
436 
437 	private static void safeClose(InputStream in) {
438 		try {
439 			in.close();
440 		} catch (IOException err2) {
441 			// Suppress any error related to closing an input
442 			// stream. We don't care, we should not have any
443 			// outstanding data to flush or anything like that.
444 		}
445 	}
446 
447 	private static boolean isBinary(Entry entry) throws IOException {
448 		InputStream in = entry.openInputStream();
449 		try {
450 			return RawText.isBinary(in);
451 		} finally {
452 			safeClose(in);
453 		}
454 	}
455 
456 	private ByteBuffer filterClean(byte[] src, int n, OperationType opType)
457 			throws IOException {
458 		InputStream in = new ByteArrayInputStream(src);
459 		try {
460 			return IO.readWholeStream(filterClean(in, opType), n);
461 		} finally {
462 			safeClose(in);
463 		}
464 	}
465 
466 	private InputStream filterClean(InputStream in) throws IOException {
467 		return filterClean(in, null);
468 	}
469 
470 	private InputStream filterClean(InputStream in, OperationType opType)
471 			throws IOException {
472 		in = handleAutoCRLF(in, opType);
473 		String filterCommand = getCleanFilterCommand();
474 		if (filterCommand != null) {
475 			if (FilterCommandRegistry.isRegistered(filterCommand)) {
476 				LocalFile buffer = new TemporaryBuffer.LocalFile(null);
477 				FilterCommand command = FilterCommandRegistry
478 						.createFilterCommand(filterCommand, repository, in,
479 								buffer);
480 				while (command.run() != -1) {
481 					// loop as long as command.run() tells there is work to do
482 				}
483 				return buffer.openInputStreamWithAutoDestroy();
484 			}
485 			FS fs = repository.getFS();
486 			ProcessBuilder filterProcessBuilder = fs.runInShell(filterCommand,
487 					new String[0]);
488 			filterProcessBuilder.directory(repository.getWorkTree());
489 			filterProcessBuilder.environment().put(Constants.GIT_DIR_KEY,
490 					repository.getDirectory().getAbsolutePath());
491 			ExecutionResult result;
492 			try {
493 				result = fs.execute(filterProcessBuilder, in);
494 			} catch (IOException | InterruptedException e) {
495 				throw new IOException(new FilterFailedException(e,
496 						filterCommand, getEntryPathString()));
497 			}
498 			int rc = result.getRc();
499 			if (rc != 0) {
500 				throw new IOException(new FilterFailedException(rc,
501 						filterCommand, getEntryPathString(),
502 						result.getStdout().toByteArray(MAX_EXCEPTION_TEXT_SIZE),
503 						RawParseUtils.decode(result.getStderr()
504 								.toByteArray(MAX_EXCEPTION_TEXT_SIZE))));
505 			}
506 			return result.getStdout().openInputStreamWithAutoDestroy();
507 		}
508 		return in;
509 	}
510 
511 	private InputStream handleAutoCRLF(InputStream in, OperationType opType)
512 			throws IOException {
513 		return EolStreamTypeUtil.wrapInputStream(in, getEolStreamType(opType));
514 	}
515 
516 	/**
517 	 * Returns the working tree options used by this iterator.
518 	 *
519 	 * @return working tree options
520 	 */
521 	public WorkingTreeOptions getOptions() {
522 		return state.options;
523 	}
524 
525 	/** {@inheritDoc} */
526 	@Override
527 	public int idOffset() {
528 		return contentIdOffset;
529 	}
530 
531 	/** {@inheritDoc} */
532 	@Override
533 	public void reset() {
534 		if (!first()) {
535 			ptr = 0;
536 			if (!eof())
537 				parseEntry();
538 		}
539 	}
540 
541 	/** {@inheritDoc} */
542 	@Override
543 	public boolean first() {
544 		return ptr == 0;
545 	}
546 
547 	/** {@inheritDoc} */
548 	@Override
549 	public boolean eof() {
550 		return ptr == entryCnt;
551 	}
552 
553 	/** {@inheritDoc} */
554 	@Override
555 	public void next(int delta) throws CorruptObjectException {
556 		ptr += delta;
557 		if (!eof()) {
558 			parseEntry();
559 		}
560 	}
561 
562 	/** {@inheritDoc} */
563 	@Override
564 	public void back(int delta) throws CorruptObjectException {
565 		ptr -= delta;
566 		parseEntry();
567 	}
568 
569 	private void parseEntry() {
570 		final Entry e = entries[ptr];
571 		mode = e.getMode().getBits();
572 
573 		final int nameLen = e.encodedNameLen;
574 		ensurePathCapacity(pathOffset + nameLen, pathOffset);
575 		System.arraycopy(e.encodedName, 0, path, pathOffset, nameLen);
576 		pathLen = pathOffset + nameLen;
577 		canonLen = -1;
578 		cleanFilterCommandHolder = null;
579 		eolStreamTypeHolder = null;
580 	}
581 
582 	/**
583 	 * Get the raw byte length of this entry.
584 	 *
585 	 * @return size of this file, in bytes.
586 	 */
587 	public long getEntryLength() {
588 		return current().getLength();
589 	}
590 
591 	/**
592 	 * Get the filtered input length of this entry
593 	 *
594 	 * @return size of the content, in bytes
595 	 * @throws java.io.IOException
596 	 */
597 	public long getEntryContentLength() throws IOException {
598 		if (canonLen == -1) {
599 			long rawLen = getEntryLength();
600 			if (rawLen == 0)
601 				canonLen = 0;
602 			InputStream is = current().openInputStream();
603 			try {
604 				// canonLen gets updated here
605 				possiblyFilteredInputStream(current(), is, current()
606 						.getLength());
607 			} finally {
608 				safeClose(is);
609 			}
610 		}
611 		return canonLen;
612 	}
613 
614 	/**
615 	 * Get the last modified time of this entry.
616 	 *
617 	 * @return last modified time of this file, in milliseconds since the epoch
618 	 *         (Jan 1, 1970 UTC).
619 	 * @deprecated use {@link #getEntryLastModifiedInstant()} instead
620 	 */
621 	@Deprecated
622 	public long getEntryLastModified() {
623 		return current().getLastModified();
624 	}
625 
626 	/**
627 	 * Get the last modified time of this entry.
628 	 *
629 	 * @return last modified time of this file
630 	 * @since 5.1.9
631 	 */
632 	public Instant getEntryLastModifiedInstant() {
633 		return current().getLastModifiedInstant();
634 	}
635 
636 	/**
637 	 * Obtain an input stream to read the file content.
638 	 * <p>
639 	 * Efficient implementations are not required. The caller will usually
640 	 * obtain the stream only once per entry, if at all.
641 	 * <p>
642 	 * The input stream should not use buffering if the implementation can avoid
643 	 * it. The caller will buffer as necessary to perform efficient block IO
644 	 * operations.
645 	 * <p>
646 	 * The caller will close the stream once complete.
647 	 *
648 	 * @return a stream to read from the file.
649 	 * @throws java.io.IOException
650 	 *             the file could not be opened for reading.
651 	 */
652 	public InputStream openEntryStream() throws IOException {
653 		InputStream rawis = current().openInputStream();
654 		if (getCleanFilterCommand() == null
655 				&& getEolStreamType() == EolStreamType.DIRECT) {
656 			return rawis;
657 		}
658 		return filterClean(rawis);
659 	}
660 
661 	/**
662 	 * Determine if the current entry path is ignored by an ignore rule.
663 	 *
664 	 * @return true if the entry was ignored by an ignore rule file.
665 	 * @throws java.io.IOException
666 	 *             a relevant ignore rule file exists but cannot be read.
667 	 */
668 	public boolean isEntryIgnored() throws IOException {
669 		return isEntryIgnored(pathLen);
670 	}
671 
672 	/**
673 	 * Determine if the entry path is ignored by an ignore rule.
674 	 *
675 	 * @param pLen
676 	 *            the length of the path in the path buffer.
677 	 * @return true if the entry is ignored by an ignore rule.
678 	 * @throws java.io.IOException
679 	 *             a relevant ignore rule file exists but cannot be read.
680 	 */
681 	protected boolean isEntryIgnored(int pLen) throws IOException {
682 		return isEntryIgnored(pLen, mode);
683 	}
684 
685 	/**
686 	 * Determine if the entry path is ignored by an ignore rule.
687 	 *
688 	 * @param pLen
689 	 *            the length of the path in the path buffer.
690 	 * @param fileMode
691 	 *            the original iterator file mode
692 	 * @return true if the entry is ignored by an ignore rule.
693 	 * @throws IOException
694 	 *             a relevant ignore rule file exists but cannot be read.
695 	 */
696 	private boolean isEntryIgnored(int pLen, int fileMode)
697 			throws IOException {
698 		// The ignore code wants path to start with a '/' if possible.
699 		// If we have the '/' in our path buffer because we are inside
700 		// a sub-directory include it in the range we convert to string.
701 		//
702 		final int pOff = 0 < pathOffset ? pathOffset - 1 : pathOffset;
703 		String pathRel = TreeWalk.pathOf(this.path, pOff, pLen);
704 		String parentRel = getParentPath(pathRel);
705 
706 		// CGit is processing .gitignore files by starting at the root of the
707 		// repository and then recursing into subdirectories. With this
708 		// approach, top-level ignored directories will be processed first which
709 		// allows to skip entire subtrees and further .gitignore-file processing
710 		// within these subtrees.
711 		//
712 		// We will follow the same approach by marking directories as "ignored"
713 		// here. This allows to have a simplified FastIgnore.checkIgnore()
714 		// implementation (both in terms of code and computational complexity):
715 		//
716 		// Without the "ignored" flag, we would have to apply the ignore-check
717 		// to a path and all of its parents always(!), to determine whether a
718 		// path is ignored directly or by one of its parent directories; with
719 		// the "ignored" flag, we know at this point that the parent directory
720 		// is definitely not ignored, thus the path can only become ignored if
721 		// there is a rule matching the path itself.
722 		if (isDirectoryIgnored(parentRel)) {
723 			return true;
724 		}
725 
726 		IgnoreNode rules = getIgnoreNode();
727 		final Boolean ignored = rules != null
728 				? rules.checkIgnored(pathRel, FileMode.TREE.equals(fileMode))
729 				: null;
730 		if (ignored != null) {
731 			return ignored.booleanValue();
732 		}
733 		return parent instanceof WorkingTreeIterator
734 				&& ((WorkingTreeIterator) parent).isEntryIgnored(pLen,
735 						fileMode);
736 	}
737 
738 	private IgnoreNode getIgnoreNode() throws IOException {
739 		if (ignoreNode instanceof PerDirectoryIgnoreNode)
740 			ignoreNode = ((PerDirectoryIgnoreNode) ignoreNode).load();
741 		return ignoreNode;
742 	}
743 
744 	/**
745 	 * Retrieves the {@link org.eclipse.jgit.attributes.AttributesNode} for the
746 	 * current entry.
747 	 *
748 	 * @return the {@link org.eclipse.jgit.attributes.AttributesNode} for the
749 	 *         current entry.
750 	 * @throws IOException
751 	 */
752 	public AttributesNode getEntryAttributesNode() throws IOException {
753 		if (attributesNode instanceof PerDirectoryAttributesNode)
754 			attributesNode = ((PerDirectoryAttributesNode) attributesNode)
755 					.load();
756 		return attributesNode;
757 	}
758 
759 	private static final Comparator<Entry> ENTRY_CMP = (Entry a,
760 			Entry b) -> Paths.compare(a.encodedName, 0, a.encodedNameLen,
761 					a.getMode().getBits(), b.encodedName, 0, b.encodedNameLen,
762 					b.getMode().getBits());
763 
764 	/**
765 	 * Constructor helper.
766 	 *
767 	 * @param list
768 	 *            files in the subtree of the work tree this iterator operates
769 	 *            on
770 	 */
771 	protected void init(Entry[] list) {
772 		// Filter out nulls, . and .. as these are not valid tree entries,
773 		// also cache the encoded forms of the path names for efficient use
774 		// later on during sorting and iteration.
775 		//
776 		entries = list;
777 		int i, o;
778 
779 		final CharsetEncoder nameEncoder = state.nameEncoder;
780 		for (i = 0, o = 0; i < entries.length; i++) {
781 			final Entry e = entries[i];
782 			if (e == null)
783 				continue;
784 			final String name = e.getName();
785 			if (".".equals(name) || "..".equals(name)) //$NON-NLS-1$ //$NON-NLS-2$
786 				continue;
787 			if (Constants.DOT_GIT.equals(name))
788 				continue;
789 			if (Constants.DOT_GIT_IGNORE.equals(name))
790 				ignoreNode = new PerDirectoryIgnoreNode(e);
791 			if (Constants.DOT_GIT_ATTRIBUTES.equals(name))
792 				attributesNode = new PerDirectoryAttributesNode(e);
793 			if (i != o)
794 				entries[o] = e;
795 			e.encodeName(nameEncoder);
796 			o++;
797 		}
798 		entryCnt = o;
799 		Arrays.sort(entries, 0, entryCnt, ENTRY_CMP);
800 
801 		contentIdFromPtr = -1;
802 		ptr = 0;
803 		if (!eof())
804 			parseEntry();
805 		else if (pathLen == 0) // see bug 445363
806 			pathLen = pathOffset;
807 	}
808 
809 	/**
810 	 * Obtain the current entry from this iterator.
811 	 *
812 	 * @return the currently selected entry.
813 	 */
814 	protected Entry current() {
815 		return entries[ptr];
816 	}
817 
818 	/**
819 	 * The result of a metadata-comparison between the current entry and a
820 	 * {@link DirCacheEntry}
821 	 */
822 	public enum MetadataDiff {
823 		/**
824 		 * The entries are equal by metaData (mode, length,
825 		 * modification-timestamp) or the <code>assumeValid</code> attribute of
826 		 * the index entry is set
827 		 */
828 		EQUAL,
829 
830 		/**
831 		 * The entries are not equal by metaData (mode, length) or the
832 		 * <code>isUpdateNeeded</code> attribute of the index entry is set
833 		 */
834 		DIFFER_BY_METADATA,
835 
836 		/** index entry is smudged - can't use that entry for comparison */
837 		SMUDGED,
838 
839 		/**
840 		 * The entries are equal by metaData (mode, length) but differ by
841 		 * modification-timestamp.
842 		 */
843 		DIFFER_BY_TIMESTAMP
844 	}
845 
846 	/**
847 	 * Is the file mode of the current entry different than the given raw mode?
848 	 *
849 	 * @param rawMode
850 	 *            an int.
851 	 * @return true if different, false otherwise
852 	 */
853 	public boolean isModeDifferent(int rawMode) {
854 		// Determine difference in mode-bits of file and index-entry. In the
855 		// bitwise presentation of modeDiff we'll have a '1' when the two modes
856 		// differ at this position.
857 		int modeDiff = getEntryRawMode() ^ rawMode;
858 
859 		if (modeDiff == 0)
860 			return false;
861 
862 		// Do not rely on filemode differences in case of symbolic links
863 		if (getOptions().getSymLinks() == SymLinks.FALSE)
864 			if (FileMode.SYMLINK.equals(rawMode))
865 				return false;
866 
867 		// Ignore the executable file bits if WorkingTreeOptions tell me to
868 		// do so. Ignoring is done by setting the bits representing a
869 		// EXECUTABLE_FILE to '0' in modeDiff
870 		if (!state.options.isFileMode())
871 			modeDiff &= ~FileMode.EXECUTABLE_FILE.getBits();
872 		return modeDiff != 0;
873 	}
874 
875 	/**
876 	 * Compare the metadata (mode, length, modification-timestamp) of the
877 	 * current entry and a {@link org.eclipse.jgit.dircache.DirCacheEntry}
878 	 *
879 	 * @param entry
880 	 *            the {@link org.eclipse.jgit.dircache.DirCacheEntry} to compare
881 	 *            with
882 	 * @return a
883 	 *         {@link org.eclipse.jgit.treewalk.WorkingTreeIterator.MetadataDiff}
884 	 *         which tells whether and how the entries metadata differ
885 	 */
886 	public MetadataDiff compareMetadata(DirCacheEntry entry) {
887 		if (entry.isAssumeValid())
888 			return MetadataDiff.EQUAL;
889 
890 		if (entry.isUpdateNeeded())
891 			return MetadataDiff.DIFFER_BY_METADATA;
892 
893 		if (isModeDifferent(entry.getRawMode()))
894 			return MetadataDiff.DIFFER_BY_METADATA;
895 
896 		// Don't check for length or lastmodified on folders
897 		int type = mode & FileMode.TYPE_MASK;
898 		if (type == FileMode.TYPE_TREE || type == FileMode.TYPE_GITLINK)
899 			return MetadataDiff.EQUAL;
900 
901 		if (!entry.isSmudged() && entry.getLength() != (int) getEntryLength())
902 			return MetadataDiff.DIFFER_BY_METADATA;
903 
904 		// Cache and file timestamps may differ in resolution. Therefore don't
905 		// compare instants directly but use a comparator that compares only
906 		// up to the lower apparent resolution of either timestamp.
907 		//
908 		// If core.checkstat is set to "minimal", compare only the seconds part.
909 		Instant cacheLastModified = entry.getLastModifiedInstant();
910 		Instant fileLastModified = getEntryLastModifiedInstant();
911 		if (timestampComparator.compare(cacheLastModified, fileLastModified,
912 				getOptions().getCheckStat() == CheckStat.MINIMAL) != 0) {
913 			return MetadataDiff.DIFFER_BY_TIMESTAMP;
914 		}
915 
916 		if (entry.isSmudged()) {
917 			return MetadataDiff.SMUDGED;
918 		}
919 		// The file is clean when when comparing timestamps
920 		return MetadataDiff.EQUAL;
921 	}
922 
923 	/**
924 	 * Checks whether this entry differs from a given entry from the
925 	 * {@link org.eclipse.jgit.dircache.DirCache}.
926 	 *
927 	 * File status information is used and if status is same we consider the
928 	 * file identical to the state in the working directory. Native git uses
929 	 * more stat fields than we have accessible in Java.
930 	 *
931 	 * @param entry
932 	 *            the entry from the dircache we want to compare against
933 	 * @param forceContentCheck
934 	 *            True if the actual file content should be checked if
935 	 *            modification time differs.
936 	 * @param reader
937 	 *            access to repository objects if necessary. Should not be null.
938 	 * @return true if content is most likely different.
939 	 * @throws java.io.IOException
940 	 * @since 3.3
941 	 */
942 	public boolean isModified(DirCacheEntry entry, boolean forceContentCheck,
943 			ObjectReader reader) throws IOException {
944 		if (entry == null)
945 			return !FileMode.MISSING.equals(getEntryFileMode());
946 		MetadataDiff diff = compareMetadata(entry);
947 		switch (diff) {
948 		case DIFFER_BY_TIMESTAMP:
949 			if (forceContentCheck) {
950 				// But we are told to look at content even though timestamps
951 				// tell us about modification
952 				return contentCheck(entry, reader);
953 			}
954 			// We are told to assume a modification if timestamps differs
955 			return true;
956 		case SMUDGED:
957 			// The file is clean by timestamps but the entry was smudged.
958 			// Lets do a content check
959 			return contentCheck(entry, reader);
960 		case EQUAL:
961 			if (mode == FileMode.SYMLINK.getBits()) {
962 				return contentCheck(entry, reader);
963 			}
964 			return false;
965 		case DIFFER_BY_METADATA:
966 			if (mode == FileMode.TREE.getBits()
967 					&& entry.getFileMode().equals(FileMode.GITLINK)) {
968 				byte[] idBuffer = idBuffer();
969 				int idOffset = idOffset();
970 				if (entry.getObjectId().compareTo(idBuffer, idOffset) == 0) {
971 					return true;
972 				} else if (ObjectId.zeroId().compareTo(idBuffer,
973 						idOffset) == 0) {
974 					return new File(repository.getWorkTree(),
975 							entry.getPathString()).list().length > 0;
976 				}
977 				return false;
978 			} else if (mode == FileMode.SYMLINK.getBits())
979 				return contentCheck(entry, reader);
980 			return true;
981 		default:
982 			throw new IllegalStateException(MessageFormat.format(
983 					JGitText.get().unexpectedCompareResult, diff.name()));
984 		}
985 	}
986 
987 	/**
988 	 * Get the file mode to use for the current entry when it is to be updated
989 	 * in the index.
990 	 *
991 	 * @param indexIter
992 	 *            {@link org.eclipse.jgit.dircache.DirCacheIterator} positioned
993 	 *            at the same entry as this iterator or null if no
994 	 *            {@link org.eclipse.jgit.dircache.DirCacheIterator} is
995 	 *            available at this iterator's current entry
996 	 * @return index file mode
997 	 */
998 	public FileMode getIndexFileMode(DirCacheIterator indexIter) {
999 		final FileMode wtMode = getEntryFileMode();
1000 		if (indexIter == null) {
1001 			return wtMode;
1002 		}
1003 		final FileMode iMode = indexIter.getEntryFileMode();
1004 		if (getOptions().isFileMode() && iMode != FileMode.GITLINK && iMode != FileMode.TREE) {
1005 			return wtMode;
1006 		}
1007 		if (!getOptions().isFileMode()) {
1008 			if (FileMode.REGULAR_FILE == wtMode
1009 					&& FileMode.EXECUTABLE_FILE == iMode) {
1010 				return iMode;
1011 			}
1012 			if (FileMode.EXECUTABLE_FILE == wtMode
1013 					&& FileMode.REGULAR_FILE == iMode) {
1014 				return iMode;
1015 			}
1016 		}
1017 		if (FileMode.GITLINK == iMode
1018 				&& FileMode.TREE == wtMode && !getOptions().isDirNoGitLinks()) {
1019 			return iMode;
1020 		}
1021 		if (FileMode.TREE == iMode
1022 				&& FileMode.GITLINK == wtMode) {
1023 			return iMode;
1024 		}
1025 		return wtMode;
1026 	}
1027 
1028 	/**
1029 	 * Compares the entries content with the content in the filesystem.
1030 	 * Unsmudges the entry when it is detected that it is clean.
1031 	 *
1032 	 * @param entry
1033 	 *            the entry to be checked
1034 	 * @param reader
1035 	 *            acccess to repository data if necessary
1036 	 * @return <code>true</code> if the content doesn't match,
1037 	 *         <code>false</code> if it matches
1038 	 * @throws IOException
1039 	 */
1040 	private boolean contentCheck(DirCacheEntry entry, ObjectReader reader)
1041 			throws IOException {
1042 		if (getEntryObjectId().equals(entry.getObjectId())) {
1043 			// Content has not changed
1044 
1045 			// We know the entry can't be racily clean because it's still clean.
1046 			// Therefore we unsmudge the entry!
1047 			// If by any chance we now unsmudge although we are still in the
1048 			// same time-slot as the last modification to the index file the
1049 			// next index write operation will smudge again.
1050 			// Caution: we are unsmudging just by setting the length of the
1051 			// in-memory entry object. It's the callers task to detect that we
1052 			// have modified the entry and to persist the modified index.
1053 			entry.setLength((int) getEntryLength());
1054 
1055 			return false;
1056 		}
1057 		if (mode == FileMode.SYMLINK.getBits()) {
1058 			return !new File(readSymlinkTarget(current())).equals(
1059 					new File(readContentAsNormalizedString(entry, reader)));
1060 		}
1061 		// Content differs: that's a real change
1062 		return true;
1063 	}
1064 
1065 	private static String readContentAsNormalizedString(DirCacheEntry entry,
1066 			ObjectReader reader) throws MissingObjectException, IOException {
1067 		ObjectLoader open = reader.open(entry.getObjectId());
1068 		byte[] cachedBytes = open.getCachedBytes();
1069 		return FS.detect().normalize(RawParseUtils.decode(cachedBytes));
1070 	}
1071 
1072 	/**
1073 	 * Reads the target of a symlink as a string. This default implementation
1074 	 * fully reads the entry's input stream and converts it to a normalized
1075 	 * string. Subclasses may override to provide more specialized
1076 	 * implementations.
1077 	 *
1078 	 * @param entry
1079 	 *            to read
1080 	 * @return the entry's content as a normalized string
1081 	 * @throws java.io.IOException
1082 	 *             if the entry cannot be read or does not denote a symlink
1083 	 * @since 4.6
1084 	 */
1085 	protected String readSymlinkTarget(Entry entry) throws IOException {
1086 		if (!entry.getMode().equals(FileMode.SYMLINK)) {
1087 			throw new java.nio.file.NotLinkException(entry.getName());
1088 		}
1089 		long length = entry.getLength();
1090 		byte[] content = new byte[(int) length];
1091 		try (InputStream is = entry.openInputStream()) {
1092 			int bytesRead = IO.readFully(is, content, 0);
1093 			return FS.detect()
1094 					.normalize(RawParseUtils.decode(content, 0, bytesRead));
1095 		}
1096 	}
1097 
1098 	private static long computeLength(InputStream in) throws IOException {
1099 		// Since we only care about the length, use skip. The stream
1100 		// may be able to more efficiently wade through its data.
1101 		//
1102 		long length = 0;
1103 		for (;;) {
1104 			long n = in.skip(1 << 20);
1105 			if (n <= 0)
1106 				break;
1107 			length += n;
1108 		}
1109 		return length;
1110 	}
1111 
1112 	private byte[] computeHash(InputStream in, long length) throws IOException {
1113 		SHA1 contentDigest = SHA1.newInstance();
1114 		final byte[] contentReadBuffer = state.contentReadBuffer;
1115 
1116 		contentDigest.update(hblob);
1117 		contentDigest.update((byte) ' ');
1118 
1119 		long sz = length;
1120 		if (sz == 0) {
1121 			contentDigest.update((byte) '0');
1122 		} else {
1123 			final int bufn = contentReadBuffer.length;
1124 			int p = bufn;
1125 			do {
1126 				contentReadBuffer[--p] = digits[(int) (sz % 10)];
1127 				sz /= 10;
1128 			} while (sz > 0);
1129 			contentDigest.update(contentReadBuffer, p, bufn - p);
1130 		}
1131 		contentDigest.update((byte) 0);
1132 
1133 		for (;;) {
1134 			final int r = in.read(contentReadBuffer);
1135 			if (r <= 0)
1136 				break;
1137 			contentDigest.update(contentReadBuffer, 0, r);
1138 			sz += r;
1139 		}
1140 		if (sz != length)
1141 			return zeroid;
1142 		return contentDigest.digest();
1143 	}
1144 
1145 	/**
1146 	 * A single entry within a working directory tree.
1147 	 *
1148 	 * @since 5.0
1149 	 */
1150 	public abstract static class Entry {
1151 		byte[] encodedName;
1152 
1153 		int encodedNameLen;
1154 
1155 		void encodeName(CharsetEncoder enc) {
1156 			final ByteBuffer b;
1157 			try {
1158 				b = enc.encode(CharBuffer.wrap(getName()));
1159 			} catch (CharacterCodingException e) {
1160 				// This should so never happen.
1161 				throw new RuntimeException(MessageFormat.format(
1162 						JGitText.get().unencodeableFile, getName()), e);
1163 			}
1164 
1165 			encodedNameLen = b.limit();
1166 			if (b.hasArray() && b.arrayOffset() == 0)
1167 				encodedName = b.array();
1168 			else
1169 				b.get(encodedName = new byte[encodedNameLen]);
1170 		}
1171 
1172 		@Override
1173 		public String toString() {
1174 			return getMode().toString() + " " + getName(); //$NON-NLS-1$
1175 		}
1176 
1177 		/**
1178 		 * Get the type of this entry.
1179 		 * <p>
1180 		 * <b>Note: Efficient implementation required.</b>
1181 		 * <p>
1182 		 * The implementation of this method must be efficient. If a subclass
1183 		 * needs to compute the value they should cache the reference within an
1184 		 * instance member instead.
1185 		 *
1186 		 * @return a file mode constant from {@link FileMode}.
1187 		 */
1188 		public abstract FileMode getMode();
1189 
1190 		/**
1191 		 * Get the byte length of this entry.
1192 		 * <p>
1193 		 * <b>Note: Efficient implementation required.</b>
1194 		 * <p>
1195 		 * The implementation of this method must be efficient. If a subclass
1196 		 * needs to compute the value they should cache the reference within an
1197 		 * instance member instead.
1198 		 *
1199 		 * @return size of this file, in bytes.
1200 		 */
1201 		public abstract long getLength();
1202 
1203 		/**
1204 		 * Get the last modified time of this entry.
1205 		 * <p>
1206 		 * <b>Note: Efficient implementation required.</b>
1207 		 * <p>
1208 		 * The implementation of this method must be efficient. If a subclass
1209 		 * needs to compute the value they should cache the reference within an
1210 		 * instance member instead.
1211 		 *
1212 		 * @return time since the epoch (in ms) of the last change.
1213 		 * @deprecated use {@link #getLastModifiedInstant()} instead
1214 		 */
1215 		@Deprecated
1216 		public abstract long getLastModified();
1217 
1218 		/**
1219 		 * Get the last modified time of this entry.
1220 		 * <p>
1221 		 * <b>Note: Efficient implementation required.</b>
1222 		 * <p>
1223 		 * The implementation of this method must be efficient. If a subclass
1224 		 * needs to compute the value they should cache the reference within an
1225 		 * instance member instead.
1226 		 *
1227 		 * @return time of the last change.
1228 		 * @since 5.1.9
1229 		 */
1230 		public abstract Instant getLastModifiedInstant();
1231 
1232 		/**
1233 		 * Get the name of this entry within its directory.
1234 		 * <p>
1235 		 * Efficient implementations are not required. The caller will obtain
1236 		 * the name only once and cache it once obtained.
1237 		 *
1238 		 * @return name of the entry.
1239 		 */
1240 		public abstract String getName();
1241 
1242 		/**
1243 		 * Obtain an input stream to read the file content.
1244 		 * <p>
1245 		 * Efficient implementations are not required. The caller will usually
1246 		 * obtain the stream only once per entry, if at all.
1247 		 * <p>
1248 		 * The input stream should not use buffering if the implementation can
1249 		 * avoid it. The caller will buffer as necessary to perform efficient
1250 		 * block IO operations.
1251 		 * <p>
1252 		 * The caller will close the stream once complete.
1253 		 *
1254 		 * @return a stream to read from the file.
1255 		 * @throws IOException
1256 		 *             the file could not be opened for reading.
1257 		 */
1258 		public abstract InputStream openInputStream() throws IOException;
1259 	}
1260 
1261 	/** Magic type indicating we know rules exist, but they aren't loaded. */
1262 	private static class PerDirectoryIgnoreNode extends IgnoreNode {
1263 		final Entry entry;
1264 
1265 		PerDirectoryIgnoreNode(Entry entry) {
1266 			super(Collections.<FastIgnoreRule> emptyList());
1267 			this.entry = entry;
1268 		}
1269 
1270 		IgnoreNode load() throws IOException {
1271 			IgnoreNode r = new IgnoreNode();
1272 			try (InputStream in = entry.openInputStream()) {
1273 				r.parse(in);
1274 			}
1275 			return r.getRules().isEmpty() ? null : r;
1276 		}
1277 	}
1278 
1279 	/** Magic type indicating there may be rules for the top level. */
1280 	private static class RootIgnoreNode extends PerDirectoryIgnoreNode {
1281 		final Repository repository;
1282 
1283 		RootIgnoreNode(Entry entry, Repository repository) {
1284 			super(entry);
1285 			this.repository = repository;
1286 		}
1287 
1288 		@Override
1289 		IgnoreNode load() throws IOException {
1290 			IgnoreNode r;
1291 			if (entry != null) {
1292 				r = super.load();
1293 				if (r == null)
1294 					r = new IgnoreNode();
1295 			} else {
1296 				r = new IgnoreNode();
1297 			}
1298 
1299 			FS fs = repository.getFS();
1300 			String path = repository.getConfig().get(CoreConfig.KEY)
1301 					.getExcludesFile();
1302 			if (path != null) {
1303 				File excludesfile;
1304 				if (path.startsWith("~/")) //$NON-NLS-1$
1305 					excludesfile = fs.resolve(fs.userHome(), path.substring(2));
1306 				else
1307 					excludesfile = fs.resolve(null, path);
1308 				loadRulesFromFile(r, excludesfile);
1309 			}
1310 
1311 			File exclude = fs.resolve(repository.getDirectory(),
1312 					Constants.INFO_EXCLUDE);
1313 			loadRulesFromFile(r, exclude);
1314 
1315 			return r.getRules().isEmpty() ? null : r;
1316 		}
1317 
1318 		private static void loadRulesFromFile(IgnoreNode r, File exclude)
1319 				throws FileNotFoundException, IOException {
1320 			if (FS.DETECTED.exists(exclude)) {
1321 				try (FileInputStream in = new FileInputStream(exclude)) {
1322 					r.parse(in);
1323 				}
1324 			}
1325 		}
1326 	}
1327 
1328 	/** Magic type indicating we know rules exist, but they aren't loaded. */
1329 	private static class PerDirectoryAttributesNode extends AttributesNode {
1330 		final Entry entry;
1331 
1332 		PerDirectoryAttributesNode(Entry entry) {
1333 			super(Collections.<AttributesRule> emptyList());
1334 			this.entry = entry;
1335 		}
1336 
1337 		AttributesNode load() throws IOException {
1338 			AttributesNode r = new AttributesNode();
1339 			try (InputStream in = entry.openInputStream()) {
1340 				r.parse(in);
1341 			}
1342 			return r.getRules().isEmpty() ? null : r;
1343 		}
1344 	}
1345 
1346 
1347 	private static final class IteratorState {
1348 		/** Options used to process the working tree. */
1349 		final WorkingTreeOptions options;
1350 
1351 		/** File name character encoder. */
1352 		final CharsetEncoder nameEncoder;
1353 
1354 		/** Buffer used to perform {@link #contentId} computations. */
1355 		byte[] contentReadBuffer;
1356 
1357 		/** TreeWalk with a (supposedly) matching DirCacheIterator. */
1358 		TreeWalk walk;
1359 
1360 		/** Position of the matching {@link DirCacheIterator}. */
1361 		int dirCacheTree = -1;
1362 
1363 		/** Whether the iterator shall walk ignored directories. */
1364 		boolean walkIgnored = false;
1365 
1366 		final Map<String, Boolean> directoryToIgnored = new HashMap<>();
1367 
1368 		IteratorState(WorkingTreeOptions options) {
1369 			this.options = options;
1370 			this.nameEncoder = UTF_8.newEncoder();
1371 		}
1372 
1373 		void initializeReadBuffer() {
1374 			if (contentReadBuffer == null) {
1375 				contentReadBuffer = new byte[BUFFER_SIZE];
1376 			}
1377 		}
1378 	}
1379 
1380 	/**
1381 	 * Get the clean filter command for the current entry.
1382 	 *
1383 	 * @return the clean filter command for the current entry or
1384 	 *         <code>null</code> if no such command is defined
1385 	 * @throws java.io.IOException
1386 	 * @since 4.2
1387 	 */
1388 	public String getCleanFilterCommand() throws IOException {
1389 		if (cleanFilterCommandHolder == null) {
1390 			String cmd = null;
1391 			if (state.walk != null) {
1392 				cmd = state.walk
1393 						.getFilterCommand(Constants.ATTR_FILTER_TYPE_CLEAN);
1394 			}
1395 			cleanFilterCommandHolder = new Holder<>(cmd);
1396 		}
1397 		return cleanFilterCommandHolder.get();
1398 	}
1399 
1400 	/**
1401 	 * Get the eol stream type for the current entry.
1402 	 *
1403 	 * @return the eol stream type for the current entry or <code>null</code> if
1404 	 *         it cannot be determined. When state or state.walk is null or the
1405 	 *         {@link org.eclipse.jgit.treewalk.TreeWalk} is not based on a
1406 	 *         {@link org.eclipse.jgit.lib.Repository} then null is returned.
1407 	 * @throws java.io.IOException
1408 	 * @since 4.3
1409 	 */
1410 	public EolStreamType getEolStreamType() throws IOException {
1411 		return getEolStreamType(null);
1412 	}
1413 
1414 	/**
1415 	 * @param opType
1416 	 *            The operationtype (checkin/checkout) which should be used
1417 	 * @return the eol stream type for the current entry or <code>null</code> if
1418 	 *         it cannot be determined. When state or state.walk is null or the
1419 	 *         {@link TreeWalk} is not based on a {@link Repository} then null
1420 	 *         is returned.
1421 	 * @throws IOException
1422 	 */
1423 	private EolStreamType getEolStreamType(OperationType opType)
1424 			throws IOException {
1425 		if (eolStreamTypeHolder == null) {
1426 			EolStreamType type = null;
1427 			if (state.walk != null) {
1428 				type = state.walk.getEolStreamType(opType);
1429 				OperationType operationType = opType != null ? opType
1430 						: state.walk.getOperationType();
1431 				if (OperationType.CHECKIN_OP.equals(operationType)
1432 						&& EolStreamType.AUTO_LF.equals(type)
1433 						&& hasCrLfInIndex(getDirCacheIterator())) {
1434 					// If text=auto (or core.autocrlf=true) and the file has
1435 					// already been committed with CR/LF, then don't convert.
1436 					type = EolStreamType.DIRECT;
1437 				}
1438 			} else {
1439 				switch (getOptions().getAutoCRLF()) {
1440 				case FALSE:
1441 					type = EolStreamType.DIRECT;
1442 					break;
1443 				case TRUE:
1444 				case INPUT:
1445 					type = EolStreamType.AUTO_LF;
1446 					break;
1447 				}
1448 			}
1449 			eolStreamTypeHolder = new Holder<>(type);
1450 		}
1451 		return eolStreamTypeHolder.get();
1452 	}
1453 
1454 	/**
1455 	 * Determines whether the file was committed un-normalized. If the iterator
1456 	 * points to a conflict entry, checks the "ours" version.
1457 	 *
1458 	 * @param dirCache
1459 	 *            iterator pointing to the current entry for the file in the
1460 	 *            index
1461 	 * @return {@code true} if the file in the index is not binary and has CR/LF
1462 	 *         line endings, {@code false} otherwise
1463 	 */
1464 	private boolean hasCrLfInIndex(DirCacheIterator dirCache) {
1465 		if (dirCache == null) {
1466 			return false;
1467 		}
1468 		// Read blob from index and check for CR/LF-delimited text.
1469 		DirCacheEntry entry = dirCache.getDirCacheEntry();
1470 		if (FileMode.REGULAR_FILE.equals(entry.getFileMode())) {
1471 			ObjectId blobId = entry.getObjectId();
1472 			if (entry.getStage() > 0
1473 					&& entry.getStage() != DirCacheEntry.STAGE_2) {
1474 				blobId = null;
1475 				// Merge conflict: check ours (stage 2)
1476 				byte[] name = entry.getRawPath();
1477 				int i = 0;
1478 				while (!dirCache.eof()) {
1479 					dirCache.next(1);
1480 					i++;
1481 					entry = dirCache.getDirCacheEntry();
1482 					if (entry == null
1483 							|| !Arrays.equals(name, entry.getRawPath())) {
1484 						break;
1485 					}
1486 					if (entry.getStage() == DirCacheEntry.STAGE_2) {
1487 						blobId = entry.getObjectId();
1488 						break;
1489 					}
1490 				}
1491 				dirCache.back(i);
1492 			}
1493 			if (blobId != null) {
1494 				try (ObjectReader reader = repository.newObjectReader()) {
1495 					ObjectLoader loader = reader.open(blobId,
1496 							Constants.OBJ_BLOB);
1497 					try {
1498 						return RawText.isCrLfText(loader.getCachedBytes());
1499 					} catch (LargeObjectException e) {
1500 						try (InputStream in = loader.openStream()) {
1501 							return RawText.isCrLfText(in);
1502 						}
1503 					}
1504 				} catch (IOException e) {
1505 					// Ignore and return false below
1506 				}
1507 			}
1508 		}
1509 		return false;
1510 	}
1511 
1512 	private boolean isDirectoryIgnored(String pathRel) throws IOException {
1513 		final int pOff = 0 < pathOffset ? pathOffset - 1 : pathOffset;
1514 		final String base = TreeWalk.pathOf(this.path, 0, pOff);
1515 		final String pathAbs = concatPath(base, pathRel);
1516 		return isDirectoryIgnored(pathRel, pathAbs);
1517 	}
1518 
1519 	private boolean isDirectoryIgnored(String pathRel, String pathAbs)
1520 			throws IOException {
1521 		assert pathRel.length() == 0 || (pathRel.charAt(0) != '/'
1522 				&& pathRel.charAt(pathRel.length() - 1) != '/');
1523 		assert pathAbs.length() == 0 || (pathAbs.charAt(0) != '/'
1524 				&& pathAbs.charAt(pathAbs.length() - 1) != '/');
1525 		assert pathAbs.endsWith(pathRel);
1526 
1527 		Boolean ignored = state.directoryToIgnored.get(pathAbs);
1528 		if (ignored != null) {
1529 			return ignored.booleanValue();
1530 		}
1531 
1532 		final String parentRel = getParentPath(pathRel);
1533 		if (parentRel != null && isDirectoryIgnored(parentRel)) {
1534 			state.directoryToIgnored.put(pathAbs, Boolean.TRUE);
1535 			return true;
1536 		}
1537 
1538 		final IgnoreNode node = getIgnoreNode();
1539 		for (String p = pathRel; node != null
1540 				&& !"".equals(p); p = getParentPath(p)) { //$NON-NLS-1$
1541 			ignored = node.checkIgnored(p, true);
1542 			if (ignored != null) {
1543 				state.directoryToIgnored.put(pathAbs, ignored);
1544 				return ignored.booleanValue();
1545 			}
1546 		}
1547 
1548 		if (!(this.parent instanceof WorkingTreeIterator)) {
1549 			state.directoryToIgnored.put(pathAbs, Boolean.FALSE);
1550 			return false;
1551 		}
1552 
1553 		final WorkingTreeIterator/eclipse/jgit/treewalk/WorkingTreeIterator.html#WorkingTreeIterator">WorkingTreeIterator wtParent = (WorkingTreeIterator) this.parent;
1554 		final String parentRelPath = concatPath(
1555 				TreeWalk.pathOf(this.path, wtParent.pathOffset, pathOffset - 1),
1556 				pathRel);
1557 		assert concatPath(TreeWalk.pathOf(wtParent.path, 0,
1558 				Math.max(0, wtParent.pathOffset - 1)), parentRelPath)
1559 						.equals(pathAbs);
1560 		return wtParent.isDirectoryIgnored(parentRelPath, pathAbs);
1561 	}
1562 
1563 	private static String getParentPath(String path) {
1564 		final int slashIndex = path.lastIndexOf('/', path.length() - 2);
1565 		if (slashIndex > 0) {
1566 			return path.substring(path.charAt(0) == '/' ? 1 : 0, slashIndex);
1567 		}
1568 		return path.length() > 0 ? "" : null; //$NON-NLS-1$
1569 	}
1570 
1571 	private static String concatPath(String p1, String p2) {
1572 		return p1 + (p1.length() > 0 && p2.length() > 0 ? "/" : "") + p2; //$NON-NLS-1$ //$NON-NLS-2$
1573 	}
1574 }