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 29KB

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