View Javadoc
1   /*
2    * Copyright (C) 2008, 2017, Google Inc.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.treewalk;
45  
46  import static java.nio.charset.StandardCharsets.UTF_8;
47  import static org.junit.Assert.assertEquals;
48  import static org.junit.Assert.assertFalse;
49  import static org.junit.Assert.assertNotNull;
50  import static org.junit.Assert.assertTrue;
51  import static org.junit.Assume.assumeNoException;
52  
53  import java.io.File;
54  import java.io.IOException;
55  import java.nio.file.InvalidPathException;
56  import java.security.MessageDigest;
57  import java.time.Instant;
58  
59  import org.eclipse.jgit.api.Git;
60  import org.eclipse.jgit.api.ResetCommand.ResetType;
61  import org.eclipse.jgit.dircache.DirCache;
62  import org.eclipse.jgit.dircache.DirCacheCheckout;
63  import org.eclipse.jgit.dircache.DirCacheEditor;
64  import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
65  import org.eclipse.jgit.dircache.DirCacheEntry;
66  import org.eclipse.jgit.dircache.DirCacheIterator;
67  import org.eclipse.jgit.errors.CorruptObjectException;
68  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
69  import org.eclipse.jgit.errors.MissingObjectException;
70  import org.eclipse.jgit.junit.JGitTestUtil;
71  import org.eclipse.jgit.junit.RepositoryTestCase;
72  import org.eclipse.jgit.lib.ConfigConstants;
73  import org.eclipse.jgit.lib.Constants;
74  import org.eclipse.jgit.lib.FileMode;
75  import org.eclipse.jgit.lib.ObjectId;
76  import org.eclipse.jgit.lib.ObjectInserter;
77  import org.eclipse.jgit.lib.ObjectReader;
78  import org.eclipse.jgit.lib.Repository;
79  import org.eclipse.jgit.revwalk.RevCommit;
80  import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
81  import org.eclipse.jgit.treewalk.WorkingTreeIterator.MetadataDiff;
82  import org.eclipse.jgit.treewalk.filter.PathFilter;
83  import org.eclipse.jgit.util.FS;
84  import org.eclipse.jgit.util.FileUtils;
85  import org.eclipse.jgit.util.RawParseUtils;
86  import org.junit.Before;
87  import org.junit.Test;
88  
89  public class FileTreeIteratorTest extends RepositoryTestCase {
90  	private final String[] paths = { "a,", "a,b", "a/b", "a0b" };
91  
92  	private Instant[] mtime;
93  
94  	@Override
95  	@Before
96  	public void setUp() throws Exception {
97  		super.setUp();
98  
99  		// We build the entries backwards so that on POSIX systems we
100 		// are likely to get the entries in the trash directory in the
101 		// opposite order of what they should be in for the iteration.
102 		// This should stress the sorting code better than doing it in
103 		// the correct order.
104 		//
105 		mtime = new Instant[paths.length];
106 		for (int i = paths.length - 1; i >= 0; i--) {
107 			final String s = paths[i];
108 			writeTrashFile(s, s);
109 			mtime[i] = db.getFS().lastModifiedInstant(new File(trash, s));
110 		}
111 	}
112 
113 	@Test
114 	public void testGetEntryContentLength() throws Exception {
115 		final FileTreeIterator fti = new FileTreeIterator(db);
116 		fti.next(1);
117 		assertEquals(3, fti.getEntryContentLength());
118 		fti.back(1);
119 		assertEquals(2, fti.getEntryContentLength());
120 		fti.next(1);
121 		assertEquals(3, fti.getEntryContentLength());
122 		fti.reset();
123 		assertEquals(2, fti.getEntryContentLength());
124 	}
125 
126 	@Test
127 	public void testEmptyIfRootIsFile() throws Exception {
128 		final File r = new File(trash, paths[0]);
129 		assertTrue(r.isFile());
130 		final FileTreeIterator fti = new FileTreeIterator(r, db.getFS(),
131 				db.getConfig().get(WorkingTreeOptions.KEY));
132 		assertTrue(fti.first());
133 		assertTrue(fti.eof());
134 	}
135 
136 	@Test
137 	public void testEmptyIfRootDoesNotExist() throws Exception {
138 		final File r = new File(trash, "not-existing-file");
139 		assertFalse(r.exists());
140 		final FileTreeIterator fti = new FileTreeIterator(r, db.getFS(),
141 				db.getConfig().get(WorkingTreeOptions.KEY));
142 		assertTrue(fti.first());
143 		assertTrue(fti.eof());
144 	}
145 
146 	@Test
147 	public void testEmptyIfRootIsEmpty() throws Exception {
148 		final File r = new File(trash, "not-existing-file");
149 		assertFalse(r.exists());
150 		FileUtils.mkdir(r);
151 
152 		final FileTreeIterator fti = new FileTreeIterator(r, db.getFS(),
153 				db.getConfig().get(WorkingTreeOptions.KEY));
154 		assertTrue(fti.first());
155 		assertTrue(fti.eof());
156 	}
157 
158 	@Test
159 	public void testEmptyIteratorOnEmptyDirectory() throws Exception {
160 		String nonExistingFileName = "not-existing-file";
161 		final File r = new File(trash, nonExistingFileName);
162 		assertFalse(r.exists());
163 		FileUtils.mkdir(r);
164 
165 		final FileTreeIterator parent = new FileTreeIterator(db);
166 
167 		while (!parent.getEntryPathString().equals(nonExistingFileName))
168 			parent.next(1);
169 
170 		final FileTreeIterator childIter = new FileTreeIterator(parent, r,
171 				db.getFS());
172 		assertTrue(childIter.first());
173 		assertTrue(childIter.eof());
174 
175 		String parentPath = parent.getEntryPathString();
176 		assertEquals(nonExistingFileName, parentPath);
177 
178 		// must be "not-existing-file/", but getEntryPathString() was broken by
179 		// 445363 too
180 		String childPath = childIter.getEntryPathString();
181 
182 		// in bug 445363 the iterator wrote garbage to the parent "path" field
183 		EmptyTreeIterator e = childIter.createEmptyTreeIterator();
184 		assertNotNull(e);
185 
186 		// check if parent path is not overridden by empty iterator (bug 445363)
187 		// due bug 445363 this was "/ot-existing-file" instead of
188 		// "not-existing-file"
189 		assertEquals(parentPath, parent.getEntryPathString());
190 		assertEquals(parentPath + "/", childPath);
191 		assertEquals(parentPath + "/", childIter.getEntryPathString());
192 		assertEquals(childPath + "/", e.getEntryPathString());
193 	}
194 
195 	@Test
196 	public void testSimpleIterate() throws Exception {
197 		final FileTreeIterator top = new FileTreeIterator(trash, db.getFS(),
198 				db.getConfig().get(WorkingTreeOptions.KEY));
199 
200 		assertTrue(top.first());
201 		assertFalse(top.eof());
202 		assertEquals(FileMode.REGULAR_FILE.getBits(), top.mode);
203 		assertEquals(paths[0], nameOf(top));
204 		assertEquals(paths[0].length(), top.getEntryLength());
205 		assertEquals(mtime[0], top.getEntryLastModifiedInstant());
206 
207 		top.next(1);
208 		assertFalse(top.first());
209 		assertFalse(top.eof());
210 		assertEquals(FileMode.REGULAR_FILE.getBits(), top.mode);
211 		assertEquals(paths[1], nameOf(top));
212 		assertEquals(paths[1].length(), top.getEntryLength());
213 		assertEquals(mtime[1], top.getEntryLastModifiedInstant());
214 
215 		top.next(1);
216 		assertFalse(top.first());
217 		assertFalse(top.eof());
218 		assertEquals(FileMode.TREE.getBits(), top.mode);
219 
220 		try (ObjectReader reader = db.newObjectReader()) {
221 			final AbstractTreeIterator sub = top.createSubtreeIterator(reader);
222 			assertTrue(sub instanceof FileTreeIterator);
223 			final FileTreeIterator subfti = (FileTreeIterator) sub;
224 			assertTrue(sub.first());
225 			assertFalse(sub.eof());
226 			assertEquals(paths[2], nameOf(sub));
227 			assertEquals(paths[2].length(), subfti.getEntryLength());
228 			assertEquals(mtime[2], subfti.getEntryLastModifiedInstant());
229 
230 			sub.next(1);
231 			assertTrue(sub.eof());
232 			top.next(1);
233 			assertFalse(top.first());
234 			assertFalse(top.eof());
235 			assertEquals(FileMode.REGULAR_FILE.getBits(), top.mode);
236 			assertEquals(paths[3], nameOf(top));
237 			assertEquals(paths[3].length(), top.getEntryLength());
238 			assertEquals(mtime[3], top.getEntryLastModifiedInstant());
239 
240 			top.next(1);
241 			assertTrue(top.eof());
242 		}
243 	}
244 
245 	@Test
246 	public void testComputeFileObjectId() throws Exception {
247 		final FileTreeIterator top = new FileTreeIterator(trash, db.getFS(),
248 				db.getConfig().get(WorkingTreeOptions.KEY));
249 
250 		final MessageDigest md = Constants.newMessageDigest();
251 		md.update(Constants.encodeASCII(Constants.TYPE_BLOB));
252 		md.update((byte) ' ');
253 		md.update(Constants.encodeASCII(paths[0].length()));
254 		md.update((byte) 0);
255 		md.update(Constants.encode(paths[0]));
256 		final ObjectId expect = ObjectId.fromRaw(md.digest());
257 
258 		assertEquals(expect, top.getEntryObjectId());
259 
260 		// Verify it was cached by removing the file and getting it again.
261 		//
262 		FileUtils.delete(new File(trash, paths[0]));
263 		assertEquals(expect, top.getEntryObjectId());
264 	}
265 
266 	@Test
267 	public void testDirCacheMatchingId() throws Exception {
268 		File f = writeTrashFile("file", "content");
269 		try (Git git = new Git(db)) {
270 			writeTrashFile("file", "content");
271 			fsTick(f);
272 			git.add().addFilepattern("file").call();
273 		}
274 		DirCacheEntry dce = db.readDirCache().getEntry("file");
275 		try (TreeWalk tw = new TreeWalk(db)) {
276 			FileTreeIterator fti = new FileTreeIterator(trash, db.getFS(),
277 					db.getConfig().get(WorkingTreeOptions.KEY));
278 			tw.addTree(fti);
279 			DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
280 			tw.addTree(dci);
281 			fti.setDirCacheIterator(tw, 1);
282 			while (tw.next() && !tw.getPathString().equals("file")) {
283 				//
284 			}
285 			assertEquals(MetadataDiff.EQUAL, fti.compareMetadata(dce));
286 			ObjectId fromRaw = ObjectId.fromRaw(fti.idBuffer(), fti.idOffset());
287 			assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea",
288 					fromRaw.getName());
289 			try (ObjectReader objectReader = db.newObjectReader()) {
290 				assertFalse(fti.isModified(dce, false, objectReader));
291 			}
292 		}
293 	}
294 
295 	@Test
296 	public void testTreewalkEnterSubtree() throws Exception {
297 		try (Git git = new Git(db); TreeWalk tw = new TreeWalk(db)) {
298 			writeTrashFile("b/c", "b/c");
299 			writeTrashFile("z/.git", "gitdir: /tmp/somewhere");
300 			git.add().addFilepattern(".").call();
301 			git.rm().addFilepattern("a,").addFilepattern("a,b")
302 					.addFilepattern("a0b").call();
303 			assertEquals("[a/b, mode:100644][b/c, mode:100644][z, mode:160000]",
304 					indexState(0));
305 			FileUtils.delete(new File(db.getWorkTree(), "b"),
306 					FileUtils.RECURSIVE);
307 
308 			tw.addTree(new DirCacheIterator(db.readDirCache()));
309 			tw.addTree(new FileTreeIterator(db));
310 			assertTrue(tw.next());
311 			assertEquals("a", tw.getPathString());
312 			tw.enterSubtree();
313 			tw.next();
314 			assertEquals("a/b", tw.getPathString());
315 			tw.next();
316 			assertEquals("b", tw.getPathString());
317 			tw.enterSubtree();
318 			tw.next();
319 			assertEquals("b/c", tw.getPathString());
320 			assertNotNull(tw.getTree(0, AbstractTreeIterator.class));
321 			assertNotNull(tw.getTree(EmptyTreeIterator.class));
322 		}
323 	}
324 
325 	@Test
326 	public void testIsModifiedSymlinkAsFile() throws Exception {
327 		writeTrashFile("symlink", "content");
328 		try (Git git = new Git(db)) {
329 			db.getConfig().setString(ConfigConstants.CONFIG_CORE_SECTION, null,
330 					ConfigConstants.CONFIG_KEY_SYMLINKS, "false");
331 			git.add().addFilepattern("symlink").call();
332 			git.commit().setMessage("commit").call();
333 		}
334 
335 		// Modify previously committed DirCacheEntry and write it back to disk
336 		DirCacheEntry dce = db.readDirCache().getEntry("symlink");
337 		dce.setFileMode(FileMode.SYMLINK);
338 		try (ObjectReader objectReader = db.newObjectReader()) {
339 			DirCacheCheckout.checkoutEntry(db, dce, objectReader, false, null);
340 
341 			FileTreeIterator fti = new FileTreeIterator(trash, db.getFS(),
342 					db.getConfig().get(WorkingTreeOptions.KEY));
343 			while (!fti.getEntryPathString().equals("symlink"))
344 				fti.next(1);
345 			assertFalse(fti.isModified(dce, false, objectReader));
346 		}
347 	}
348 
349 	@Test
350 	public void testIsModifiedFileSmudged() throws Exception {
351 		File f = writeTrashFile("file", "content");
352 		FS fs = db.getFS();
353 		try (Git git = new Git(db)) {
354 			// The idea of this test is to check the smudged handling
355 			// Hopefully fsTick will make sure our entry gets smudged
356 			fsTick(f);
357 			writeTrashFile("file", "content");
358 			Instant lastModified = fs.lastModifiedInstant(f);
359 			git.add().addFilepattern("file").call();
360 			writeTrashFile("file", "conten2");
361 			fs.setLastModified(f.toPath(), lastModified);
362 			// We cannot trust this to go fast enough on
363 			// a system with less than one-second lastModified
364 			// resolution, so we force the index to have the
365 			// same timestamp as the file we look at.
366 			fs.setLastModified(db.getIndexFile().toPath(), lastModified);
367 		}
368 		DirCacheEntry dce = db.readDirCache().getEntry("file");
369 		FileTreeIterator fti = new FileTreeIterator(trash, db.getFS(), db
370 				.getConfig().get(WorkingTreeOptions.KEY));
371 		while (!fti.getEntryPathString().equals("file"))
372 			fti.next(1);
373 		// If the rounding trick does not work we could skip the compareMetaData
374 		// test and hope that we are usually testing the intended code path.
375 		assertEquals(MetadataDiff.SMUDGED, fti.compareMetadata(dce));
376 		try (ObjectReader objectReader = db.newObjectReader()) {
377 			assertTrue(fti.isModified(dce, false, objectReader));
378 		}
379 	}
380 
381 	@Test
382 	public void submoduleHeadMatchesIndex() throws Exception {
383 		try (Git git = new Git(db);
384 				TreeWalk walk = new TreeWalk(db)) {
385 			writeTrashFile("file.txt", "content");
386 			git.add().addFilepattern("file.txt").call();
387 			final RevCommit id = git.commit().setMessage("create file").call();
388 			final String path = "sub";
389 			DirCache cache = db.lockDirCache();
390 			DirCacheEditor editor = cache.editor();
391 			editor.add(new PathEdit(path) {
392 
393 				@Override
394 				public void apply(DirCacheEntry ent) {
395 					ent.setFileMode(FileMode.GITLINK);
396 					ent.setObjectId(id);
397 				}
398 			});
399 			editor.commit();
400 
401 			Git.cloneRepository().setURI(db.getDirectory().toURI().toString())
402 					.setDirectory(new File(db.getWorkTree(), path)).call()
403 					.getRepository().close();
404 
405 			DirCacheIterator indexIter = new DirCacheIterator(db.readDirCache());
406 			FileTreeIterator workTreeIter = new FileTreeIterator(db);
407 			walk.addTree(indexIter);
408 			walk.addTree(workTreeIter);
409 			walk.setFilter(PathFilter.create(path));
410 
411 			assertTrue(walk.next());
412 			assertTrue(indexIter.idEqual(workTreeIter));
413 		}
414 	}
415 
416 	@Test
417 	public void submoduleWithNoGitDirectory() throws Exception {
418 		try (Git git = new Git(db);
419 				TreeWalk walk = new TreeWalk(db)) {
420 			writeTrashFile("file.txt", "content");
421 			git.add().addFilepattern("file.txt").call();
422 			final RevCommit id = git.commit().setMessage("create file").call();
423 			final String path = "sub";
424 			DirCache cache = db.lockDirCache();
425 			DirCacheEditor editor = cache.editor();
426 			editor.add(new PathEdit(path) {
427 
428 				@Override
429 				public void apply(DirCacheEntry ent) {
430 					ent.setFileMode(FileMode.GITLINK);
431 					ent.setObjectId(id);
432 				}
433 			});
434 			editor.commit();
435 
436 			File submoduleRoot = new File(db.getWorkTree(), path);
437 			assertTrue(submoduleRoot.mkdir());
438 			assertTrue(new File(submoduleRoot, Constants.DOT_GIT).mkdir());
439 
440 			DirCacheIterator indexIter = new DirCacheIterator(db.readDirCache());
441 			FileTreeIterator workTreeIter = new FileTreeIterator(db);
442 			walk.addTree(indexIter);
443 			walk.addTree(workTreeIter);
444 			walk.setFilter(PathFilter.create(path));
445 
446 			assertTrue(walk.next());
447 			assertFalse(indexIter.idEqual(workTreeIter));
448 			assertEquals(ObjectId.zeroId(), workTreeIter.getEntryObjectId());
449 		}
450 	}
451 
452 	@Test
453 	public void submoduleWithNoHead() throws Exception {
454 		try (Git git = new Git(db);
455 				TreeWalk walk = new TreeWalk(db)) {
456 			writeTrashFile("file.txt", "content");
457 			git.add().addFilepattern("file.txt").call();
458 			final RevCommit id = git.commit().setMessage("create file").call();
459 			final String path = "sub";
460 			DirCache cache = db.lockDirCache();
461 			DirCacheEditor editor = cache.editor();
462 			editor.add(new PathEdit(path) {
463 
464 				@Override
465 				public void apply(DirCacheEntry ent) {
466 					ent.setFileMode(FileMode.GITLINK);
467 					ent.setObjectId(id);
468 				}
469 			});
470 			editor.commit();
471 
472 			assertNotNull(Git.init().setDirectory(new File(db.getWorkTree(), path))
473 					.call().getRepository());
474 
475 			DirCacheIterator indexIter = new DirCacheIterator(db.readDirCache());
476 			FileTreeIterator workTreeIter = new FileTreeIterator(db);
477 			walk.addTree(indexIter);
478 			walk.addTree(workTreeIter);
479 			walk.setFilter(PathFilter.create(path));
480 
481 			assertTrue(walk.next());
482 			assertFalse(indexIter.idEqual(workTreeIter));
483 			assertEquals(ObjectId.zeroId(), workTreeIter.getEntryObjectId());
484 		}
485 	}
486 
487 	@Test
488 	public void submoduleDirectoryIterator() throws Exception {
489 		try (Git git = new Git(db);
490 				TreeWalk walk = new TreeWalk(db)) {
491 			writeTrashFile("file.txt", "content");
492 			git.add().addFilepattern("file.txt").call();
493 			final RevCommit id = git.commit().setMessage("create file").call();
494 			final String path = "sub";
495 			DirCache cache = db.lockDirCache();
496 			DirCacheEditor editor = cache.editor();
497 			editor.add(new PathEdit(path) {
498 
499 				@Override
500 				public void apply(DirCacheEntry ent) {
501 					ent.setFileMode(FileMode.GITLINK);
502 					ent.setObjectId(id);
503 				}
504 			});
505 			editor.commit();
506 
507 			Git.cloneRepository().setURI(db.getDirectory().toURI().toString())
508 					.setDirectory(new File(db.getWorkTree(), path)).call()
509 					.getRepository().close();
510 
511 			DirCacheIterator indexIter = new DirCacheIterator(db.readDirCache());
512 			FileTreeIterator workTreeIter = new FileTreeIterator(db.getWorkTree(),
513 					db.getFS(), db.getConfig().get(WorkingTreeOptions.KEY));
514 			walk.addTree(indexIter);
515 			walk.addTree(workTreeIter);
516 			walk.setFilter(PathFilter.create(path));
517 
518 			assertTrue(walk.next());
519 			assertTrue(indexIter.idEqual(workTreeIter));
520 		}
521 	}
522 
523 	@Test
524 	public void submoduleNestedWithHeadMatchingIndex() throws Exception {
525 		try (Git git = new Git(db);
526 				TreeWalk walk = new TreeWalk(db)) {
527 			writeTrashFile("file.txt", "content");
528 			git.add().addFilepattern("file.txt").call();
529 			final RevCommit id = git.commit().setMessage("create file").call();
530 			final String path = "sub/dir1/dir2";
531 			DirCache cache = db.lockDirCache();
532 			DirCacheEditor editor = cache.editor();
533 			editor.add(new PathEdit(path) {
534 
535 				@Override
536 				public void apply(DirCacheEntry ent) {
537 					ent.setFileMode(FileMode.GITLINK);
538 					ent.setObjectId(id);
539 				}
540 			});
541 			editor.commit();
542 
543 			Git.cloneRepository().setURI(db.getDirectory().toURI().toString())
544 					.setDirectory(new File(db.getWorkTree(), path)).call()
545 					.getRepository().close();
546 
547 			DirCacheIterator indexIter = new DirCacheIterator(db.readDirCache());
548 			FileTreeIterator workTreeIter = new FileTreeIterator(db);
549 			walk.addTree(indexIter);
550 			walk.addTree(workTreeIter);
551 			walk.setFilter(PathFilter.create(path));
552 
553 			assertTrue(walk.next());
554 			assertTrue(indexIter.idEqual(workTreeIter));
555 		}
556 	}
557 
558 	@Test
559 	public void idOffset() throws Exception {
560 		try (Git git = new Git(db);
561 				TreeWalk tw = new TreeWalk(db)) {
562 			writeTrashFile("fileAinfsonly", "A");
563 			File fileBinindex = writeTrashFile("fileBinindex", "B");
564 			fsTick(fileBinindex);
565 			git.add().addFilepattern("fileBinindex").call();
566 			writeTrashFile("fileCinfsonly", "C");
567 			DirCacheIterator indexIter = new DirCacheIterator(db.readDirCache());
568 			FileTreeIterator workTreeIter = new FileTreeIterator(db);
569 			tw.addTree(indexIter);
570 			tw.addTree(workTreeIter);
571 			workTreeIter.setDirCacheIterator(tw, 0);
572 			assertEntry("d46c305e85b630558ee19cc47e73d2e5c8c64cdc", "a,", tw);
573 			assertEntry("58ee403f98538ec02409538b3f80adf610accdec", "a,b", tw);
574 			assertEntry("0000000000000000000000000000000000000000", "a", tw);
575 			assertEntry("b8d30ff397626f0f1d3538d66067edf865e201d6", "a0b", tw);
576 			// The reason for adding this test. Check that the id is correct for
577 			// mixed
578 			assertEntry("8c7e5a667f1b771847fe88c01c3de34413a1b220",
579 					"fileAinfsonly", tw);
580 			assertEntry("7371f47a6f8bd23a8fa1a8b2a9479cdd76380e54", "fileBinindex",
581 					tw);
582 			assertEntry("96d80cd6c4e7158dbebd0849f4fb7ce513e5828c",
583 					"fileCinfsonly", tw);
584 			assertFalse(tw.next());
585 		}
586 	}
587 
588 	private final FileTreeIterator.FileModeStrategy NO_GITLINKS_STRATEGY = (
589 			File f, FS.Attributes attributes) -> {
590 		if (attributes.isSymbolicLink()) {
591 			return FileMode.SYMLINK;
592 		} else if (attributes.isDirectory()) {
593 			// NOTE: in the production DefaultFileModeStrategy, there is
594 			// a check here for a subdirectory called '.git', and if it
595 			// exists, we create a GITLINK instead of recursing into the
596 			// tree. In this custom strategy, we ignore nested git dirs
597 			// and treat all directories the same.
598 			return FileMode.TREE;
599 		} else if (attributes.isExecutable()) {
600 			return FileMode.EXECUTABLE_FILE;
601 		} else {
602 			return FileMode.REGULAR_FILE;
603 		}
604 	};
605 
606 	private Repository createNestedRepo() throws IOException {
607 		File gitdir = createUniqueTestGitDir(false);
608 		FileRepositoryBuilder builder = new FileRepositoryBuilder();
609 		builder.setGitDir(gitdir);
610 		Repository nestedRepo = builder.build();
611 		nestedRepo.create();
612 
613 		JGitTestUtil.writeTrashFile(nestedRepo, "sub", "a.txt", "content");
614 
615 		File nestedRepoPath = new File(nestedRepo.getWorkTree(), "sub/nested");
616 		FileRepositoryBuilder nestedBuilder = new FileRepositoryBuilder();
617 		nestedBuilder.setWorkTree(nestedRepoPath);
618 		nestedBuilder.build().create();
619 
620 		JGitTestUtil.writeTrashFile(nestedRepo, "sub/nested", "b.txt",
621 				"content b");
622 
623 		return nestedRepo;
624 	}
625 
626 	@Test
627 	public void testCustomFileModeStrategy() throws Exception {
628 		try (Repository nestedRepo = createNestedRepo();
629 				Git git = new Git(nestedRepo)) {
630 			// validate that our custom strategy is honored
631 			WorkingTreeIterator customIterator = new FileTreeIterator(
632 					nestedRepo, NO_GITLINKS_STRATEGY);
633 			git.add().setWorkingTreeIterator(customIterator).addFilepattern(".")
634 					.call();
635 			assertEquals(
636 					"[sub/a.txt, mode:100644, content:content]"
637 							+ "[sub/nested/b.txt, mode:100644, content:content b]",
638 					indexState(nestedRepo, CONTENT));
639 		}
640 	}
641 
642 	@Test
643 	public void testCustomFileModeStrategyFromParentIterator() throws Exception {
644 		try (Repository nestedRepo = createNestedRepo();
645 				Git git = new Git(nestedRepo)) {
646 			FileTreeIterator customIterator = new FileTreeIterator(nestedRepo,
647 					NO_GITLINKS_STRATEGY);
648 			File r = new File(nestedRepo.getWorkTree(), "sub");
649 
650 			// here we want to validate that if we create a new iterator using
651 			// the constructor that accepts a parent iterator, that the child
652 			// iterator correctly inherits the FileModeStrategy from the parent
653 			// iterator.
654 			FileTreeIterator childIterator = new FileTreeIterator(
655 					customIterator, r, nestedRepo.getFS());
656 			git.add().setWorkingTreeIterator(childIterator).addFilepattern(".")
657 					.call();
658 			assertEquals(
659 					"[sub/a.txt, mode:100644, content:content]"
660 							+ "[sub/nested/b.txt, mode:100644, content:content b]",
661 					indexState(nestedRepo, CONTENT));
662 		}
663 	}
664 
665 	@Test
666 	public void testFileModeSymLinkIsNotATree() throws IOException {
667 		org.junit.Assume.assumeTrue(FS.DETECTED.supportsSymlinks());
668 		FS fs = db.getFS();
669 		// mål = target in swedish, just to get some unicode in here
670 		writeTrashFile("mål/data", "targetdata");
671 		File file = new File(trash, "länk");
672 
673 		try {
674 			file.toPath();
675 		} catch (InvalidPathException e) {
676 			// When executing a test with LANG environment variable set to non
677 			// UTF-8 encoding, it seems that JRE cannot handle Unicode file
678 			// paths. This happens when this test is executed in Bazel as it
679 			// unsets LANG
680 			// (https://docs.bazel.build/versions/master/test-encyclopedia.html#initial-conditions).
681 			// Skip the test if the runtime cannot handle Unicode characters.
682 			assumeNoException(e);
683 		}
684 
685 		fs.createSymLink(file, "mål");
686 		FileTreeIterator fti = new FileTreeIterator(db);
687 		assertFalse(fti.eof());
688 		while (!fti.getEntryPathString().equals("länk")) {
689 			fti.next(1);
690 		}
691 		assertEquals("länk", fti.getEntryPathString());
692 		assertEquals(FileMode.SYMLINK, fti.getEntryFileMode());
693 		fti.next(1);
694 		assertFalse(fti.eof());
695 		assertEquals("mål", fti.getEntryPathString());
696 		assertEquals(FileMode.TREE, fti.getEntryFileMode());
697 		fti.next(1);
698 		assertTrue(fti.eof());
699 	}
700 
701 	@Test
702 	public void testSymlinkNotModifiedThoughNormalized() throws Exception {
703 		DirCache dc = db.lockDirCache();
704 		DirCacheEditor dce = dc.editor();
705 		final String UNNORMALIZED = "target/";
706 		final byte[] UNNORMALIZED_BYTES = Constants.encode(UNNORMALIZED);
707 		try (ObjectInserter oi = db.newObjectInserter()) {
708 			final ObjectId linkid = oi.insert(Constants.OBJ_BLOB,
709 					UNNORMALIZED_BYTES, 0, UNNORMALIZED_BYTES.length);
710 			dce.add(new DirCacheEditor.PathEdit("link") {
711 				@Override
712 				public void apply(DirCacheEntry ent) {
713 					ent.setFileMode(FileMode.SYMLINK);
714 					ent.setObjectId(linkid);
715 					ent.setLength(UNNORMALIZED_BYTES.length);
716 				}
717 			});
718 			assertTrue(dce.commit());
719 		}
720 		try (Git git = new Git(db)) {
721 			git.commit().setMessage("Adding link").call();
722 			git.reset().setMode(ResetType.HARD).call();
723 			DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
724 			FileTreeIterator fti = new FileTreeIterator(db);
725 
726 			// self-check
727 			while (!fti.getEntryPathString().equals("link")) {
728 				fti.next(1);
729 			}
730 			assertEquals("link", fti.getEntryPathString());
731 			assertEquals("link", dci.getEntryPathString());
732 
733 			// test
734 			assertFalse(fti.isModified(dci.getDirCacheEntry(), true,
735 					db.newObjectReader()));
736 		}
737 	}
738 
739 	/**
740 	 * Like #testSymlinkNotModifiedThoughNormalized but there is no
741 	 * normalization being done.
742 	 *
743 	 * @throws Exception
744 	 */
745 	@Test
746 	public void testSymlinkModifiedNotNormalized() throws Exception {
747 		DirCache dc = db.lockDirCache();
748 		DirCacheEditor dce = dc.editor();
749 		final String NORMALIZED = "target";
750 		final byte[] NORMALIZED_BYTES = Constants.encode(NORMALIZED);
751 		try (ObjectInserter oi = db.newObjectInserter()) {
752 			final ObjectId linkid = oi.insert(Constants.OBJ_BLOB,
753 					NORMALIZED_BYTES, 0, NORMALIZED_BYTES.length);
754 			dce.add(new DirCacheEditor.PathEdit("link") {
755 				@Override
756 				public void apply(DirCacheEntry ent) {
757 					ent.setFileMode(FileMode.SYMLINK);
758 					ent.setObjectId(linkid);
759 					ent.setLength(NORMALIZED_BYTES.length);
760 				}
761 			});
762 			assertTrue(dce.commit());
763 		}
764 		try (Git git = new Git(db)) {
765 			git.commit().setMessage("Adding link").call();
766 			git.reset().setMode(ResetType.HARD).call();
767 			DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
768 			FileTreeIterator fti = new FileTreeIterator(db);
769 
770 			// self-check
771 			while (!fti.getEntryPathString().equals("link")) {
772 				fti.next(1);
773 			}
774 			assertEquals("link", fti.getEntryPathString());
775 			assertEquals("link", dci.getEntryPathString());
776 
777 			// test
778 			assertFalse(fti.isModified(dci.getDirCacheEntry(), true,
779 					db.newObjectReader()));
780 		}
781 	}
782 
783 	/**
784 	 * Like #testSymlinkNotModifiedThoughNormalized but here the link is
785 	 * modified.
786 	 *
787 	 * @throws Exception
788 	 */
789 	@Test
790 	public void testSymlinkActuallyModified() throws Exception {
791 		org.junit.Assume.assumeTrue(FS.DETECTED.supportsSymlinks());
792 		final String NORMALIZED = "target";
793 		final byte[] NORMALIZED_BYTES = Constants.encode(NORMALIZED);
794 		try (ObjectInserter oi = db.newObjectInserter()) {
795 			final ObjectId linkid = oi.insert(Constants.OBJ_BLOB,
796 					NORMALIZED_BYTES, 0, NORMALIZED_BYTES.length);
797 			DirCache dc = db.lockDirCache();
798 			DirCacheEditor dce = dc.editor();
799 			dce.add(new DirCacheEditor.PathEdit("link") {
800 				@Override
801 				public void apply(DirCacheEntry ent) {
802 					ent.setFileMode(FileMode.SYMLINK);
803 					ent.setObjectId(linkid);
804 					ent.setLength(NORMALIZED_BYTES.length);
805 				}
806 			});
807 			assertTrue(dce.commit());
808 		}
809 		try (Git git = new Git(db)) {
810 			git.commit().setMessage("Adding link").call();
811 			git.reset().setMode(ResetType.HARD).call();
812 
813 			FileUtils.delete(new File(trash, "link"), FileUtils.NONE);
814 			FS.DETECTED.createSymLink(new File(trash, "link"), "newtarget");
815 			DirCacheIterator dci = new DirCacheIterator(db.readDirCache());
816 			FileTreeIterator fti = new FileTreeIterator(db);
817 
818 			// self-check
819 			while (!fti.getEntryPathString().equals("link")) {
820 				fti.next(1);
821 			}
822 			assertEquals("link", fti.getEntryPathString());
823 			assertEquals("link", dci.getEntryPathString());
824 
825 			// test
826 			assertTrue(fti.isModified(dci.getDirCacheEntry(), true,
827 					db.newObjectReader()));
828 		}
829 	}
830 
831 	private static void assertEntry(String sha1string, String path, TreeWalk tw)
832 			throws MissingObjectException, IncorrectObjectTypeException,
833 			CorruptObjectException, IOException {
834 		assertTrue(tw.next());
835 		assertEquals(path, tw.getPathString());
836 		assertEquals(sha1string, tw.getObjectId(1).getName() /* 1=filetree here */);
837 	}
838 
839 	private static String nameOf(AbstractTreeIterator i) {
840 		return RawParseUtils.decode(UTF_8, i.path, 0, i.pathLen);
841 	}
842 }