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

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