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

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