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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. /*
  2. * Copyright (C) 2010, Chris Aniszczyk <caniszczyk@gmail.com>
  3. * Copyright (C) 2011, Matthias Sohn <matthias.sohn@sap.com> and others
  4. *
  5. * This program and the accompanying materials are made available under the
  6. * terms of the Eclipse Distribution License v. 1.0 which is available at
  7. * https://www.eclipse.org/org/documents/edl-v10.php.
  8. *
  9. * SPDX-License-Identifier: BSD-3-Clause
  10. */
  11. package org.eclipse.jgit.api;
  12. import static java.time.Instant.EPOCH;
  13. import static org.eclipse.jgit.lib.Constants.MASTER;
  14. import static org.eclipse.jgit.lib.Constants.R_HEADS;
  15. import static org.hamcrest.CoreMatchers.is;
  16. import static org.hamcrest.MatcherAssert.assertThat;
  17. import static org.junit.Assert.assertEquals;
  18. import static org.junit.Assert.assertFalse;
  19. import static org.junit.Assert.assertNotNull;
  20. import static org.junit.Assert.assertNull;
  21. import static org.junit.Assert.assertSame;
  22. import static org.junit.Assert.assertTrue;
  23. import static org.junit.Assert.fail;
  24. import java.io.File;
  25. import java.io.FileInputStream;
  26. import java.io.IOException;
  27. import java.net.MalformedURLException;
  28. import java.net.URISyntaxException;
  29. import java.nio.file.Files;
  30. import java.nio.file.attribute.FileTime;
  31. import java.time.Instant;
  32. import org.eclipse.jgit.api.CheckoutResult.Status;
  33. import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
  34. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  35. import org.eclipse.jgit.api.errors.GitAPIException;
  36. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  37. import org.eclipse.jgit.api.errors.InvalidRemoteException;
  38. import org.eclipse.jgit.api.errors.JGitInternalException;
  39. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  40. import org.eclipse.jgit.api.errors.RefNotFoundException;
  41. import org.eclipse.jgit.api.errors.TransportException;
  42. import org.eclipse.jgit.dircache.DirCache;
  43. import org.eclipse.jgit.dircache.DirCacheEntry;
  44. import org.eclipse.jgit.junit.JGitTestUtil;
  45. import org.eclipse.jgit.junit.RepositoryTestCase;
  46. import org.eclipse.jgit.junit.time.TimeUtil;
  47. import org.eclipse.jgit.lfs.BuiltinLFS;
  48. import org.eclipse.jgit.lib.ConfigConstants;
  49. import org.eclipse.jgit.lib.Constants;
  50. import org.eclipse.jgit.lib.Ref;
  51. import org.eclipse.jgit.lib.RefUpdate;
  52. import org.eclipse.jgit.lib.Repository;
  53. import org.eclipse.jgit.lib.Sets;
  54. import org.eclipse.jgit.lib.StoredConfig;
  55. import org.eclipse.jgit.revwalk.RevCommit;
  56. import org.eclipse.jgit.storage.file.FileBasedConfig;
  57. import org.eclipse.jgit.transport.RemoteConfig;
  58. import org.eclipse.jgit.transport.URIish;
  59. import org.eclipse.jgit.util.FS;
  60. import org.eclipse.jgit.util.FileUtils;
  61. import org.eclipse.jgit.util.SystemReader;
  62. import org.junit.Before;
  63. import org.junit.Test;
  64. public class CheckoutCommandTest extends RepositoryTestCase {
  65. private Git git;
  66. RevCommit initialCommit;
  67. RevCommit secondCommit;
  68. @Override
  69. @Before
  70. public void setUp() throws Exception {
  71. BuiltinLFS.register();
  72. super.setUp();
  73. git = new Git(db);
  74. // commit something
  75. writeTrashFile("Test.txt", "Hello world");
  76. git.add().addFilepattern("Test.txt").call();
  77. initialCommit = git.commit().setMessage("Initial commit").call();
  78. // create a test branch and switch to it
  79. git.branchCreate().setName("test").call();
  80. RefUpdate rup = db.updateRef(Constants.HEAD);
  81. rup.link("refs/heads/test");
  82. // commit something on the test branch
  83. writeTrashFile("Test.txt", "Some change");
  84. git.add().addFilepattern("Test.txt").call();
  85. secondCommit = git.commit().setMessage("Second commit").call();
  86. }
  87. @Test
  88. public void testSimpleCheckout() throws Exception {
  89. git.checkout().setName("test").call();
  90. }
  91. @Test
  92. public void testCheckout() throws Exception {
  93. git.checkout().setName("test").call();
  94. assertEquals("[Test.txt, mode:100644, content:Some change]",
  95. indexState(CONTENT));
  96. Ref result = git.checkout().setName("master").call();
  97. assertEquals("[Test.txt, mode:100644, content:Hello world]",
  98. indexState(CONTENT));
  99. assertEquals("refs/heads/master", result.getName());
  100. assertEquals("refs/heads/master", git.getRepository().getFullBranch());
  101. }
  102. @Test
  103. public void testCheckoutForced() throws Exception {
  104. writeTrashFile("Test.txt", "Garbage");
  105. try {
  106. git.checkout().setName("master").call().getObjectId();
  107. fail("Expected CheckoutConflictException didn't occur");
  108. } catch (CheckoutConflictException e) {
  109. // Expected
  110. }
  111. assertEquals(initialCommit.getId(), git.checkout().setName("master")
  112. .setForced(true).call().getObjectId());
  113. }
  114. @Test
  115. public void testCheckoutForced_deleteFileAndRestore() throws Exception {
  116. File testFile = new File(db.getWorkTree(), "Test.txt");
  117. assertTrue(testFile.exists());
  118. assertEquals("test", git.getRepository().getBranch());
  119. FileUtils.delete(testFile);
  120. assertFalse(testFile.exists());
  121. // Switch from "test" to "master".
  122. assertEquals(initialCommit.getId(), git.checkout().setName("master")
  123. .setForced(true).call().getObjectId());
  124. assertTrue(testFile.exists());
  125. assertEquals("master", git.getRepository().getBranch());
  126. FileUtils.delete(testFile);
  127. assertFalse(testFile.exists());
  128. // Stay in current branch.
  129. assertEquals(initialCommit.getId(), git.checkout().setName("master")
  130. .setForced(true).call().getObjectId());
  131. assertTrue(testFile.exists());
  132. }
  133. @Test
  134. public void testCheckoutForcedNoChangeNotInIndex() throws Exception {
  135. git.checkout().setCreateBranch(true).setName("test2").call();
  136. File f = writeTrashFile("NewFile.txt", "New file");
  137. git.add().addFilepattern("NewFile.txt").call();
  138. git.commit().setMessage("New file created").call();
  139. git.checkout().setName("test").call();
  140. assertFalse("NewFile.txt should not exist", f.exists());
  141. writeTrashFile("NewFile.txt", "New file");
  142. git.add().addFilepattern("NewFile.txt").call();
  143. git.commit().setMessage("New file created again with same content")
  144. .call();
  145. // Now remove the file from the index only. So it exists in both
  146. // commits, and in the working tree, but not in the index.
  147. git.rm().addFilepattern("NewFile.txt").setCached(true).call();
  148. assertTrue("NewFile.txt should exist", f.isFile());
  149. git.checkout().setForced(true).setName("test2").call();
  150. assertTrue("NewFile.txt should exist", f.isFile());
  151. assertEquals(Constants.R_HEADS + "test2", git.getRepository()
  152. .exactRef(Constants.HEAD).getTarget().getName());
  153. assertTrue("Force checkout should have undone git rm --cached",
  154. git.status().call().isClean());
  155. }
  156. @Test
  157. public void testCheckoutNoChangeNotInIndex() throws Exception {
  158. git.checkout().setCreateBranch(true).setName("test2").call();
  159. File f = writeTrashFile("NewFile.txt", "New file");
  160. git.add().addFilepattern("NewFile.txt").call();
  161. git.commit().setMessage("New file created").call();
  162. git.checkout().setName("test").call();
  163. assertFalse("NewFile.txt should not exist", f.exists());
  164. writeTrashFile("NewFile.txt", "New file");
  165. git.add().addFilepattern("NewFile.txt").call();
  166. git.commit().setMessage("New file created again with same content")
  167. .call();
  168. // Now remove the file from the index only. So it exists in both
  169. // commits, and in the working tree, but not in the index.
  170. git.rm().addFilepattern("NewFile.txt").setCached(true).call();
  171. assertTrue("NewFile.txt should exist", f.isFile());
  172. git.checkout().setName("test2").call();
  173. assertTrue("NewFile.txt should exist", f.isFile());
  174. assertEquals(Constants.R_HEADS + "test2", git.getRepository()
  175. .exactRef(Constants.HEAD).getTarget().getName());
  176. org.eclipse.jgit.api.Status status = git.status().call();
  177. assertEquals("[NewFile.txt]", status.getRemoved().toString());
  178. assertEquals("[NewFile.txt]", status.getUntracked().toString());
  179. }
  180. @Test
  181. public void testCreateBranchOnCheckout() throws Exception {
  182. git.checkout().setCreateBranch(true).setName("test2").call();
  183. assertNotNull(db.exactRef("refs/heads/test2"));
  184. }
  185. @Test
  186. public void testCheckoutToNonExistingBranch() throws GitAPIException {
  187. try {
  188. git.checkout().setName("badbranch").call();
  189. fail("Should have failed");
  190. } catch (RefNotFoundException e) {
  191. // except to hit here
  192. }
  193. }
  194. @Test
  195. public void testCheckoutWithConflict() throws Exception {
  196. CheckoutCommand co = git.checkout();
  197. try {
  198. writeTrashFile("Test.txt", "Another change");
  199. assertEquals(Status.NOT_TRIED, co.getResult().getStatus());
  200. co.setName("master").call();
  201. fail("Should have failed");
  202. } catch (Exception e) {
  203. assertEquals(Status.CONFLICTS, co.getResult().getStatus());
  204. assertTrue(co.getResult().getConflictList().contains("Test.txt"));
  205. }
  206. git.checkout().setName("master").setForced(true).call();
  207. assertThat(read("Test.txt"), is("Hello world"));
  208. }
  209. @Test
  210. public void testCheckoutWithNonDeletedFiles() throws Exception {
  211. File testFile = writeTrashFile("temp", "");
  212. try (FileInputStream fis = new FileInputStream(testFile)) {
  213. FileUtils.delete(testFile);
  214. return;
  215. } catch (IOException e) {
  216. // the test makes only sense if deletion of
  217. // a file with open stream fails
  218. }
  219. FileUtils.delete(testFile);
  220. CheckoutCommand co = git.checkout();
  221. // delete Test.txt in branch test
  222. testFile = new File(db.getWorkTree(), "Test.txt");
  223. assertTrue(testFile.exists());
  224. FileUtils.delete(testFile);
  225. assertFalse(testFile.exists());
  226. git.add().addFilepattern("Test.txt");
  227. git.commit().setMessage("Delete Test.txt").setAll(true).call();
  228. git.checkout().setName("master").call();
  229. assertTrue(testFile.exists());
  230. // lock the file so it can't be deleted (in Windows, that is)
  231. try (FileInputStream fis = new FileInputStream(testFile)) {
  232. assertEquals(Status.NOT_TRIED, co.getResult().getStatus());
  233. co.setName("test").call();
  234. assertTrue(testFile.exists());
  235. assertEquals(Status.NONDELETED, co.getResult().getStatus());
  236. assertTrue(co.getResult().getUndeletedList().contains("Test.txt"));
  237. }
  238. }
  239. @Test
  240. public void testCheckoutCommit() throws Exception {
  241. Ref result = git.checkout().setName(initialCommit.name()).call();
  242. assertEquals("[Test.txt, mode:100644, content:Hello world]",
  243. indexState(CONTENT));
  244. assertNull(result);
  245. assertEquals(initialCommit.name(), git.getRepository().getFullBranch());
  246. }
  247. @Test
  248. public void testCheckoutLightweightTag() throws Exception {
  249. git.tag().setAnnotated(false).setName("test-tag")
  250. .setObjectId(initialCommit).call();
  251. Ref result = git.checkout().setName("test-tag").call();
  252. assertNull(result);
  253. assertEquals(initialCommit.getId(), db.resolve(Constants.HEAD));
  254. assertHeadDetached();
  255. }
  256. @Test
  257. public void testCheckoutAnnotatedTag() throws Exception {
  258. git.tag().setAnnotated(true).setName("test-tag")
  259. .setObjectId(initialCommit).call();
  260. Ref result = git.checkout().setName("test-tag").call();
  261. assertNull(result);
  262. assertEquals(initialCommit.getId(), db.resolve(Constants.HEAD));
  263. assertHeadDetached();
  264. }
  265. @Test
  266. public void testCheckoutRemoteTrackingWithUpstream() throws Exception {
  267. Repository db2 = createRepositoryWithRemote();
  268. Git.wrap(db2).checkout().setCreateBranch(true).setName("test")
  269. .setStartPoint("origin/test")
  270. .setUpstreamMode(SetupUpstreamMode.TRACK).call();
  271. assertEquals("refs/heads/test",
  272. db2.exactRef(Constants.HEAD).getTarget().getName());
  273. StoredConfig config = db2.getConfig();
  274. assertEquals("origin", config.getString(
  275. ConfigConstants.CONFIG_BRANCH_SECTION, "test",
  276. ConfigConstants.CONFIG_KEY_REMOTE));
  277. assertEquals("refs/heads/test", config.getString(
  278. ConfigConstants.CONFIG_BRANCH_SECTION, "test",
  279. ConfigConstants.CONFIG_KEY_MERGE));
  280. }
  281. @Test
  282. public void testCheckoutRemoteTrackingWithoutLocalBranch() throws Exception {
  283. Repository db2 = createRepositoryWithRemote();
  284. // checkout remote tracking branch in second repository
  285. // (no local branches exist yet in second repository)
  286. Git.wrap(db2).checkout().setName("remotes/origin/test").call();
  287. assertEquals("[Test.txt, mode:100644, content:Some change]",
  288. indexState(db2, CONTENT));
  289. }
  290. @Test
  291. public void testCheckoutOfFileWithInexistentParentDir() throws Exception {
  292. File a = writeTrashFile("dir/a.txt", "A");
  293. writeTrashFile("dir/b.txt", "A");
  294. git.add().addFilepattern("dir/a.txt").addFilepattern("dir/b.txt")
  295. .call();
  296. git.commit().setMessage("Added dir").call();
  297. File dir = new File(db.getWorkTree(), "dir");
  298. FileUtils.delete(dir, FileUtils.RECURSIVE);
  299. git.checkout().addPath("dir/a.txt").call();
  300. assertTrue(a.exists());
  301. }
  302. @Test
  303. public void testCheckoutOfDirectoryShouldBeRecursive() throws Exception {
  304. File a = writeTrashFile("dir/a.txt", "A");
  305. File b = writeTrashFile("dir/sub/b.txt", "B");
  306. git.add().addFilepattern("dir").call();
  307. git.commit().setMessage("Added dir").call();
  308. write(a, "modified");
  309. write(b, "modified");
  310. git.checkout().addPath("dir").call();
  311. assertThat(read(a), is("A"));
  312. assertThat(read(b), is("B"));
  313. }
  314. @Test
  315. public void testCheckoutAllPaths() throws Exception {
  316. File a = writeTrashFile("dir/a.txt", "A");
  317. File b = writeTrashFile("dir/sub/b.txt", "B");
  318. git.add().addFilepattern("dir").call();
  319. git.commit().setMessage("Added dir").call();
  320. write(a, "modified");
  321. write(b, "modified");
  322. git.checkout().setAllPaths(true).call();
  323. assertThat(read(a), is("A"));
  324. assertThat(read(b), is("B"));
  325. }
  326. @Test
  327. public void testCheckoutWithStartPoint() throws Exception {
  328. File a = writeTrashFile("a.txt", "A");
  329. git.add().addFilepattern("a.txt").call();
  330. RevCommit first = git.commit().setMessage("Added a").call();
  331. write(a, "other");
  332. git.commit().setAll(true).setMessage("Other").call();
  333. git.checkout().setCreateBranch(true).setName("a")
  334. .setStartPoint(first.getId().getName()).call();
  335. assertThat(read(a), is("A"));
  336. }
  337. @Test
  338. public void testCheckoutWithStartPointOnlyCertainFiles() throws Exception {
  339. File a = writeTrashFile("a.txt", "A");
  340. File b = writeTrashFile("b.txt", "B");
  341. git.add().addFilepattern("a.txt").addFilepattern("b.txt").call();
  342. RevCommit first = git.commit().setMessage("First").call();
  343. write(a, "other");
  344. write(b, "other");
  345. git.commit().setAll(true).setMessage("Other").call();
  346. git.checkout().setCreateBranch(true).setName("a")
  347. .setStartPoint(first.getId().getName()).addPath("a.txt").call();
  348. assertThat(read(a), is("A"));
  349. assertThat(read(b), is("other"));
  350. }
  351. @Test
  352. public void testDetachedHeadOnCheckout() throws JGitInternalException,
  353. IOException, GitAPIException {
  354. CheckoutCommand co = git.checkout();
  355. co.setName("master").call();
  356. String commitId = db.exactRef(R_HEADS + MASTER).getObjectId().name();
  357. co = git.checkout();
  358. co.setName(commitId).call();
  359. assertHeadDetached();
  360. }
  361. @Test
  362. public void testUpdateSmudgedEntries() throws Exception {
  363. git.branchCreate().setName("test2").call();
  364. RefUpdate rup = db.updateRef(Constants.HEAD);
  365. rup.link("refs/heads/test2");
  366. File file = new File(db.getWorkTree(), "Test.txt");
  367. long size = file.length();
  368. Instant mTime = TimeUtil.setLastModifiedWithOffset(file.toPath(),
  369. -5000L);
  370. DirCache cache = DirCache.lock(db.getIndexFile(), db.getFS());
  371. DirCacheEntry entry = cache.getEntry("Test.txt");
  372. assertNotNull(entry);
  373. entry.setLength(0);
  374. entry.setLastModified(EPOCH);
  375. cache.write();
  376. assertTrue(cache.commit());
  377. cache = DirCache.read(db.getIndexFile(), db.getFS());
  378. entry = cache.getEntry("Test.txt");
  379. assertNotNull(entry);
  380. assertEquals(0, entry.getLength());
  381. assertEquals(EPOCH, entry.getLastModifiedInstant());
  382. Files.setLastModifiedTime(db.getIndexFile().toPath(),
  383. FileTime.from(FS.DETECTED
  384. .lastModifiedInstant(db.getIndexFile())
  385. .minusMillis(5000L)));
  386. assertNotNull(git.checkout().setName("test").call());
  387. cache = DirCache.read(db.getIndexFile(), db.getFS());
  388. entry = cache.getEntry("Test.txt");
  389. assertNotNull(entry);
  390. assertEquals(size, entry.getLength());
  391. assertEquals(mTime, entry.getLastModifiedInstant());
  392. }
  393. @Test
  394. public void testCheckoutOrphanBranch() throws Exception {
  395. CheckoutCommand co = newOrphanBranchCommand();
  396. assertCheckoutRef(co.call());
  397. File HEAD = new File(trash, ".git/HEAD");
  398. String headRef = read(HEAD);
  399. assertEquals("ref: refs/heads/orphanbranch\n", headRef);
  400. assertEquals(2, trash.list().length);
  401. File heads = new File(trash, ".git/refs/heads");
  402. assertEquals(2, heads.listFiles().length);
  403. this.assertNoHead();
  404. this.assertRepositoryCondition(1);
  405. assertEquals(CheckoutResult.NOT_TRIED_RESULT, co.getResult());
  406. }
  407. private Repository createRepositoryWithRemote() throws IOException,
  408. URISyntaxException, MalformedURLException, GitAPIException,
  409. InvalidRemoteException, TransportException {
  410. // create second repository
  411. Repository db2 = createWorkRepository();
  412. try (Git git2 = new Git(db2)) {
  413. // setup the second repository to fetch from the first repository
  414. final StoredConfig config = db2.getConfig();
  415. RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
  416. URIish uri = new URIish(db.getDirectory().toURI().toURL());
  417. remoteConfig.addURI(uri);
  418. remoteConfig.update(config);
  419. config.save();
  420. // fetch from first repository
  421. git2.fetch().setRemote("origin")
  422. .setRefSpecs("+refs/heads/*:refs/remotes/origin/*").call();
  423. return db2;
  424. }
  425. }
  426. private CheckoutCommand newOrphanBranchCommand() {
  427. return git.checkout().setOrphan(true)
  428. .setName("orphanbranch");
  429. }
  430. private static void assertCheckoutRef(Ref ref) {
  431. assertNotNull(ref);
  432. assertEquals("refs/heads/orphanbranch", ref.getTarget().getName());
  433. }
  434. private void assertNoHead() throws IOException {
  435. assertNull(db.resolve("HEAD"));
  436. }
  437. private void assertHeadDetached() throws IOException {
  438. Ref head = db.exactRef(Constants.HEAD);
  439. assertFalse(head.isSymbolic());
  440. assertSame(head, head.getTarget());
  441. }
  442. private void assertRepositoryCondition(int files) throws GitAPIException {
  443. org.eclipse.jgit.api.Status status = this.git.status().call();
  444. assertFalse(status.isClean());
  445. assertEquals(files, status.getAdded().size());
  446. }
  447. @Test
  448. public void testCreateOrphanBranchWithStartCommit() throws Exception {
  449. CheckoutCommand co = newOrphanBranchCommand();
  450. Ref ref = co.setStartPoint(initialCommit).call();
  451. assertCheckoutRef(ref);
  452. assertEquals(2, trash.list().length);
  453. this.assertNoHead();
  454. this.assertRepositoryCondition(1);
  455. }
  456. @Test
  457. public void testCreateOrphanBranchWithStartPoint() throws Exception {
  458. CheckoutCommand co = newOrphanBranchCommand();
  459. Ref ref = co.setStartPoint("HEAD^").call();
  460. assertCheckoutRef(ref);
  461. assertEquals(2, trash.list().length);
  462. this.assertNoHead();
  463. this.assertRepositoryCondition(1);
  464. }
  465. @Test
  466. public void testInvalidRefName() throws Exception {
  467. try {
  468. git.checkout().setOrphan(true).setName("../invalidname").call();
  469. fail("Should have failed");
  470. } catch (InvalidRefNameException e) {
  471. // except to hit here
  472. }
  473. }
  474. @Test
  475. public void testNullRefName() throws Exception {
  476. try {
  477. git.checkout().setOrphan(true).setName(null).call();
  478. fail("Should have failed");
  479. } catch (InvalidRefNameException e) {
  480. // except to hit here
  481. }
  482. }
  483. @Test
  484. public void testAlreadyExists() throws Exception {
  485. this.git.checkout().setCreateBranch(true).setName("orphanbranch")
  486. .call();
  487. this.git.checkout().setName("master").call();
  488. try {
  489. newOrphanBranchCommand().call();
  490. fail("Should have failed");
  491. } catch (RefAlreadyExistsException e) {
  492. // except to hit here
  493. }
  494. }
  495. // TODO: write a faster test which depends less on characteristics of
  496. // underlying filesystem/OS.
  497. @Test
  498. public void testCheckoutAutoCrlfTrue() throws Exception {
  499. int nrOfAutoCrlfTestFiles = 200;
  500. FileBasedConfig c = db.getConfig();
  501. c.setString("core", null, "autocrlf", "true");
  502. c.save();
  503. AddCommand add = git.add();
  504. for (int i = 100; i < 100 + nrOfAutoCrlfTestFiles; i++) {
  505. writeTrashFile("Test_" + i + ".txt", "Hello " + i
  506. + " world\nX\nYU\nJK\n");
  507. add.addFilepattern("Test_" + i + ".txt");
  508. }
  509. fsTick(null);
  510. add.call();
  511. RevCommit c1 = git.commit().setMessage("add some lines").call();
  512. add = git.add();
  513. for (int i = 100; i < 100 + nrOfAutoCrlfTestFiles; i++) {
  514. writeTrashFile("Test_" + i + ".txt", "Hello " + i
  515. + " world\nX\nY\n");
  516. add.addFilepattern("Test_" + i + ".txt");
  517. }
  518. fsTick(null);
  519. add.call();
  520. git.commit().setMessage("add more").call();
  521. git.checkout().setName(c1.getName()).call();
  522. boolean foundUnsmudged = false;
  523. DirCache dc = db.readDirCache();
  524. for (int i = 100; i < 100 + nrOfAutoCrlfTestFiles; i++) {
  525. DirCacheEntry entry = dc.getEntry(
  526. "Test_" + i + ".txt");
  527. if (!entry.isSmudged()) {
  528. foundUnsmudged = true;
  529. assertEquals("unexpected file length in git index", 28,
  530. entry.getLength());
  531. }
  532. }
  533. org.junit.Assume.assumeTrue(foundUnsmudged);
  534. }
  535. @Test
  536. public void testSmudgeFilter_modifyExisting() throws IOException, GitAPIException {
  537. File script = writeTempFile("sed s/o/e/g");
  538. StoredConfig config = git.getRepository().getConfig();
  539. config.setString("filter", "lfs", "smudge",
  540. "sh " + slashify(script.getPath()));
  541. config.save();
  542. writeTrashFile(".gitattributes", "*.txt filter=lfs");
  543. git.add().addFilepattern(".gitattributes").call();
  544. git.commit().setMessage("add filter").call();
  545. writeTrashFile("src/a.tmp", "x");
  546. // Caution: we need a trailing '\n' since sed on mac always appends
  547. // linefeeds if missing
  548. writeTrashFile("src/a.txt", "x\n");
  549. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  550. .call();
  551. RevCommit content1 = git.commit().setMessage("add content").call();
  552. writeTrashFile("src/a.tmp", "foo");
  553. writeTrashFile("src/a.txt", "foo\n");
  554. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  555. .call();
  556. RevCommit content2 = git.commit().setMessage("changed content").call();
  557. git.checkout().setName(content1.getName()).call();
  558. git.checkout().setName(content2.getName()).call();
  559. assertEquals(
  560. "[.gitattributes, mode:100644, content:*.txt filter=lfs][Test.txt, mode:100644, content:Some change][src/a.tmp, mode:100644, content:foo][src/a.txt, mode:100644, content:foo\n]",
  561. indexState(CONTENT));
  562. assertEquals(Sets.of("src/a.txt"), git.status().call().getModified());
  563. assertEquals("foo", read("src/a.tmp"));
  564. assertEquals("fee\n", read("src/a.txt"));
  565. }
  566. @Test
  567. public void testSmudgeFilter_createNew()
  568. throws IOException, GitAPIException {
  569. File script = writeTempFile("sed s/o/e/g");
  570. StoredConfig config = git.getRepository().getConfig();
  571. config.setString("filter", "lfs", "smudge",
  572. "sh " + slashify(script.getPath()));
  573. config.save();
  574. writeTrashFile("foo", "foo");
  575. git.add().addFilepattern("foo").call();
  576. RevCommit initial = git.commit().setMessage("initial").call();
  577. writeTrashFile(".gitattributes", "*.txt filter=lfs");
  578. git.add().addFilepattern(".gitattributes").call();
  579. git.commit().setMessage("add filter").call();
  580. writeTrashFile("src/a.tmp", "foo");
  581. // Caution: we need a trailing '\n' since sed on mac always appends
  582. // linefeeds if missing
  583. writeTrashFile("src/a.txt", "foo\n");
  584. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  585. .call();
  586. RevCommit content = git.commit().setMessage("added content").call();
  587. git.checkout().setName(initial.getName()).call();
  588. git.checkout().setName(content.getName()).call();
  589. assertEquals(
  590. "[.gitattributes, mode:100644, content:*.txt filter=lfs][Test.txt, mode:100644, content:Some change][foo, mode:100644, content:foo][src/a.tmp, mode:100644, content:foo][src/a.txt, mode:100644, content:foo\n]",
  591. indexState(CONTENT));
  592. assertEquals("foo", read("src/a.tmp"));
  593. assertEquals("fee\n", read("src/a.txt"));
  594. }
  595. @Test
  596. public void testSmudgeFilter_deleteFileAndRestoreFromCommit()
  597. throws IOException, GitAPIException {
  598. File script = writeTempFile("sed s/o/e/g");
  599. StoredConfig config = git.getRepository().getConfig();
  600. config.setString("filter", "lfs", "smudge",
  601. "sh " + slashify(script.getPath()));
  602. config.save();
  603. writeTrashFile("foo", "foo");
  604. git.add().addFilepattern("foo").call();
  605. git.commit().setMessage("initial").call();
  606. writeTrashFile(".gitattributes", "*.txt filter=lfs");
  607. git.add().addFilepattern(".gitattributes").call();
  608. git.commit().setMessage("add filter").call();
  609. writeTrashFile("src/a.tmp", "foo");
  610. // Caution: we need a trailing '\n' since sed on mac always appends
  611. // linefeeds if missing
  612. writeTrashFile("src/a.txt", "foo\n");
  613. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  614. .call();
  615. RevCommit content = git.commit().setMessage("added content").call();
  616. deleteTrashFile("src/a.txt");
  617. git.checkout().setStartPoint(content.getName()).addPath("src/a.txt")
  618. .call();
  619. assertEquals(
  620. "[.gitattributes, mode:100644, content:*.txt filter=lfs][Test.txt, mode:100644, content:Some change][foo, mode:100644, content:foo][src/a.tmp, mode:100644, content:foo][src/a.txt, mode:100644, content:foo\n]",
  621. indexState(CONTENT));
  622. assertEquals("foo", read("src/a.tmp"));
  623. assertEquals("fee\n", read("src/a.txt"));
  624. }
  625. @Test
  626. public void testSmudgeFilter_deleteFileAndRestoreFromIndex()
  627. throws IOException, GitAPIException {
  628. File script = writeTempFile("sed s/o/e/g");
  629. StoredConfig config = git.getRepository().getConfig();
  630. config.setString("filter", "lfs", "smudge",
  631. "sh " + slashify(script.getPath()));
  632. config.save();
  633. writeTrashFile("foo", "foo");
  634. git.add().addFilepattern("foo").call();
  635. git.commit().setMessage("initial").call();
  636. writeTrashFile(".gitattributes", "*.txt filter=lfs");
  637. git.add().addFilepattern(".gitattributes").call();
  638. git.commit().setMessage("add filter").call();
  639. writeTrashFile("src/a.tmp", "foo");
  640. // Caution: we need a trailing '\n' since sed on mac always appends
  641. // linefeeds if missing
  642. writeTrashFile("src/a.txt", "foo\n");
  643. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  644. .call();
  645. git.commit().setMessage("added content").call();
  646. deleteTrashFile("src/a.txt");
  647. git.checkout().addPath("src/a.txt").call();
  648. assertEquals(
  649. "[.gitattributes, mode:100644, content:*.txt filter=lfs][Test.txt, mode:100644, content:Some change][foo, mode:100644, content:foo][src/a.tmp, mode:100644, content:foo][src/a.txt, mode:100644, content:foo\n]",
  650. indexState(CONTENT));
  651. assertEquals("foo", read("src/a.tmp"));
  652. assertEquals("fee\n", read("src/a.txt"));
  653. }
  654. @Test
  655. public void testSmudgeFilter_deleteFileAndCreateBranchAndRestoreFromCommit()
  656. throws IOException, GitAPIException {
  657. File script = writeTempFile("sed s/o/e/g");
  658. StoredConfig config = git.getRepository().getConfig();
  659. config.setString("filter", "lfs", "smudge",
  660. "sh " + slashify(script.getPath()));
  661. config.save();
  662. writeTrashFile("foo", "foo");
  663. git.add().addFilepattern("foo").call();
  664. git.commit().setMessage("initial").call();
  665. writeTrashFile(".gitattributes", "*.txt filter=lfs");
  666. git.add().addFilepattern(".gitattributes").call();
  667. git.commit().setMessage("add filter").call();
  668. writeTrashFile("src/a.tmp", "foo");
  669. // Caution: we need a trailing '\n' since sed on mac always appends
  670. // linefeeds if missing
  671. writeTrashFile("src/a.txt", "foo\n");
  672. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  673. .call();
  674. RevCommit content = git.commit().setMessage("added content").call();
  675. deleteTrashFile("src/a.txt");
  676. git.checkout().setName("newBranch").setCreateBranch(true)
  677. .setStartPoint(content).addPath("src/a.txt").call();
  678. assertEquals(
  679. "[.gitattributes, mode:100644, content:*.txt filter=lfs][Test.txt, mode:100644, content:Some change][foo, mode:100644, content:foo][src/a.tmp, mode:100644, content:foo][src/a.txt, mode:100644, content:foo\n]",
  680. indexState(CONTENT));
  681. assertEquals("foo", read("src/a.tmp"));
  682. assertEquals("fee\n", read("src/a.txt"));
  683. }
  684. @Test
  685. public void testSmudgeAndClean() throws Exception {
  686. File clean_filter = writeTempFile("sed s/V1/@version/g");
  687. File smudge_filter = writeTempFile("sed s/@version/V1/g");
  688. try (Git git2 = new Git(db)) {
  689. StoredConfig config = git.getRepository().getConfig();
  690. config.setString("filter", "lfs", "smudge",
  691. "sh " + slashify(smudge_filter.getPath()));
  692. config.setString("filter", "lfs", "clean",
  693. "sh " + slashify(clean_filter.getPath()));
  694. config.setBoolean("filter", "lfs", "useJGitBuiltin", true);
  695. config.save();
  696. writeTrashFile(".gitattributes", "filterTest.txt filter=lfs");
  697. git2.add().addFilepattern(".gitattributes").call();
  698. git2.commit().setMessage("add attributes").call();
  699. fsTick(writeTrashFile("filterTest.txt", "hello world, V1\n"));
  700. git2.add().addFilepattern("filterTest.txt").call();
  701. RevCommit one = git2.commit().setMessage("add filterText.txt").call();
  702. assertEquals(
  703. "[.gitattributes, mode:100644, content:filterTest.txt filter=lfs][Test.txt, mode:100644, content:Some change][filterTest.txt, mode:100644, content:version https://git-lfs.github.com/spec/v1\noid sha256:7bd5d32e5c494354aa4c2473a1306d0ce7b52cc3bffeb342c03cd517ef8cf8da\nsize 16\n]",
  704. indexState(CONTENT));
  705. fsTick(writeTrashFile("filterTest.txt", "bon giorno world, V1\n"));
  706. git2.add().addFilepattern("filterTest.txt").call();
  707. RevCommit two = git2.commit().setMessage("modified filterTest.txt").call();
  708. assertTrue(git2.status().call().isClean());
  709. assertEquals(
  710. "[.gitattributes, mode:100644, content:filterTest.txt filter=lfs][Test.txt, mode:100644, content:Some change][filterTest.txt, mode:100644, content:version https://git-lfs.github.com/spec/v1\noid sha256:087148cccf53b0049c56475c1595113c9da4b638997c3489af8ac7108d51ef13\nsize 21\n]",
  711. indexState(CONTENT));
  712. git2.checkout().setName(one.getName()).call();
  713. assertTrue(git2.status().call().isClean());
  714. assertEquals(
  715. "[.gitattributes, mode:100644, content:filterTest.txt filter=lfs][Test.txt, mode:100644, content:Some change][filterTest.txt, mode:100644, content:version https://git-lfs.github.com/spec/v1\noid sha256:7bd5d32e5c494354aa4c2473a1306d0ce7b52cc3bffeb342c03cd517ef8cf8da\nsize 16\n]",
  716. indexState(CONTENT));
  717. assertEquals("hello world, V1\n", read("filterTest.txt"));
  718. git2.checkout().setName(two.getName()).call();
  719. assertTrue(git2.status().call().isClean());
  720. assertEquals(
  721. "[.gitattributes, mode:100644, content:filterTest.txt filter=lfs][Test.txt, mode:100644, content:Some change][filterTest.txt, mode:100644, content:version https://git-lfs.github.com/spec/v1\noid sha256:087148cccf53b0049c56475c1595113c9da4b638997c3489af8ac7108d51ef13\nsize 21\n]",
  722. indexState(CONTENT));
  723. assertEquals("bon giorno world, V1\n", read("filterTest.txt"));
  724. }
  725. }
  726. @Test
  727. public void testNonDeletableFilesOnWindows()
  728. throws GitAPIException, IOException {
  729. // Only on windows a FileInputStream blocks us from deleting a file
  730. org.junit.Assume.assumeTrue(SystemReader.getInstance().isWindows());
  731. writeTrashFile("toBeModified.txt", "a");
  732. writeTrashFile("toBeDeleted.txt", "a");
  733. git.add().addFilepattern(".").call();
  734. RevCommit addFiles = git.commit().setMessage("add more files").call();
  735. git.rm().setCached(false).addFilepattern("Test.txt")
  736. .addFilepattern("toBeDeleted.txt").call();
  737. writeTrashFile("toBeModified.txt", "b");
  738. writeTrashFile("toBeCreated.txt", "a");
  739. git.add().addFilepattern(".").call();
  740. RevCommit crudCommit = git.commit().setMessage("delete, modify, add")
  741. .call();
  742. git.checkout().setName(addFiles.getName()).call();
  743. try ( FileInputStream fis=new FileInputStream(new File(db.getWorkTree(), "Test.txt")) ) {
  744. CheckoutCommand coCommand = git.checkout();
  745. coCommand.setName(crudCommit.getName()).call();
  746. CheckoutResult result = coCommand.getResult();
  747. assertEquals(Status.NONDELETED, result.getStatus());
  748. assertEquals("[Test.txt, toBeDeleted.txt]",
  749. result.getRemovedList().toString());
  750. assertEquals("[toBeCreated.txt, toBeModified.txt]",
  751. result.getModifiedList().toString());
  752. assertEquals("[Test.txt]", result.getUndeletedList().toString());
  753. assertTrue(result.getConflictList().isEmpty());
  754. }
  755. }
  756. private File writeTempFile(String body) throws IOException {
  757. File f = File.createTempFile("CheckoutCommandTest_", "");
  758. JGitTestUtil.write(f, body);
  759. return f;
  760. }
  761. }