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

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