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.

CheckoutCommandTest.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /*
  2. * Copyright (C) 2010, Chris Aniszczyk <caniszczyk@gmail.com>
  3. * Copyright (C) 2011, Matthias Sohn <matthias.sohn@sap.com>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.api;
  45. import static org.hamcrest.MatcherAssert.assertThat;
  46. import static org.hamcrest.CoreMatchers.is;
  47. import static org.junit.Assert.assertEquals;
  48. import static org.junit.Assert.assertFalse;
  49. import static org.junit.Assert.assertNotNull;
  50. import static org.junit.Assert.assertNull;
  51. import static org.junit.Assert.assertSame;
  52. import static org.junit.Assert.assertTrue;
  53. import static org.junit.Assert.fail;
  54. import java.io.File;
  55. import java.io.FileInputStream;
  56. import java.io.IOException;
  57. import java.net.MalformedURLException;
  58. import java.net.URISyntaxException;
  59. import org.eclipse.jgit.api.CheckoutResult.Status;
  60. import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
  61. import org.eclipse.jgit.api.errors.GitAPIException;
  62. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  63. import org.eclipse.jgit.api.errors.InvalidRemoteException;
  64. import org.eclipse.jgit.api.errors.JGitInternalException;
  65. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  66. import org.eclipse.jgit.api.errors.RefNotFoundException;
  67. import org.eclipse.jgit.api.errors.TransportException;
  68. import org.eclipse.jgit.dircache.DirCache;
  69. import org.eclipse.jgit.dircache.DirCacheEntry;
  70. import org.eclipse.jgit.junit.RepositoryTestCase;
  71. import org.eclipse.jgit.lib.ConfigConstants;
  72. import org.eclipse.jgit.lib.Constants;
  73. import org.eclipse.jgit.lib.Ref;
  74. import org.eclipse.jgit.lib.RefUpdate;
  75. import org.eclipse.jgit.lib.Repository;
  76. import org.eclipse.jgit.lib.StoredConfig;
  77. import org.eclipse.jgit.revwalk.RevCommit;
  78. import org.eclipse.jgit.transport.RefSpec;
  79. import org.eclipse.jgit.transport.RemoteConfig;
  80. import org.eclipse.jgit.transport.URIish;
  81. import org.eclipse.jgit.util.FileUtils;
  82. import org.junit.Before;
  83. import org.junit.Test;
  84. public class CheckoutCommandTest extends RepositoryTestCase {
  85. private Git git;
  86. RevCommit initialCommit;
  87. RevCommit secondCommit;
  88. @Override
  89. @Before
  90. public void setUp() throws Exception {
  91. super.setUp();
  92. git = new Git(db);
  93. // commit something
  94. writeTrashFile("Test.txt", "Hello world");
  95. git.add().addFilepattern("Test.txt").call();
  96. initialCommit = git.commit().setMessage("Initial commit").call();
  97. // create a master branch and switch to it
  98. git.branchCreate().setName("test").call();
  99. RefUpdate rup = db.updateRef(Constants.HEAD);
  100. rup.link("refs/heads/test");
  101. // commit something on the test branch
  102. writeTrashFile("Test.txt", "Some change");
  103. git.add().addFilepattern("Test.txt").call();
  104. secondCommit = git.commit().setMessage("Second commit").call();
  105. }
  106. @Test
  107. public void testSimpleCheckout() throws Exception {
  108. git.checkout().setName("test").call();
  109. }
  110. @Test
  111. public void testCheckout() throws Exception {
  112. git.checkout().setName("test").call();
  113. assertEquals("[Test.txt, mode:100644, content:Some change]",
  114. indexState(CONTENT));
  115. Ref result = git.checkout().setName("master").call();
  116. assertEquals("[Test.txt, mode:100644, content:Hello world]",
  117. indexState(CONTENT));
  118. assertEquals("refs/heads/master", result.getName());
  119. assertEquals("refs/heads/master", git.getRepository().getFullBranch());
  120. }
  121. @Test
  122. public void testCreateBranchOnCheckout() throws Exception {
  123. git.checkout().setCreateBranch(true).setName("test2").call();
  124. assertNotNull(db.getRef("test2"));
  125. }
  126. @Test
  127. public void testCheckoutToNonExistingBranch() throws GitAPIException {
  128. try {
  129. git.checkout().setName("badbranch").call();
  130. fail("Should have failed");
  131. } catch (RefNotFoundException e) {
  132. // except to hit here
  133. }
  134. }
  135. @Test
  136. public void testCheckoutWithConflict() {
  137. CheckoutCommand co = git.checkout();
  138. try {
  139. writeTrashFile("Test.txt", "Another change");
  140. assertEquals(Status.NOT_TRIED, co.getResult().getStatus());
  141. co.setName("master").call();
  142. fail("Should have failed");
  143. } catch (Exception e) {
  144. assertEquals(Status.CONFLICTS, co.getResult().getStatus());
  145. assertTrue(co.getResult().getConflictList().contains("Test.txt"));
  146. }
  147. }
  148. @Test
  149. public void testCheckoutWithNonDeletedFiles() throws Exception {
  150. File testFile = writeTrashFile("temp", "");
  151. FileInputStream fis = new FileInputStream(testFile);
  152. try {
  153. FileUtils.delete(testFile);
  154. return;
  155. } catch (IOException e) {
  156. // the test makes only sense if deletion of
  157. // a file with open stream fails
  158. } finally {
  159. fis.close();
  160. }
  161. FileUtils.delete(testFile);
  162. CheckoutCommand co = git.checkout();
  163. // delete Test.txt in branch test
  164. testFile = new File(db.getWorkTree(), "Test.txt");
  165. assertTrue(testFile.exists());
  166. FileUtils.delete(testFile);
  167. assertFalse(testFile.exists());
  168. git.add().addFilepattern("Test.txt");
  169. git.commit().setMessage("Delete Test.txt").setAll(true).call();
  170. git.checkout().setName("master").call();
  171. assertTrue(testFile.exists());
  172. // lock the file so it can't be deleted (in Windows, that is)
  173. fis = new FileInputStream(testFile);
  174. try {
  175. assertEquals(Status.NOT_TRIED, co.getResult().getStatus());
  176. co.setName("test").call();
  177. assertTrue(testFile.exists());
  178. assertEquals(Status.NONDELETED, co.getResult().getStatus());
  179. assertTrue(co.getResult().getUndeletedList().contains("Test.txt"));
  180. } finally {
  181. fis.close();
  182. }
  183. }
  184. @Test
  185. public void testCheckoutCommit() throws Exception {
  186. Ref result = git.checkout().setName(initialCommit.name()).call();
  187. assertEquals("[Test.txt, mode:100644, content:Hello world]",
  188. indexState(CONTENT));
  189. assertNull(result);
  190. assertEquals(initialCommit.name(), git.getRepository().getFullBranch());
  191. }
  192. @Test
  193. public void testCheckoutLightweightTag() throws Exception {
  194. git.tag().setAnnotated(false).setName("test-tag")
  195. .setObjectId(initialCommit).call();
  196. Ref result = git.checkout().setName("test-tag").call();
  197. assertNull(result);
  198. assertEquals(initialCommit.getId(), db.resolve(Constants.HEAD));
  199. assertHeadDetached();
  200. }
  201. @Test
  202. public void testCheckoutAnnotatedTag() throws Exception {
  203. git.tag().setAnnotated(true).setName("test-tag")
  204. .setObjectId(initialCommit).call();
  205. Ref result = git.checkout().setName("test-tag").call();
  206. assertNull(result);
  207. assertEquals(initialCommit.getId(), db.resolve(Constants.HEAD));
  208. assertHeadDetached();
  209. }
  210. @Test
  211. public void testCheckoutRemoteTrackingWithUpstream() throws Exception {
  212. Repository db2 = createRepositoryWithRemote();
  213. Git.wrap(db2).checkout().setCreateBranch(true).setName("test")
  214. .setStartPoint("origin/test")
  215. .setUpstreamMode(SetupUpstreamMode.TRACK).call();
  216. assertEquals("refs/heads/test", db2.getRef(Constants.HEAD).getTarget()
  217. .getName());
  218. StoredConfig config = db2.getConfig();
  219. assertEquals("origin", config.getString(
  220. ConfigConstants.CONFIG_BRANCH_SECTION, "test",
  221. ConfigConstants.CONFIG_KEY_REMOTE));
  222. assertEquals("refs/heads/test", config.getString(
  223. ConfigConstants.CONFIG_BRANCH_SECTION, "test",
  224. ConfigConstants.CONFIG_KEY_MERGE));
  225. }
  226. @Test
  227. public void testCheckoutRemoteTrackingWithoutLocalBranch() throws Exception {
  228. Repository db2 = createRepositoryWithRemote();
  229. // checkout remote tracking branch in second repository
  230. // (no local branches exist yet in second repository)
  231. Git.wrap(db2).checkout().setName("remotes/origin/test").call();
  232. assertEquals("[Test.txt, mode:100644, content:Some change]",
  233. indexState(db2, CONTENT));
  234. }
  235. @Test
  236. public void testCheckoutOfFileWithInexistentParentDir() throws Exception {
  237. File a = writeTrashFile("dir/a.txt", "A");
  238. writeTrashFile("dir/b.txt", "A");
  239. git.add().addFilepattern("dir/a.txt").addFilepattern("dir/b.txt")
  240. .call();
  241. git.commit().setMessage("Added dir").call();
  242. File dir = new File(db.getWorkTree(), "dir");
  243. FileUtils.delete(dir, FileUtils.RECURSIVE);
  244. git.checkout().addPath("dir/a.txt").call();
  245. assertTrue(a.exists());
  246. }
  247. @Test
  248. public void testCheckoutOfDirectoryShouldBeRecursive() throws Exception {
  249. File a = writeTrashFile("dir/a.txt", "A");
  250. File b = writeTrashFile("dir/sub/b.txt", "B");
  251. git.add().addFilepattern("dir").call();
  252. git.commit().setMessage("Added dir").call();
  253. write(a, "modified");
  254. write(b, "modified");
  255. git.checkout().addPath("dir").call();
  256. assertThat(read(a), is("A"));
  257. assertThat(read(b), is("B"));
  258. }
  259. @Test
  260. public void testCheckoutAllPaths() throws Exception {
  261. File a = writeTrashFile("dir/a.txt", "A");
  262. File b = writeTrashFile("dir/sub/b.txt", "B");
  263. git.add().addFilepattern("dir").call();
  264. git.commit().setMessage("Added dir").call();
  265. write(a, "modified");
  266. write(b, "modified");
  267. git.checkout().setAllPaths(true).call();
  268. assertThat(read(a), is("A"));
  269. assertThat(read(b), is("B"));
  270. }
  271. @Test
  272. public void testCheckoutWithStartPoint() throws Exception {
  273. File a = writeTrashFile("a.txt", "A");
  274. git.add().addFilepattern("a.txt").call();
  275. RevCommit first = git.commit().setMessage("Added a").call();
  276. write(a, "other");
  277. git.commit().setAll(true).setMessage("Other").call();
  278. git.checkout().setCreateBranch(true).setName("a")
  279. .setStartPoint(first.getId().getName()).call();
  280. assertThat(read(a), is("A"));
  281. }
  282. @Test
  283. public void testCheckoutWithStartPointOnlyCertainFiles() throws Exception {
  284. File a = writeTrashFile("a.txt", "A");
  285. File b = writeTrashFile("b.txt", "B");
  286. git.add().addFilepattern("a.txt").addFilepattern("b.txt").call();
  287. RevCommit first = git.commit().setMessage("First").call();
  288. write(a, "other");
  289. write(b, "other");
  290. git.commit().setAll(true).setMessage("Other").call();
  291. git.checkout().setCreateBranch(true).setName("a")
  292. .setStartPoint(first.getId().getName()).addPath("a.txt").call();
  293. assertThat(read(a), is("A"));
  294. assertThat(read(b), is("other"));
  295. }
  296. @Test
  297. public void testDetachedHeadOnCheckout() throws JGitInternalException,
  298. IOException, GitAPIException {
  299. CheckoutCommand co = git.checkout();
  300. co.setName("master").call();
  301. String commitId = db.getRef(Constants.MASTER).getObjectId().name();
  302. co = git.checkout();
  303. co.setName(commitId).call();
  304. assertHeadDetached();
  305. }
  306. @Test
  307. public void testUpdateSmudgedEntries() throws Exception {
  308. git.branchCreate().setName("test2").call();
  309. RefUpdate rup = db.updateRef(Constants.HEAD);
  310. rup.link("refs/heads/test2");
  311. File file = new File(db.getWorkTree(), "Test.txt");
  312. long size = file.length();
  313. long mTime = file.lastModified() - 5000L;
  314. assertTrue(file.setLastModified(mTime));
  315. DirCache cache = DirCache.lock(db.getIndexFile(), db.getFS());
  316. DirCacheEntry entry = cache.getEntry("Test.txt");
  317. assertNotNull(entry);
  318. entry.setLength(0);
  319. entry.setLastModified(0);
  320. cache.write();
  321. assertTrue(cache.commit());
  322. cache = DirCache.read(db.getIndexFile(), db.getFS());
  323. entry = cache.getEntry("Test.txt");
  324. assertNotNull(entry);
  325. assertEquals(0, entry.getLength());
  326. assertEquals(0, entry.getLastModified());
  327. db.getIndexFile().setLastModified(
  328. db.getIndexFile().lastModified() - 5000);
  329. assertNotNull(git.checkout().setName("test").call());
  330. cache = DirCache.read(db.getIndexFile(), db.getFS());
  331. entry = cache.getEntry("Test.txt");
  332. assertNotNull(entry);
  333. assertEquals(size, entry.getLength());
  334. assertEquals(mTime, entry.getLastModified());
  335. }
  336. @Test
  337. public void testCheckoutOrphanBranch() throws Exception {
  338. CheckoutCommand co = newOrphanBranchCommand();
  339. assertCheckoutRef(co.call());
  340. File HEAD = new File(trash, ".git/HEAD");
  341. String headRef = read(HEAD);
  342. assertEquals("ref: refs/heads/orphanbranch\n", headRef);
  343. assertEquals(2, trash.list().length);
  344. File heads = new File(trash, ".git/refs/heads");
  345. assertEquals(2, heads.listFiles().length);
  346. this.assertNoHead();
  347. this.assertRepositoryCondition(1);
  348. assertEquals(CheckoutResult.NOT_TRIED_RESULT, co.getResult());
  349. }
  350. private Repository createRepositoryWithRemote() throws IOException,
  351. URISyntaxException, MalformedURLException, GitAPIException,
  352. InvalidRemoteException, TransportException {
  353. // create second repository
  354. Repository db2 = createWorkRepository();
  355. Git git2 = new Git(db2);
  356. // setup the second repository to fetch from the first repository
  357. final StoredConfig config = db2.getConfig();
  358. RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
  359. URIish uri = new URIish(db.getDirectory().toURI().toURL());
  360. remoteConfig.addURI(uri);
  361. remoteConfig.update(config);
  362. config.save();
  363. // fetch from first repository
  364. RefSpec spec = new RefSpec("+refs/heads/*:refs/remotes/origin/*");
  365. git2.fetch().setRemote("origin").setRefSpecs(spec).call();
  366. return db2;
  367. }
  368. private CheckoutCommand newOrphanBranchCommand() {
  369. return git.checkout().setOrphan(true)
  370. .setName("orphanbranch");
  371. }
  372. private static void assertCheckoutRef(Ref ref) {
  373. assertNotNull(ref);
  374. assertEquals("refs/heads/orphanbranch", ref.getTarget().getName());
  375. }
  376. private void assertNoHead() throws IOException {
  377. assertNull(db.resolve("HEAD"));
  378. }
  379. private void assertHeadDetached() throws IOException {
  380. Ref head = db.getRef(Constants.HEAD);
  381. assertFalse(head.isSymbolic());
  382. assertSame(head, head.getTarget());
  383. }
  384. private void assertRepositoryCondition(int files) throws GitAPIException {
  385. org.eclipse.jgit.api.Status status = this.git.status().call();
  386. assertFalse(status.isClean());
  387. assertEquals(files, status.getAdded().size());
  388. }
  389. @Test
  390. public void testCreateOrphanBranchWithStartCommit() throws Exception {
  391. CheckoutCommand co = newOrphanBranchCommand();
  392. Ref ref = co.setStartPoint(initialCommit).call();
  393. assertCheckoutRef(ref);
  394. assertEquals(2, trash.list().length);
  395. this.assertNoHead();
  396. this.assertRepositoryCondition(1);
  397. }
  398. @Test
  399. public void testCreateOrphanBranchWithStartPoint() throws Exception {
  400. CheckoutCommand co = newOrphanBranchCommand();
  401. Ref ref = co.setStartPoint("HEAD^").call();
  402. assertCheckoutRef(ref);
  403. assertEquals(2, trash.list().length);
  404. this.assertNoHead();
  405. this.assertRepositoryCondition(1);
  406. }
  407. @Test
  408. public void testInvalidRefName() throws Exception {
  409. try {
  410. git.checkout().setOrphan(true).setName("../invalidname").call();
  411. fail("Should have failed");
  412. } catch (InvalidRefNameException e) {
  413. // except to hit here
  414. }
  415. }
  416. @Test
  417. public void testNullRefName() throws Exception {
  418. try {
  419. git.checkout().setOrphan(true).setName(null).call();
  420. fail("Should have failed");
  421. } catch (InvalidRefNameException e) {
  422. // except to hit here
  423. }
  424. }
  425. @Test
  426. public void testAlreadyExists() throws Exception {
  427. this.git.checkout().setCreateBranch(true).setName("orphanbranch")
  428. .call();
  429. this.git.checkout().setName("master").call();
  430. try {
  431. newOrphanBranchCommand().call();
  432. fail("Should have failed");
  433. } catch (RefAlreadyExistsException e) {
  434. // except to hit here
  435. }
  436. }
  437. }