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

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