You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileTreeIteratorTest.java 27KB

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