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

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