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

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