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.

ResetCommandTest.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /*
  2. * Copyright (C) 2011, Chris Aniszczyk <caniszczyk@gmail.com>
  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.api;
  44. import static org.eclipse.jgit.api.ResetCommand.ResetType.HARD;
  45. import static org.junit.Assert.assertEquals;
  46. import static org.junit.Assert.assertFalse;
  47. import static org.junit.Assert.assertNotNull;
  48. import static org.junit.Assert.assertTrue;
  49. import static org.junit.Assert.fail;
  50. import java.io.File;
  51. import java.io.IOException;
  52. import java.io.PrintWriter;
  53. import org.eclipse.jgit.api.ResetCommand.ResetType;
  54. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  55. import org.eclipse.jgit.api.errors.JGitInternalException;
  56. import org.eclipse.jgit.api.errors.NoFilepatternException;
  57. import org.eclipse.jgit.api.errors.NoHeadException;
  58. import org.eclipse.jgit.api.errors.NoMessageException;
  59. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  60. import org.eclipse.jgit.dircache.DirCache;
  61. import org.eclipse.jgit.dircache.DirCacheEntry;
  62. import org.eclipse.jgit.errors.AmbiguousObjectException;
  63. import org.eclipse.jgit.lib.Constants;
  64. import org.eclipse.jgit.lib.ObjectId;
  65. import org.eclipse.jgit.lib.RepositoryTestCase;
  66. import org.eclipse.jgit.revwalk.RevCommit;
  67. import org.eclipse.jgit.revwalk.RevWalk;
  68. import org.eclipse.jgit.treewalk.TreeWalk;
  69. import org.eclipse.jgit.util.FileUtils;
  70. import org.junit.Assert;
  71. import org.junit.Test;
  72. public class ResetCommandTest extends RepositoryTestCase {
  73. private Git git;
  74. private RevCommit initialCommit;
  75. private RevCommit secondCommit;
  76. private File indexFile;
  77. private File untrackedFile;
  78. private DirCacheEntry prestage;
  79. public void setupRepository() throws IOException, NoFilepatternException,
  80. NoHeadException, NoMessageException, ConcurrentRefUpdateException,
  81. JGitInternalException, WrongRepositoryStateException {
  82. // create initial commit
  83. git = new Git(db);
  84. initialCommit = git.commit().setMessage("initial commit").call();
  85. // create nested file
  86. File dir = new File(db.getWorkTree(), "dir");
  87. FileUtils.mkdir(dir);
  88. File nestedFile = new File(dir, "b.txt");
  89. FileUtils.createNewFile(nestedFile);
  90. PrintWriter nesterFileWriter = new PrintWriter(nestedFile);
  91. nesterFileWriter.print("content");
  92. nesterFileWriter.flush();
  93. // create file
  94. indexFile = new File(db.getWorkTree(), "a.txt");
  95. FileUtils.createNewFile(indexFile);
  96. PrintWriter writer = new PrintWriter(indexFile);
  97. writer.print("content");
  98. writer.flush();
  99. // add file and commit it
  100. git.add().addFilepattern("dir").addFilepattern("a.txt").call();
  101. secondCommit = git.commit().setMessage("adding a.txt and dir/b.txt")
  102. .call();
  103. prestage = DirCache.read(db.getIndexFile(), db.getFS()).getEntry(
  104. indexFile.getName());
  105. // modify file and add to index
  106. writer.print("new content");
  107. writer.close();
  108. nesterFileWriter.print("new content");
  109. nesterFileWriter.close();
  110. git.add().addFilepattern("a.txt").addFilepattern("dir").call();
  111. // create a file not added to the index
  112. untrackedFile = new File(db.getWorkTree(),
  113. "notAddedToIndex.txt");
  114. FileUtils.createNewFile(untrackedFile);
  115. PrintWriter writer2 = new PrintWriter(untrackedFile);
  116. writer2.print("content");
  117. writer2.close();
  118. }
  119. @Test
  120. public void testHardReset() throws JGitInternalException,
  121. AmbiguousObjectException, IOException, NoFilepatternException,
  122. NoHeadException, NoMessageException, ConcurrentRefUpdateException,
  123. WrongRepositoryStateException {
  124. setupRepository();
  125. ObjectId prevHead = db.resolve(Constants.HEAD);
  126. git.reset().setMode(ResetType.HARD).setRef(initialCommit.getName())
  127. .call();
  128. // check if HEAD points to initial commit now
  129. ObjectId head = db.resolve(Constants.HEAD);
  130. assertTrue(head.equals(initialCommit));
  131. // check if files were removed
  132. assertFalse(indexFile.exists());
  133. assertTrue(untrackedFile.exists());
  134. // fileInIndex must no longer be in HEAD and in the index
  135. String fileInIndexPath = indexFile.getAbsolutePath();
  136. assertFalse(inHead(fileInIndexPath));
  137. assertFalse(inIndex(indexFile.getName()));
  138. assertReflog(prevHead, head);
  139. }
  140. @Test
  141. public void testResetToNonexistingHEAD() throws JGitInternalException,
  142. AmbiguousObjectException, IOException {
  143. // create a file in the working tree of a fresh repo
  144. git = new Git(db);
  145. writeTrashFile("f", "content");
  146. try {
  147. git.reset().setRef(Constants.HEAD).call();
  148. fail("Expected JGitInternalException didn't occur");
  149. } catch (JGitInternalException e) {
  150. // got the expected exception
  151. }
  152. }
  153. @Test
  154. public void testSoftReset() throws JGitInternalException,
  155. AmbiguousObjectException, IOException, NoFilepatternException,
  156. NoHeadException, NoMessageException, ConcurrentRefUpdateException,
  157. WrongRepositoryStateException {
  158. setupRepository();
  159. ObjectId prevHead = db.resolve(Constants.HEAD);
  160. git.reset().setMode(ResetType.SOFT).setRef(initialCommit.getName())
  161. .call();
  162. // check if HEAD points to initial commit now
  163. ObjectId head = db.resolve(Constants.HEAD);
  164. assertTrue(head.equals(initialCommit));
  165. // check if files still exist
  166. assertTrue(untrackedFile.exists());
  167. assertTrue(indexFile.exists());
  168. // fileInIndex must no longer be in HEAD but has to be in the index
  169. String fileInIndexPath = indexFile.getAbsolutePath();
  170. assertFalse(inHead(fileInIndexPath));
  171. assertTrue(inIndex(indexFile.getName()));
  172. assertReflog(prevHead, head);
  173. }
  174. @Test
  175. public void testMixedReset() throws JGitInternalException,
  176. AmbiguousObjectException, IOException, NoFilepatternException,
  177. NoHeadException, NoMessageException, ConcurrentRefUpdateException,
  178. WrongRepositoryStateException {
  179. setupRepository();
  180. ObjectId prevHead = db.resolve(Constants.HEAD);
  181. git.reset().setMode(ResetType.MIXED).setRef(initialCommit.getName())
  182. .call();
  183. // check if HEAD points to initial commit now
  184. ObjectId head = db.resolve(Constants.HEAD);
  185. assertTrue(head.equals(initialCommit));
  186. // check if files still exist
  187. assertTrue(untrackedFile.exists());
  188. assertTrue(indexFile.exists());
  189. // fileInIndex must no longer be in HEAD and in the index
  190. String fileInIndexPath = indexFile.getAbsolutePath();
  191. assertFalse(inHead(fileInIndexPath));
  192. assertFalse(inIndex(indexFile.getName()));
  193. assertReflog(prevHead, head);
  194. }
  195. @Test
  196. public void testMixedResetRetainsSizeAndModifiedTime() throws Exception {
  197. git = new Git(db);
  198. writeTrashFile("a.txt", "a").setLastModified(
  199. System.currentTimeMillis() - 60 * 1000);
  200. assertNotNull(git.add().addFilepattern("a.txt").call());
  201. assertNotNull(git.commit().setMessage("a commit").call());
  202. writeTrashFile("b.txt", "b").setLastModified(
  203. System.currentTimeMillis() - 60 * 1000);
  204. assertNotNull(git.add().addFilepattern("b.txt").call());
  205. RevCommit commit2 = git.commit().setMessage("b commit").call();
  206. assertNotNull(commit2);
  207. DirCache cache = db.readDirCache();
  208. DirCacheEntry aEntry = cache.getEntry("a.txt");
  209. assertNotNull(aEntry);
  210. assertTrue(aEntry.getLength() > 0);
  211. assertTrue(aEntry.getLastModified() > 0);
  212. DirCacheEntry bEntry = cache.getEntry("b.txt");
  213. assertNotNull(bEntry);
  214. assertTrue(bEntry.getLength() > 0);
  215. assertTrue(bEntry.getLastModified() > 0);
  216. git.reset().setMode(ResetType.MIXED).setRef(commit2.getName()).call();
  217. cache = db.readDirCache();
  218. DirCacheEntry mixedAEntry = cache.getEntry("a.txt");
  219. assertNotNull(mixedAEntry);
  220. assertEquals(aEntry.getLastModified(), mixedAEntry.getLastModified());
  221. assertEquals(aEntry.getLastModified(), mixedAEntry.getLastModified());
  222. DirCacheEntry mixedBEntry = cache.getEntry("b.txt");
  223. assertNotNull(mixedBEntry);
  224. assertEquals(bEntry.getLastModified(), mixedBEntry.getLastModified());
  225. assertEquals(bEntry.getLastModified(), mixedBEntry.getLastModified());
  226. }
  227. @Test
  228. public void testPathsReset() throws Exception {
  229. setupRepository();
  230. DirCacheEntry preReset = DirCache.read(db.getIndexFile(), db.getFS())
  231. .getEntry(indexFile.getName());
  232. assertNotNull(preReset);
  233. git.add().addFilepattern(untrackedFile.getName()).call();
  234. // 'a.txt' has already been modified in setupRepository
  235. // 'notAddedToIndex.txt' has been added to repository
  236. git.reset().addPath(indexFile.getName())
  237. .addPath(untrackedFile.getName()).call();
  238. DirCacheEntry postReset = DirCache.read(db.getIndexFile(), db.getFS())
  239. .getEntry(indexFile.getName());
  240. assertNotNull(postReset);
  241. Assert.assertNotSame(preReset.getObjectId(), postReset.getObjectId());
  242. Assert.assertEquals(prestage.getObjectId(), postReset.getObjectId());
  243. // check that HEAD hasn't moved
  244. ObjectId head = db.resolve(Constants.HEAD);
  245. assertTrue(head.equals(secondCommit));
  246. // check if files still exist
  247. assertTrue(untrackedFile.exists());
  248. assertTrue(indexFile.exists());
  249. assertTrue(inHead(indexFile.getName()));
  250. assertTrue(inIndex(indexFile.getName()));
  251. assertFalse(inIndex(untrackedFile.getName()));
  252. }
  253. @Test
  254. public void testPathsResetOnDirs() throws Exception {
  255. setupRepository();
  256. DirCacheEntry preReset = DirCache.read(db.getIndexFile(), db.getFS())
  257. .getEntry("dir/b.txt");
  258. assertNotNull(preReset);
  259. git.add().addFilepattern(untrackedFile.getName()).call();
  260. // 'dir/b.txt' has already been modified in setupRepository
  261. git.reset().addPath("dir").call();
  262. DirCacheEntry postReset = DirCache.read(db.getIndexFile(), db.getFS())
  263. .getEntry("dir/b.txt");
  264. assertNotNull(postReset);
  265. Assert.assertNotSame(preReset.getObjectId(), postReset.getObjectId());
  266. // check that HEAD hasn't moved
  267. ObjectId head = db.resolve(Constants.HEAD);
  268. assertTrue(head.equals(secondCommit));
  269. // check if files still exist
  270. assertTrue(untrackedFile.exists());
  271. assertTrue(inHead("dir/b.txt"));
  272. assertTrue(inIndex("dir/b.txt"));
  273. }
  274. @Test
  275. public void testPathsResetWithRef() throws Exception {
  276. setupRepository();
  277. DirCacheEntry preReset = DirCache.read(db.getIndexFile(), db.getFS())
  278. .getEntry(indexFile.getName());
  279. assertNotNull(preReset);
  280. git.add().addFilepattern(untrackedFile.getName()).call();
  281. // 'a.txt' has already been modified in setupRepository
  282. // 'notAddedToIndex.txt' has been added to repository
  283. // reset to the inital commit
  284. git.reset().setRef(initialCommit.getName())
  285. .addPath(indexFile.getName())
  286. .addPath(untrackedFile.getName()).call();
  287. // check that HEAD hasn't moved
  288. ObjectId head = db.resolve(Constants.HEAD);
  289. assertTrue(head.equals(secondCommit));
  290. // check if files still exist
  291. assertTrue(untrackedFile.exists());
  292. assertTrue(indexFile.exists());
  293. assertTrue(inHead(indexFile.getName()));
  294. assertFalse(inIndex(indexFile.getName()));
  295. assertFalse(inIndex(untrackedFile.getName()));
  296. }
  297. @Test
  298. public void testHardResetOnTag() throws Exception {
  299. setupRepository();
  300. String tagName = "initialtag";
  301. git.tag().setName(tagName).setObjectId(secondCommit)
  302. .setMessage("message").call();
  303. DirCacheEntry preReset = DirCache.read(db.getIndexFile(), db.getFS())
  304. .getEntry(indexFile.getName());
  305. assertNotNull(preReset);
  306. git.add().addFilepattern(untrackedFile.getName()).call();
  307. git.reset().setRef(tagName).setMode(HARD).call();
  308. ObjectId head = db.resolve(Constants.HEAD);
  309. assertTrue(head.equals(secondCommit));
  310. }
  311. private void assertReflog(ObjectId prevHead, ObjectId head)
  312. throws IOException {
  313. // Check the reflog for HEAD
  314. String actualHeadMessage = db.getReflogReader(Constants.HEAD)
  315. .getLastEntry().getComment();
  316. String expectedHeadMessage = head.getName() + ": updating HEAD";
  317. assertEquals(expectedHeadMessage, actualHeadMessage);
  318. assertEquals(head.getName(), db.getReflogReader(Constants.HEAD)
  319. .getLastEntry().getNewId().getName());
  320. assertEquals(prevHead.getName(), db.getReflogReader(Constants.HEAD)
  321. .getLastEntry().getOldId().getName());
  322. // The reflog for master contains the same as the one for HEAD
  323. String actualMasterMessage = db.getReflogReader("refs/heads/master")
  324. .getLastEntry().getComment();
  325. String expectedMasterMessage = head.getName() + ": updating HEAD"; // yes!
  326. assertEquals(expectedMasterMessage, actualMasterMessage);
  327. assertEquals(head.getName(), db.getReflogReader(Constants.HEAD)
  328. .getLastEntry().getNewId().getName());
  329. assertEquals(prevHead.getName(), db
  330. .getReflogReader("refs/heads/master").getLastEntry().getOldId()
  331. .getName());
  332. }
  333. /**
  334. * Checks if a file with the given path exists in the HEAD tree
  335. *
  336. * @param path
  337. * @return true if the file exists
  338. * @throws IOException
  339. */
  340. private boolean inHead(String path) throws IOException {
  341. ObjectId headId = db.resolve(Constants.HEAD);
  342. RevWalk rw = new RevWalk(db);
  343. TreeWalk tw = null;
  344. try {
  345. tw = TreeWalk.forPath(db, path, rw.parseTree(headId));
  346. return tw != null;
  347. } finally {
  348. rw.release();
  349. rw.dispose();
  350. if (tw != null)
  351. tw.release();
  352. }
  353. }
  354. /**
  355. * Checks if a file with the given path exists in the index
  356. *
  357. * @param path
  358. * @return true if the file exists
  359. * @throws IOException
  360. */
  361. private boolean inIndex(String path) throws IOException {
  362. DirCache dc = DirCache.read(db.getIndexFile(), db.getFS());
  363. return dc.getEntry(path) != null;
  364. }
  365. }