Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

CheckoutCommandTest.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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.eclipse.jgit.lib.Constants.MASTER;
  46. import static org.eclipse.jgit.lib.Constants.R_HEADS;
  47. import static org.hamcrest.CoreMatchers.is;
  48. import static org.hamcrest.MatcherAssert.assertThat;
  49. import static org.junit.Assert.assertEquals;
  50. import static org.junit.Assert.assertFalse;
  51. import static org.junit.Assert.assertNotNull;
  52. import static org.junit.Assert.assertNull;
  53. import static org.junit.Assert.assertSame;
  54. import static org.junit.Assert.assertTrue;
  55. import static org.junit.Assert.fail;
  56. import java.io.File;
  57. import java.io.FileInputStream;
  58. import java.io.IOException;
  59. import java.net.MalformedURLException;
  60. import java.net.URISyntaxException;
  61. import org.eclipse.jgit.api.CheckoutResult.Status;
  62. import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
  63. import org.eclipse.jgit.api.errors.GitAPIException;
  64. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  65. import org.eclipse.jgit.api.errors.InvalidRemoteException;
  66. import org.eclipse.jgit.api.errors.JGitInternalException;
  67. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  68. import org.eclipse.jgit.api.errors.RefNotFoundException;
  69. import org.eclipse.jgit.api.errors.TransportException;
  70. import org.eclipse.jgit.dircache.DirCache;
  71. import org.eclipse.jgit.dircache.DirCacheEntry;
  72. import org.eclipse.jgit.junit.RepositoryTestCase;
  73. import org.eclipse.jgit.lib.ConfigConstants;
  74. import org.eclipse.jgit.lib.Constants;
  75. import org.eclipse.jgit.lib.Ref;
  76. import org.eclipse.jgit.lib.RefUpdate;
  77. import org.eclipse.jgit.lib.Repository;
  78. import org.eclipse.jgit.lib.StoredConfig;
  79. import org.eclipse.jgit.revwalk.RevCommit;
  80. import org.eclipse.jgit.storage.file.FileBasedConfig;
  81. import org.eclipse.jgit.transport.RefSpec;
  82. import org.eclipse.jgit.transport.RemoteConfig;
  83. import org.eclipse.jgit.transport.URIish;
  84. import org.eclipse.jgit.util.FileUtils;
  85. import org.junit.Before;
  86. import org.junit.Test;
  87. public class CheckoutCommandTest extends RepositoryTestCase {
  88. private Git git;
  89. RevCommit initialCommit;
  90. RevCommit secondCommit;
  91. @Override
  92. @Before
  93. public void setUp() throws Exception {
  94. super.setUp();
  95. git = new Git(db);
  96. // commit something
  97. writeTrashFile("Test.txt", "Hello world");
  98. git.add().addFilepattern("Test.txt").call();
  99. initialCommit = git.commit().setMessage("Initial commit").call();
  100. // create a master branch and switch to it
  101. git.branchCreate().setName("test").call();
  102. RefUpdate rup = db.updateRef(Constants.HEAD);
  103. rup.link("refs/heads/test");
  104. // commit something on the test branch
  105. writeTrashFile("Test.txt", "Some change");
  106. git.add().addFilepattern("Test.txt").call();
  107. secondCommit = git.commit().setMessage("Second commit").call();
  108. }
  109. @Test
  110. public void testSimpleCheckout() throws Exception {
  111. git.checkout().setName("test").call();
  112. }
  113. @Test
  114. public void testCheckout() throws Exception {
  115. git.checkout().setName("test").call();
  116. assertEquals("[Test.txt, mode:100644, content:Some change]",
  117. indexState(CONTENT));
  118. Ref result = git.checkout().setName("master").call();
  119. assertEquals("[Test.txt, mode:100644, content:Hello world]",
  120. indexState(CONTENT));
  121. assertEquals("refs/heads/master", result.getName());
  122. assertEquals("refs/heads/master", git.getRepository().getFullBranch());
  123. }
  124. @Test
  125. public void testCreateBranchOnCheckout() throws Exception {
  126. git.checkout().setCreateBranch(true).setName("test2").call();
  127. assertNotNull(db.exactRef("refs/heads/test2"));
  128. }
  129. @Test
  130. public void testCheckoutToNonExistingBranch() throws GitAPIException {
  131. try {
  132. git.checkout().setName("badbranch").call();
  133. fail("Should have failed");
  134. } catch (RefNotFoundException e) {
  135. // except to hit here
  136. }
  137. }
  138. @Test
  139. public void testCheckoutWithConflict() {
  140. CheckoutCommand co = git.checkout();
  141. try {
  142. writeTrashFile("Test.txt", "Another change");
  143. assertEquals(Status.NOT_TRIED, co.getResult().getStatus());
  144. co.setName("master").call();
  145. fail("Should have failed");
  146. } catch (Exception e) {
  147. assertEquals(Status.CONFLICTS, co.getResult().getStatus());
  148. assertTrue(co.getResult().getConflictList().contains("Test.txt"));
  149. }
  150. }
  151. @Test
  152. public void testCheckoutWithNonDeletedFiles() throws Exception {
  153. File testFile = writeTrashFile("temp", "");
  154. FileInputStream fis = new FileInputStream(testFile);
  155. try {
  156. FileUtils.delete(testFile);
  157. return;
  158. } catch (IOException e) {
  159. // the test makes only sense if deletion of
  160. // a file with open stream fails
  161. } finally {
  162. fis.close();
  163. }
  164. FileUtils.delete(testFile);
  165. CheckoutCommand co = git.checkout();
  166. // delete Test.txt in branch test
  167. testFile = new File(db.getWorkTree(), "Test.txt");
  168. assertTrue(testFile.exists());
  169. FileUtils.delete(testFile);
  170. assertFalse(testFile.exists());
  171. git.add().addFilepattern("Test.txt");
  172. git.commit().setMessage("Delete Test.txt").setAll(true).call();
  173. git.checkout().setName("master").call();
  174. assertTrue(testFile.exists());
  175. // lock the file so it can't be deleted (in Windows, that is)
  176. fis = new FileInputStream(testFile);
  177. try {
  178. assertEquals(Status.NOT_TRIED, co.getResult().getStatus());
  179. co.setName("test").call();
  180. assertTrue(testFile.exists());
  181. assertEquals(Status.NONDELETED, co.getResult().getStatus());
  182. assertTrue(co.getResult().getUndeletedList().contains("Test.txt"));
  183. } finally {
  184. fis.close();
  185. }
  186. }
  187. @Test
  188. public void testCheckoutCommit() throws Exception {
  189. Ref result = git.checkout().setName(initialCommit.name()).call();
  190. assertEquals("[Test.txt, mode:100644, content:Hello world]",
  191. indexState(CONTENT));
  192. assertNull(result);
  193. assertEquals(initialCommit.name(), git.getRepository().getFullBranch());
  194. }
  195. @Test
  196. public void testCheckoutLightweightTag() throws Exception {
  197. git.tag().setAnnotated(false).setName("test-tag")
  198. .setObjectId(initialCommit).call();
  199. Ref result = git.checkout().setName("test-tag").call();
  200. assertNull(result);
  201. assertEquals(initialCommit.getId(), db.resolve(Constants.HEAD));
  202. assertHeadDetached();
  203. }
  204. @Test
  205. public void testCheckoutAnnotatedTag() throws Exception {
  206. git.tag().setAnnotated(true).setName("test-tag")
  207. .setObjectId(initialCommit).call();
  208. Ref result = git.checkout().setName("test-tag").call();
  209. assertNull(result);
  210. assertEquals(initialCommit.getId(), db.resolve(Constants.HEAD));
  211. assertHeadDetached();
  212. }
  213. @Test
  214. public void testCheckoutRemoteTrackingWithUpstream() throws Exception {
  215. Repository db2 = createRepositoryWithRemote();
  216. Git.wrap(db2).checkout().setCreateBranch(true).setName("test")
  217. .setStartPoint("origin/test")
  218. .setUpstreamMode(SetupUpstreamMode.TRACK).call();
  219. assertEquals("refs/heads/test",
  220. db2.exactRef(Constants.HEAD).getTarget().getName());
  221. StoredConfig config = db2.getConfig();
  222. assertEquals("origin", config.getString(
  223. ConfigConstants.CONFIG_BRANCH_SECTION, "test",
  224. ConfigConstants.CONFIG_KEY_REMOTE));
  225. assertEquals("refs/heads/test", config.getString(
  226. ConfigConstants.CONFIG_BRANCH_SECTION, "test",
  227. ConfigConstants.CONFIG_KEY_MERGE));
  228. }
  229. @Test
  230. public void testCheckoutRemoteTrackingWithoutLocalBranch() throws Exception {
  231. Repository db2 = createRepositoryWithRemote();
  232. // checkout remote tracking branch in second repository
  233. // (no local branches exist yet in second repository)
  234. Git.wrap(db2).checkout().setName("remotes/origin/test").call();
  235. assertEquals("[Test.txt, mode:100644, content:Some change]",
  236. indexState(db2, CONTENT));
  237. }
  238. @Test
  239. public void testCheckoutOfFileWithInexistentParentDir() throws Exception {
  240. File a = writeTrashFile("dir/a.txt", "A");
  241. writeTrashFile("dir/b.txt", "A");
  242. git.add().addFilepattern("dir/a.txt").addFilepattern("dir/b.txt")
  243. .call();
  244. git.commit().setMessage("Added dir").call();
  245. File dir = new File(db.getWorkTree(), "dir");
  246. FileUtils.delete(dir, FileUtils.RECURSIVE);
  247. git.checkout().addPath("dir/a.txt").call();
  248. assertTrue(a.exists());
  249. }
  250. @Test
  251. public void testCheckoutOfDirectoryShouldBeRecursive() throws Exception {
  252. File a = writeTrashFile("dir/a.txt", "A");
  253. File b = writeTrashFile("dir/sub/b.txt", "B");
  254. git.add().addFilepattern("dir").call();
  255. git.commit().setMessage("Added dir").call();
  256. write(a, "modified");
  257. write(b, "modified");
  258. git.checkout().addPath("dir").call();
  259. assertThat(read(a), is("A"));
  260. assertThat(read(b), is("B"));
  261. }
  262. @Test
  263. public void testCheckoutAllPaths() throws Exception {
  264. File a = writeTrashFile("dir/a.txt", "A");
  265. File b = writeTrashFile("dir/sub/b.txt", "B");
  266. git.add().addFilepattern("dir").call();
  267. git.commit().setMessage("Added dir").call();
  268. write(a, "modified");
  269. write(b, "modified");
  270. git.checkout().setAllPaths(true).call();
  271. assertThat(read(a), is("A"));
  272. assertThat(read(b), is("B"));
  273. }
  274. @Test
  275. public void testCheckoutWithStartPoint() throws Exception {
  276. File a = writeTrashFile("a.txt", "A");
  277. git.add().addFilepattern("a.txt").call();
  278. RevCommit first = git.commit().setMessage("Added a").call();
  279. write(a, "other");
  280. git.commit().setAll(true).setMessage("Other").call();
  281. git.checkout().setCreateBranch(true).setName("a")
  282. .setStartPoint(first.getId().getName()).call();
  283. assertThat(read(a), is("A"));
  284. }
  285. @Test
  286. public void testCheckoutWithStartPointOnlyCertainFiles() throws Exception {
  287. File a = writeTrashFile("a.txt", "A");
  288. File b = writeTrashFile("b.txt", "B");
  289. git.add().addFilepattern("a.txt").addFilepattern("b.txt").call();
  290. RevCommit first = git.commit().setMessage("First").call();
  291. write(a, "other");
  292. write(b, "other");
  293. git.commit().setAll(true).setMessage("Other").call();
  294. git.checkout().setCreateBranch(true).setName("a")
  295. .setStartPoint(first.getId().getName()).addPath("a.txt").call();
  296. assertThat(read(a), is("A"));
  297. assertThat(read(b), is("other"));
  298. }
  299. @Test
  300. public void testDetachedHeadOnCheckout() throws JGitInternalException,
  301. IOException, GitAPIException {
  302. CheckoutCommand co = git.checkout();
  303. co.setName("master").call();
  304. String commitId = db.exactRef(R_HEADS + MASTER).getObjectId().name();
  305. co = git.checkout();
  306. co.setName(commitId).call();
  307. assertHeadDetached();
  308. }
  309. @Test
  310. public void testUpdateSmudgedEntries() throws Exception {
  311. git.branchCreate().setName("test2").call();
  312. RefUpdate rup = db.updateRef(Constants.HEAD);
  313. rup.link("refs/heads/test2");
  314. File file = new File(db.getWorkTree(), "Test.txt");
  315. long size = file.length();
  316. long mTime = file.lastModified() - 5000L;
  317. assertTrue(file.setLastModified(mTime));
  318. DirCache cache = DirCache.lock(db.getIndexFile(), db.getFS());
  319. DirCacheEntry entry = cache.getEntry("Test.txt");
  320. assertNotNull(entry);
  321. entry.setLength(0);
  322. entry.setLastModified(0);
  323. cache.write();
  324. assertTrue(cache.commit());
  325. cache = DirCache.read(db.getIndexFile(), db.getFS());
  326. entry = cache.getEntry("Test.txt");
  327. assertNotNull(entry);
  328. assertEquals(0, entry.getLength());
  329. assertEquals(0, entry.getLastModified());
  330. db.getIndexFile().setLastModified(
  331. db.getIndexFile().lastModified() - 5000);
  332. assertNotNull(git.checkout().setName("test").call());
  333. cache = DirCache.read(db.getIndexFile(), db.getFS());
  334. entry = cache.getEntry("Test.txt");
  335. assertNotNull(entry);
  336. assertEquals(size, entry.getLength());
  337. assertEquals(mTime, entry.getLastModified());
  338. }
  339. @Test
  340. public void testCheckoutOrphanBranch() throws Exception {
  341. CheckoutCommand co = newOrphanBranchCommand();
  342. assertCheckoutRef(co.call());
  343. File HEAD = new File(trash, ".git/HEAD");
  344. String headRef = read(HEAD);
  345. assertEquals("ref: refs/heads/orphanbranch\n", headRef);
  346. assertEquals(2, trash.list().length);
  347. File heads = new File(trash, ".git/refs/heads");
  348. assertEquals(2, heads.listFiles().length);
  349. this.assertNoHead();
  350. this.assertRepositoryCondition(1);
  351. assertEquals(CheckoutResult.NOT_TRIED_RESULT, co.getResult());
  352. }
  353. private Repository createRepositoryWithRemote() throws IOException,
  354. URISyntaxException, MalformedURLException, GitAPIException,
  355. InvalidRemoteException, TransportException {
  356. // create second repository
  357. Repository db2 = createWorkRepository();
  358. Git git2 = new Git(db2);
  359. // setup the second repository to fetch from the first repository
  360. final StoredConfig config = db2.getConfig();
  361. RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
  362. URIish uri = new URIish(db.getDirectory().toURI().toURL());
  363. remoteConfig.addURI(uri);
  364. remoteConfig.update(config);
  365. config.save();
  366. // fetch from first repository
  367. RefSpec spec = new RefSpec("+refs/heads/*:refs/remotes/origin/*");
  368. git2.fetch().setRemote("origin").setRefSpecs(spec).call();
  369. return db2;
  370. }
  371. private CheckoutCommand newOrphanBranchCommand() {
  372. return git.checkout().setOrphan(true)
  373. .setName("orphanbranch");
  374. }
  375. private static void assertCheckoutRef(Ref ref) {
  376. assertNotNull(ref);
  377. assertEquals("refs/heads/orphanbranch", ref.getTarget().getName());
  378. }
  379. private void assertNoHead() throws IOException {
  380. assertNull(db.resolve("HEAD"));
  381. }
  382. private void assertHeadDetached() throws IOException {
  383. Ref head = db.exactRef(Constants.HEAD);
  384. assertFalse(head.isSymbolic());
  385. assertSame(head, head.getTarget());
  386. }
  387. private void assertRepositoryCondition(int files) throws GitAPIException {
  388. org.eclipse.jgit.api.Status status = this.git.status().call();
  389. assertFalse(status.isClean());
  390. assertEquals(files, status.getAdded().size());
  391. }
  392. @Test
  393. public void testCreateOrphanBranchWithStartCommit() throws Exception {
  394. CheckoutCommand co = newOrphanBranchCommand();
  395. Ref ref = co.setStartPoint(initialCommit).call();
  396. assertCheckoutRef(ref);
  397. assertEquals(2, trash.list().length);
  398. this.assertNoHead();
  399. this.assertRepositoryCondition(1);
  400. }
  401. @Test
  402. public void testCreateOrphanBranchWithStartPoint() throws Exception {
  403. CheckoutCommand co = newOrphanBranchCommand();
  404. Ref ref = co.setStartPoint("HEAD^").call();
  405. assertCheckoutRef(ref);
  406. assertEquals(2, trash.list().length);
  407. this.assertNoHead();
  408. this.assertRepositoryCondition(1);
  409. }
  410. @Test
  411. public void testInvalidRefName() throws Exception {
  412. try {
  413. git.checkout().setOrphan(true).setName("../invalidname").call();
  414. fail("Should have failed");
  415. } catch (InvalidRefNameException e) {
  416. // except to hit here
  417. }
  418. }
  419. @Test
  420. public void testNullRefName() throws Exception {
  421. try {
  422. git.checkout().setOrphan(true).setName(null).call();
  423. fail("Should have failed");
  424. } catch (InvalidRefNameException e) {
  425. // except to hit here
  426. }
  427. }
  428. @Test
  429. public void testAlreadyExists() throws Exception {
  430. this.git.checkout().setCreateBranch(true).setName("orphanbranch")
  431. .call();
  432. this.git.checkout().setName("master").call();
  433. try {
  434. newOrphanBranchCommand().call();
  435. fail("Should have failed");
  436. } catch (RefAlreadyExistsException e) {
  437. // except to hit here
  438. }
  439. }
  440. // TODO: write a faster test which depends less on characteristics of
  441. // underlying filesystem/OS.
  442. @Test
  443. public void testCheckoutAutoCrlfTrue() throws Exception {
  444. int nrOfAutoCrlfTestFiles = 200;
  445. FileBasedConfig c = db.getConfig();
  446. c.setString("core", null, "autocrlf", "true");
  447. c.save();
  448. AddCommand add = git.add();
  449. for (int i = 100; i < 100 + nrOfAutoCrlfTestFiles; i++) {
  450. writeTrashFile("Test_" + i + ".txt", "Hello " + i
  451. + " world\nX\nYU\nJK\n");
  452. add.addFilepattern("Test_" + i + ".txt");
  453. }
  454. fsTick(null);
  455. add.call();
  456. RevCommit c1 = git.commit().setMessage("add some lines").call();
  457. add = git.add();
  458. for (int i = 100; i < 100 + nrOfAutoCrlfTestFiles; i++) {
  459. writeTrashFile("Test_" + i + ".txt", "Hello " + i
  460. + " world\nX\nY\n");
  461. add.addFilepattern("Test_" + i + ".txt");
  462. }
  463. fsTick(null);
  464. add.call();
  465. git.commit().setMessage("add more").call();
  466. git.checkout().setName(c1.getName()).call();
  467. boolean foundUnsmudged = false;
  468. DirCache dc = db.readDirCache();
  469. for (int i = 100; i < 100 + nrOfAutoCrlfTestFiles; i++) {
  470. DirCacheEntry entry = dc.getEntry(
  471. "Test_" + i + ".txt");
  472. if (!entry.isSmudged()) {
  473. foundUnsmudged = true;
  474. assertEquals("unexpected file length in git index", 28,
  475. entry.getLength());
  476. }
  477. }
  478. org.junit.Assume.assumeTrue(foundUnsmudged);
  479. }
  480. }