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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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 testCreateBranchOnCheckout() throws Exception {
  116. git.checkout().setCreateBranch(true).setName("test2").call();
  117. assertNotNull(db.exactRef("refs/heads/test2"));
  118. }
  119. @Test
  120. public void testCheckoutToNonExistingBranch() throws GitAPIException {
  121. try {
  122. git.checkout().setName("badbranch").call();
  123. fail("Should have failed");
  124. } catch (RefNotFoundException e) {
  125. // except to hit here
  126. }
  127. }
  128. @Test
  129. public void testCheckoutWithConflict() throws Exception {
  130. CheckoutCommand co = git.checkout();
  131. try {
  132. writeTrashFile("Test.txt", "Another change");
  133. assertEquals(Status.NOT_TRIED, co.getResult().getStatus());
  134. co.setName("master").call();
  135. fail("Should have failed");
  136. } catch (Exception e) {
  137. assertEquals(Status.CONFLICTS, co.getResult().getStatus());
  138. assertTrue(co.getResult().getConflictList().contains("Test.txt"));
  139. }
  140. git.checkout().setName("master").setForced(true).call();
  141. assertThat(read("Test.txt"), is("Hello world"));
  142. }
  143. @Test
  144. public void testCheckoutWithNonDeletedFiles() throws Exception {
  145. File testFile = writeTrashFile("temp", "");
  146. try (FileInputStream fis = new FileInputStream(testFile)) {
  147. FileUtils.delete(testFile);
  148. return;
  149. } catch (IOException e) {
  150. // the test makes only sense if deletion of
  151. // a file with open stream fails
  152. }
  153. FileUtils.delete(testFile);
  154. CheckoutCommand co = git.checkout();
  155. // delete Test.txt in branch test
  156. testFile = new File(db.getWorkTree(), "Test.txt");
  157. assertTrue(testFile.exists());
  158. FileUtils.delete(testFile);
  159. assertFalse(testFile.exists());
  160. git.add().addFilepattern("Test.txt");
  161. git.commit().setMessage("Delete Test.txt").setAll(true).call();
  162. git.checkout().setName("master").call();
  163. assertTrue(testFile.exists());
  164. // lock the file so it can't be deleted (in Windows, that is)
  165. try (FileInputStream fis = new FileInputStream(testFile)) {
  166. assertEquals(Status.NOT_TRIED, co.getResult().getStatus());
  167. co.setName("test").call();
  168. assertTrue(testFile.exists());
  169. assertEquals(Status.NONDELETED, co.getResult().getStatus());
  170. assertTrue(co.getResult().getUndeletedList().contains("Test.txt"));
  171. }
  172. }
  173. @Test
  174. public void testCheckoutCommit() throws Exception {
  175. Ref result = git.checkout().setName(initialCommit.name()).call();
  176. assertEquals("[Test.txt, mode:100644, content:Hello world]",
  177. indexState(CONTENT));
  178. assertNull(result);
  179. assertEquals(initialCommit.name(), git.getRepository().getFullBranch());
  180. }
  181. @Test
  182. public void testCheckoutLightweightTag() throws Exception {
  183. git.tag().setAnnotated(false).setName("test-tag")
  184. .setObjectId(initialCommit).call();
  185. Ref result = git.checkout().setName("test-tag").call();
  186. assertNull(result);
  187. assertEquals(initialCommit.getId(), db.resolve(Constants.HEAD));
  188. assertHeadDetached();
  189. }
  190. @Test
  191. public void testCheckoutAnnotatedTag() throws Exception {
  192. git.tag().setAnnotated(true).setName("test-tag")
  193. .setObjectId(initialCommit).call();
  194. Ref result = git.checkout().setName("test-tag").call();
  195. assertNull(result);
  196. assertEquals(initialCommit.getId(), db.resolve(Constants.HEAD));
  197. assertHeadDetached();
  198. }
  199. @Test
  200. public void testCheckoutRemoteTrackingWithUpstream() throws Exception {
  201. Repository db2 = createRepositoryWithRemote();
  202. Git.wrap(db2).checkout().setCreateBranch(true).setName("test")
  203. .setStartPoint("origin/test")
  204. .setUpstreamMode(SetupUpstreamMode.TRACK).call();
  205. assertEquals("refs/heads/test",
  206. db2.exactRef(Constants.HEAD).getTarget().getName());
  207. StoredConfig config = db2.getConfig();
  208. assertEquals("origin", config.getString(
  209. ConfigConstants.CONFIG_BRANCH_SECTION, "test",
  210. ConfigConstants.CONFIG_KEY_REMOTE));
  211. assertEquals("refs/heads/test", config.getString(
  212. ConfigConstants.CONFIG_BRANCH_SECTION, "test",
  213. ConfigConstants.CONFIG_KEY_MERGE));
  214. }
  215. @Test
  216. public void testCheckoutRemoteTrackingWithoutLocalBranch() throws Exception {
  217. Repository db2 = createRepositoryWithRemote();
  218. // checkout remote tracking branch in second repository
  219. // (no local branches exist yet in second repository)
  220. Git.wrap(db2).checkout().setName("remotes/origin/test").call();
  221. assertEquals("[Test.txt, mode:100644, content:Some change]",
  222. indexState(db2, CONTENT));
  223. }
  224. @Test
  225. public void testCheckoutOfFileWithInexistentParentDir() throws Exception {
  226. File a = writeTrashFile("dir/a.txt", "A");
  227. writeTrashFile("dir/b.txt", "A");
  228. git.add().addFilepattern("dir/a.txt").addFilepattern("dir/b.txt")
  229. .call();
  230. git.commit().setMessage("Added dir").call();
  231. File dir = new File(db.getWorkTree(), "dir");
  232. FileUtils.delete(dir, FileUtils.RECURSIVE);
  233. git.checkout().addPath("dir/a.txt").call();
  234. assertTrue(a.exists());
  235. }
  236. @Test
  237. public void testCheckoutOfDirectoryShouldBeRecursive() throws Exception {
  238. File a = writeTrashFile("dir/a.txt", "A");
  239. File b = writeTrashFile("dir/sub/b.txt", "B");
  240. git.add().addFilepattern("dir").call();
  241. git.commit().setMessage("Added dir").call();
  242. write(a, "modified");
  243. write(b, "modified");
  244. git.checkout().addPath("dir").call();
  245. assertThat(read(a), is("A"));
  246. assertThat(read(b), is("B"));
  247. }
  248. @Test
  249. public void testCheckoutAllPaths() throws Exception {
  250. File a = writeTrashFile("dir/a.txt", "A");
  251. File b = writeTrashFile("dir/sub/b.txt", "B");
  252. git.add().addFilepattern("dir").call();
  253. git.commit().setMessage("Added dir").call();
  254. write(a, "modified");
  255. write(b, "modified");
  256. git.checkout().setAllPaths(true).call();
  257. assertThat(read(a), is("A"));
  258. assertThat(read(b), is("B"));
  259. }
  260. @Test
  261. public void testCheckoutWithStartPoint() throws Exception {
  262. File a = writeTrashFile("a.txt", "A");
  263. git.add().addFilepattern("a.txt").call();
  264. RevCommit first = git.commit().setMessage("Added a").call();
  265. write(a, "other");
  266. git.commit().setAll(true).setMessage("Other").call();
  267. git.checkout().setCreateBranch(true).setName("a")
  268. .setStartPoint(first.getId().getName()).call();
  269. assertThat(read(a), is("A"));
  270. }
  271. @Test
  272. public void testCheckoutWithStartPointOnlyCertainFiles() throws Exception {
  273. File a = writeTrashFile("a.txt", "A");
  274. File b = writeTrashFile("b.txt", "B");
  275. git.add().addFilepattern("a.txt").addFilepattern("b.txt").call();
  276. RevCommit first = git.commit().setMessage("First").call();
  277. write(a, "other");
  278. write(b, "other");
  279. git.commit().setAll(true).setMessage("Other").call();
  280. git.checkout().setCreateBranch(true).setName("a")
  281. .setStartPoint(first.getId().getName()).addPath("a.txt").call();
  282. assertThat(read(a), is("A"));
  283. assertThat(read(b), is("other"));
  284. }
  285. @Test
  286. public void testDetachedHeadOnCheckout() throws JGitInternalException,
  287. IOException, GitAPIException {
  288. CheckoutCommand co = git.checkout();
  289. co.setName("master").call();
  290. String commitId = db.exactRef(R_HEADS + MASTER).getObjectId().name();
  291. co = git.checkout();
  292. co.setName(commitId).call();
  293. assertHeadDetached();
  294. }
  295. @Test
  296. public void testUpdateSmudgedEntries() throws Exception {
  297. git.branchCreate().setName("test2").call();
  298. RefUpdate rup = db.updateRef(Constants.HEAD);
  299. rup.link("refs/heads/test2");
  300. File file = new File(db.getWorkTree(), "Test.txt");
  301. long size = file.length();
  302. Instant mTime = TimeUtil.setLastModifiedWithOffset(file.toPath(),
  303. -5000L);
  304. DirCache cache = DirCache.lock(db.getIndexFile(), db.getFS());
  305. DirCacheEntry entry = cache.getEntry("Test.txt");
  306. assertNotNull(entry);
  307. entry.setLength(0);
  308. entry.setLastModified(EPOCH);
  309. cache.write();
  310. assertTrue(cache.commit());
  311. cache = DirCache.read(db.getIndexFile(), db.getFS());
  312. entry = cache.getEntry("Test.txt");
  313. assertNotNull(entry);
  314. assertEquals(0, entry.getLength());
  315. assertEquals(EPOCH, entry.getLastModifiedInstant());
  316. Files.setLastModifiedTime(db.getIndexFile().toPath(),
  317. FileTime.from(FS.DETECTED
  318. .lastModifiedInstant(db.getIndexFile())
  319. .minusMillis(5000L)));
  320. assertNotNull(git.checkout().setName("test").call());
  321. cache = DirCache.read(db.getIndexFile(), db.getFS());
  322. entry = cache.getEntry("Test.txt");
  323. assertNotNull(entry);
  324. assertEquals(size, entry.getLength());
  325. assertEquals(mTime, entry.getLastModifiedInstant());
  326. }
  327. @Test
  328. public void testCheckoutOrphanBranch() throws Exception {
  329. CheckoutCommand co = newOrphanBranchCommand();
  330. assertCheckoutRef(co.call());
  331. File HEAD = new File(trash, ".git/HEAD");
  332. String headRef = read(HEAD);
  333. assertEquals("ref: refs/heads/orphanbranch\n", headRef);
  334. assertEquals(2, trash.list().length);
  335. File heads = new File(trash, ".git/refs/heads");
  336. assertEquals(2, heads.listFiles().length);
  337. this.assertNoHead();
  338. this.assertRepositoryCondition(1);
  339. assertEquals(CheckoutResult.NOT_TRIED_RESULT, co.getResult());
  340. }
  341. private Repository createRepositoryWithRemote() throws IOException,
  342. URISyntaxException, MalformedURLException, GitAPIException,
  343. InvalidRemoteException, TransportException {
  344. // create second repository
  345. Repository db2 = createWorkRepository();
  346. try (Git git2 = new Git(db2)) {
  347. // setup the second repository to fetch from the first repository
  348. final StoredConfig config = db2.getConfig();
  349. RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
  350. URIish uri = new URIish(db.getDirectory().toURI().toURL());
  351. remoteConfig.addURI(uri);
  352. remoteConfig.update(config);
  353. config.save();
  354. // fetch from first repository
  355. git2.fetch().setRemote("origin")
  356. .setRefSpecs("+refs/heads/*:refs/remotes/origin/*").call();
  357. return db2;
  358. }
  359. }
  360. private CheckoutCommand newOrphanBranchCommand() {
  361. return git.checkout().setOrphan(true)
  362. .setName("orphanbranch");
  363. }
  364. private static void assertCheckoutRef(Ref ref) {
  365. assertNotNull(ref);
  366. assertEquals("refs/heads/orphanbranch", ref.getTarget().getName());
  367. }
  368. private void assertNoHead() throws IOException {
  369. assertNull(db.resolve("HEAD"));
  370. }
  371. private void assertHeadDetached() throws IOException {
  372. Ref head = db.exactRef(Constants.HEAD);
  373. assertFalse(head.isSymbolic());
  374. assertSame(head, head.getTarget());
  375. }
  376. private void assertRepositoryCondition(int files) throws GitAPIException {
  377. org.eclipse.jgit.api.Status status = this.git.status().call();
  378. assertFalse(status.isClean());
  379. assertEquals(files, status.getAdded().size());
  380. }
  381. @Test
  382. public void testCreateOrphanBranchWithStartCommit() throws Exception {
  383. CheckoutCommand co = newOrphanBranchCommand();
  384. Ref ref = co.setStartPoint(initialCommit).call();
  385. assertCheckoutRef(ref);
  386. assertEquals(2, trash.list().length);
  387. this.assertNoHead();
  388. this.assertRepositoryCondition(1);
  389. }
  390. @Test
  391. public void testCreateOrphanBranchWithStartPoint() throws Exception {
  392. CheckoutCommand co = newOrphanBranchCommand();
  393. Ref ref = co.setStartPoint("HEAD^").call();
  394. assertCheckoutRef(ref);
  395. assertEquals(2, trash.list().length);
  396. this.assertNoHead();
  397. this.assertRepositoryCondition(1);
  398. }
  399. @Test
  400. public void testInvalidRefName() throws Exception {
  401. try {
  402. git.checkout().setOrphan(true).setName("../invalidname").call();
  403. fail("Should have failed");
  404. } catch (InvalidRefNameException e) {
  405. // except to hit here
  406. }
  407. }
  408. @Test
  409. public void testNullRefName() throws Exception {
  410. try {
  411. git.checkout().setOrphan(true).setName(null).call();
  412. fail("Should have failed");
  413. } catch (InvalidRefNameException e) {
  414. // except to hit here
  415. }
  416. }
  417. @Test
  418. public void testAlreadyExists() throws Exception {
  419. this.git.checkout().setCreateBranch(true).setName("orphanbranch")
  420. .call();
  421. this.git.checkout().setName("master").call();
  422. try {
  423. newOrphanBranchCommand().call();
  424. fail("Should have failed");
  425. } catch (RefAlreadyExistsException e) {
  426. // except to hit here
  427. }
  428. }
  429. // TODO: write a faster test which depends less on characteristics of
  430. // underlying filesystem/OS.
  431. @Test
  432. public void testCheckoutAutoCrlfTrue() throws Exception {
  433. int nrOfAutoCrlfTestFiles = 200;
  434. FileBasedConfig c = db.getConfig();
  435. c.setString("core", null, "autocrlf", "true");
  436. c.save();
  437. AddCommand add = git.add();
  438. for (int i = 100; i < 100 + nrOfAutoCrlfTestFiles; i++) {
  439. writeTrashFile("Test_" + i + ".txt", "Hello " + i
  440. + " world\nX\nYU\nJK\n");
  441. add.addFilepattern("Test_" + i + ".txt");
  442. }
  443. fsTick(null);
  444. add.call();
  445. RevCommit c1 = git.commit().setMessage("add some lines").call();
  446. add = git.add();
  447. for (int i = 100; i < 100 + nrOfAutoCrlfTestFiles; i++) {
  448. writeTrashFile("Test_" + i + ".txt", "Hello " + i
  449. + " world\nX\nY\n");
  450. add.addFilepattern("Test_" + i + ".txt");
  451. }
  452. fsTick(null);
  453. add.call();
  454. git.commit().setMessage("add more").call();
  455. git.checkout().setName(c1.getName()).call();
  456. boolean foundUnsmudged = false;
  457. DirCache dc = db.readDirCache();
  458. for (int i = 100; i < 100 + nrOfAutoCrlfTestFiles; i++) {
  459. DirCacheEntry entry = dc.getEntry(
  460. "Test_" + i + ".txt");
  461. if (!entry.isSmudged()) {
  462. foundUnsmudged = true;
  463. assertEquals("unexpected file length in git index", 28,
  464. entry.getLength());
  465. }
  466. }
  467. org.junit.Assume.assumeTrue(foundUnsmudged);
  468. }
  469. @Test
  470. public void testSmudgeFilter_modifyExisting() throws IOException, GitAPIException {
  471. File script = writeTempFile("sed s/o/e/g");
  472. StoredConfig config = git.getRepository().getConfig();
  473. config.setString("filter", "lfs", "smudge",
  474. "sh " + slashify(script.getPath()));
  475. config.save();
  476. writeTrashFile(".gitattributes", "*.txt filter=lfs");
  477. git.add().addFilepattern(".gitattributes").call();
  478. git.commit().setMessage("add filter").call();
  479. writeTrashFile("src/a.tmp", "x");
  480. // Caution: we need a trailing '\n' since sed on mac always appends
  481. // linefeeds if missing
  482. writeTrashFile("src/a.txt", "x\n");
  483. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  484. .call();
  485. RevCommit content1 = git.commit().setMessage("add content").call();
  486. writeTrashFile("src/a.tmp", "foo");
  487. writeTrashFile("src/a.txt", "foo\n");
  488. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  489. .call();
  490. RevCommit content2 = git.commit().setMessage("changed content").call();
  491. git.checkout().setName(content1.getName()).call();
  492. git.checkout().setName(content2.getName()).call();
  493. assertEquals(
  494. "[.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]",
  495. indexState(CONTENT));
  496. assertEquals(Sets.of("src/a.txt"), git.status().call().getModified());
  497. assertEquals("foo", read("src/a.tmp"));
  498. assertEquals("fee\n", read("src/a.txt"));
  499. }
  500. @Test
  501. public void testSmudgeFilter_createNew()
  502. throws IOException, GitAPIException {
  503. File script = writeTempFile("sed s/o/e/g");
  504. StoredConfig config = git.getRepository().getConfig();
  505. config.setString("filter", "lfs", "smudge",
  506. "sh " + slashify(script.getPath()));
  507. config.save();
  508. writeTrashFile("foo", "foo");
  509. git.add().addFilepattern("foo").call();
  510. RevCommit initial = git.commit().setMessage("initial").call();
  511. writeTrashFile(".gitattributes", "*.txt filter=lfs");
  512. git.add().addFilepattern(".gitattributes").call();
  513. git.commit().setMessage("add filter").call();
  514. writeTrashFile("src/a.tmp", "foo");
  515. // Caution: we need a trailing '\n' since sed on mac always appends
  516. // linefeeds if missing
  517. writeTrashFile("src/a.txt", "foo\n");
  518. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  519. .call();
  520. RevCommit content = git.commit().setMessage("added content").call();
  521. git.checkout().setName(initial.getName()).call();
  522. git.checkout().setName(content.getName()).call();
  523. assertEquals(
  524. "[.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]",
  525. indexState(CONTENT));
  526. assertEquals("foo", read("src/a.tmp"));
  527. assertEquals("fee\n", read("src/a.txt"));
  528. }
  529. @Test
  530. public void testSmudgeFilter_deleteFileAndRestoreFromCommit()
  531. throws IOException, GitAPIException {
  532. File script = writeTempFile("sed s/o/e/g");
  533. StoredConfig config = git.getRepository().getConfig();
  534. config.setString("filter", "lfs", "smudge",
  535. "sh " + slashify(script.getPath()));
  536. config.save();
  537. writeTrashFile("foo", "foo");
  538. git.add().addFilepattern("foo").call();
  539. git.commit().setMessage("initial").call();
  540. writeTrashFile(".gitattributes", "*.txt filter=lfs");
  541. git.add().addFilepattern(".gitattributes").call();
  542. git.commit().setMessage("add filter").call();
  543. writeTrashFile("src/a.tmp", "foo");
  544. // Caution: we need a trailing '\n' since sed on mac always appends
  545. // linefeeds if missing
  546. writeTrashFile("src/a.txt", "foo\n");
  547. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  548. .call();
  549. RevCommit content = git.commit().setMessage("added content").call();
  550. deleteTrashFile("src/a.txt");
  551. git.checkout().setStartPoint(content.getName()).addPath("src/a.txt")
  552. .call();
  553. assertEquals(
  554. "[.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]",
  555. indexState(CONTENT));
  556. assertEquals("foo", read("src/a.tmp"));
  557. assertEquals("fee\n", read("src/a.txt"));
  558. }
  559. @Test
  560. public void testSmudgeFilter_deleteFileAndRestoreFromIndex()
  561. throws IOException, GitAPIException {
  562. File script = writeTempFile("sed s/o/e/g");
  563. StoredConfig config = git.getRepository().getConfig();
  564. config.setString("filter", "lfs", "smudge",
  565. "sh " + slashify(script.getPath()));
  566. config.save();
  567. writeTrashFile("foo", "foo");
  568. git.add().addFilepattern("foo").call();
  569. git.commit().setMessage("initial").call();
  570. writeTrashFile(".gitattributes", "*.txt filter=lfs");
  571. git.add().addFilepattern(".gitattributes").call();
  572. git.commit().setMessage("add filter").call();
  573. writeTrashFile("src/a.tmp", "foo");
  574. // Caution: we need a trailing '\n' since sed on mac always appends
  575. // linefeeds if missing
  576. writeTrashFile("src/a.txt", "foo\n");
  577. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  578. .call();
  579. git.commit().setMessage("added content").call();
  580. deleteTrashFile("src/a.txt");
  581. git.checkout().addPath("src/a.txt").call();
  582. assertEquals(
  583. "[.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]",
  584. indexState(CONTENT));
  585. assertEquals("foo", read("src/a.tmp"));
  586. assertEquals("fee\n", read("src/a.txt"));
  587. }
  588. @Test
  589. public void testSmudgeFilter_deleteFileAndCreateBranchAndRestoreFromCommit()
  590. throws IOException, GitAPIException {
  591. File script = writeTempFile("sed s/o/e/g");
  592. StoredConfig config = git.getRepository().getConfig();
  593. config.setString("filter", "lfs", "smudge",
  594. "sh " + slashify(script.getPath()));
  595. config.save();
  596. writeTrashFile("foo", "foo");
  597. git.add().addFilepattern("foo").call();
  598. git.commit().setMessage("initial").call();
  599. writeTrashFile(".gitattributes", "*.txt filter=lfs");
  600. git.add().addFilepattern(".gitattributes").call();
  601. git.commit().setMessage("add filter").call();
  602. writeTrashFile("src/a.tmp", "foo");
  603. // Caution: we need a trailing '\n' since sed on mac always appends
  604. // linefeeds if missing
  605. writeTrashFile("src/a.txt", "foo\n");
  606. git.add().addFilepattern("src/a.tmp").addFilepattern("src/a.txt")
  607. .call();
  608. RevCommit content = git.commit().setMessage("added content").call();
  609. deleteTrashFile("src/a.txt");
  610. git.checkout().setName("newBranch").setCreateBranch(true)
  611. .setStartPoint(content).addPath("src/a.txt").call();
  612. assertEquals(
  613. "[.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]",
  614. indexState(CONTENT));
  615. assertEquals("foo", read("src/a.tmp"));
  616. assertEquals("fee\n", read("src/a.txt"));
  617. }
  618. @Test
  619. public void testSmudgeAndClean() throws Exception {
  620. File clean_filter = writeTempFile("sed s/V1/@version/g");
  621. File smudge_filter = writeTempFile("sed s/@version/V1/g");
  622. try (Git git2 = new Git(db)) {
  623. StoredConfig config = git.getRepository().getConfig();
  624. config.setString("filter", "lfs", "smudge",
  625. "sh " + slashify(smudge_filter.getPath()));
  626. config.setString("filter", "lfs", "clean",
  627. "sh " + slashify(clean_filter.getPath()));
  628. config.setBoolean("filter", "lfs", "useJGitBuiltin", true);
  629. config.save();
  630. writeTrashFile(".gitattributes", "filterTest.txt filter=lfs");
  631. git2.add().addFilepattern(".gitattributes").call();
  632. git2.commit().setMessage("add attributes").call();
  633. fsTick(writeTrashFile("filterTest.txt", "hello world, V1\n"));
  634. git2.add().addFilepattern("filterTest.txt").call();
  635. RevCommit one = git2.commit().setMessage("add filterText.txt").call();
  636. assertEquals(
  637. "[.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]",
  638. indexState(CONTENT));
  639. fsTick(writeTrashFile("filterTest.txt", "bon giorno world, V1\n"));
  640. git2.add().addFilepattern("filterTest.txt").call();
  641. RevCommit two = git2.commit().setMessage("modified filterTest.txt").call();
  642. assertTrue(git2.status().call().isClean());
  643. assertEquals(
  644. "[.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]",
  645. indexState(CONTENT));
  646. git2.checkout().setName(one.getName()).call();
  647. assertTrue(git2.status().call().isClean());
  648. assertEquals(
  649. "[.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]",
  650. indexState(CONTENT));
  651. assertEquals("hello world, V1\n", read("filterTest.txt"));
  652. git2.checkout().setName(two.getName()).call();
  653. assertTrue(git2.status().call().isClean());
  654. assertEquals(
  655. "[.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]",
  656. indexState(CONTENT));
  657. assertEquals("bon giorno world, V1\n", read("filterTest.txt"));
  658. }
  659. }
  660. @Test
  661. public void testNonDeletableFilesOnWindows()
  662. throws GitAPIException, IOException {
  663. // Only on windows a FileInputStream blocks us from deleting a file
  664. org.junit.Assume.assumeTrue(SystemReader.getInstance().isWindows());
  665. writeTrashFile("toBeModified.txt", "a");
  666. writeTrashFile("toBeDeleted.txt", "a");
  667. git.add().addFilepattern(".").call();
  668. RevCommit addFiles = git.commit().setMessage("add more files").call();
  669. git.rm().setCached(false).addFilepattern("Test.txt")
  670. .addFilepattern("toBeDeleted.txt").call();
  671. writeTrashFile("toBeModified.txt", "b");
  672. writeTrashFile("toBeCreated.txt", "a");
  673. git.add().addFilepattern(".").call();
  674. RevCommit crudCommit = git.commit().setMessage("delete, modify, add")
  675. .call();
  676. git.checkout().setName(addFiles.getName()).call();
  677. try ( FileInputStream fis=new FileInputStream(new File(db.getWorkTree(), "Test.txt")) ) {
  678. CheckoutCommand coCommand = git.checkout();
  679. coCommand.setName(crudCommit.getName()).call();
  680. CheckoutResult result = coCommand.getResult();
  681. assertEquals(Status.NONDELETED, result.getStatus());
  682. assertEquals("[Test.txt, toBeDeleted.txt]",
  683. result.getRemovedList().toString());
  684. assertEquals("[toBeCreated.txt, toBeModified.txt]",
  685. result.getModifiedList().toString());
  686. assertEquals("[Test.txt]", result.getUndeletedList().toString());
  687. assertTrue(result.getConflictList().isEmpty());
  688. }
  689. }
  690. private File writeTempFile(String body) throws IOException {
  691. File f = File.createTempFile("CheckoutCommandTest_", "");
  692. JGitTestUtil.write(f, body);
  693. return f;
  694. }
  695. }