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

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