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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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.RefSpec;
  86. import org.eclipse.jgit.transport.RemoteConfig;
  87. import org.eclipse.jgit.transport.URIish;
  88. import org.eclipse.jgit.util.FileUtils;
  89. import org.eclipse.jgit.util.SystemReader;
  90. import org.junit.Before;
  91. import org.junit.Test;
  92. public class CheckoutCommandTest extends RepositoryTestCase {
  93. private Git git;
  94. RevCommit initialCommit;
  95. RevCommit secondCommit;
  96. @Override
  97. @Before
  98. public void setUp() throws Exception {
  99. CleanFilter.register();
  100. SmudgeFilter.register();
  101. super.setUp();
  102. git = new Git(db);
  103. // commit something
  104. writeTrashFile("Test.txt", "Hello world");
  105. git.add().addFilepattern("Test.txt").call();
  106. initialCommit = git.commit().setMessage("Initial commit").call();
  107. // create a master branch and switch to it
  108. git.branchCreate().setName("test").call();
  109. RefUpdate rup = db.updateRef(Constants.HEAD);
  110. rup.link("refs/heads/test");
  111. // commit something on the test branch
  112. writeTrashFile("Test.txt", "Some change");
  113. git.add().addFilepattern("Test.txt").call();
  114. secondCommit = git.commit().setMessage("Second commit").call();
  115. }
  116. @Test
  117. public void testSimpleCheckout() throws Exception {
  118. git.checkout().setName("test").call();
  119. }
  120. @Test
  121. public void testCheckout() throws Exception {
  122. git.checkout().setName("test").call();
  123. assertEquals("[Test.txt, mode:100644, content:Some change]",
  124. indexState(CONTENT));
  125. Ref result = git.checkout().setName("master").call();
  126. assertEquals("[Test.txt, mode:100644, content:Hello world]",
  127. indexState(CONTENT));
  128. assertEquals("refs/heads/master", result.getName());
  129. assertEquals("refs/heads/master", git.getRepository().getFullBranch());
  130. }
  131. @Test
  132. public void testCreateBranchOnCheckout() throws Exception {
  133. git.checkout().setCreateBranch(true).setName("test2").call();
  134. assertNotNull(db.exactRef("refs/heads/test2"));
  135. }
  136. @Test
  137. public void testCheckoutToNonExistingBranch() throws GitAPIException {
  138. try {
  139. git.checkout().setName("badbranch").call();
  140. fail("Should have failed");
  141. } catch (RefNotFoundException e) {
  142. // except to hit here
  143. }
  144. }
  145. @Test
  146. public void testCheckoutWithConflict() {
  147. CheckoutCommand co = git.checkout();
  148. try {
  149. writeTrashFile("Test.txt", "Another change");
  150. assertEquals(Status.NOT_TRIED, co.getResult().getStatus());
  151. co.setName("master").call();
  152. fail("Should have failed");
  153. } catch (Exception e) {
  154. assertEquals(Status.CONFLICTS, co.getResult().getStatus());
  155. assertTrue(co.getResult().getConflictList().contains("Test.txt"));
  156. }
  157. }
  158. @Test
  159. public void testCheckoutWithNonDeletedFiles() throws Exception {
  160. File testFile = writeTrashFile("temp", "");
  161. FileInputStream fis = new FileInputStream(testFile);
  162. try {
  163. FileUtils.delete(testFile);
  164. return;
  165. } catch (IOException e) {
  166. // the test makes only sense if deletion of
  167. // a file with open stream fails
  168. } finally {
  169. fis.close();
  170. }
  171. FileUtils.delete(testFile);
  172. CheckoutCommand co = git.checkout();
  173. // delete Test.txt in branch test
  174. testFile = new File(db.getWorkTree(), "Test.txt");
  175. assertTrue(testFile.exists());
  176. FileUtils.delete(testFile);
  177. assertFalse(testFile.exists());
  178. git.add().addFilepattern("Test.txt");
  179. git.commit().setMessage("Delete Test.txt").setAll(true).call();
  180. git.checkout().setName("master").call();
  181. assertTrue(testFile.exists());
  182. // lock the file so it can't be deleted (in Windows, that is)
  183. fis = new FileInputStream(testFile);
  184. try {
  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. } finally {
  191. fis.close();
  192. }
  193. }
  194. @Test
  195. public void testCheckoutCommit() throws Exception {
  196. Ref result = git.checkout().setName(initialCommit.name()).call();
  197. assertEquals("[Test.txt, mode:100644, content:Hello world]",
  198. indexState(CONTENT));
  199. assertNull(result);
  200. assertEquals(initialCommit.name(), git.getRepository().getFullBranch());
  201. }
  202. @Test
  203. public void testCheckoutLightweightTag() throws Exception {
  204. git.tag().setAnnotated(false).setName("test-tag")
  205. .setObjectId(initialCommit).call();
  206. Ref result = git.checkout().setName("test-tag").call();
  207. assertNull(result);
  208. assertEquals(initialCommit.getId(), db.resolve(Constants.HEAD));
  209. assertHeadDetached();
  210. }
  211. @Test
  212. public void testCheckoutAnnotatedTag() throws Exception {
  213. git.tag().setAnnotated(true).setName("test-tag")
  214. .setObjectId(initialCommit).call();
  215. Ref result = git.checkout().setName("test-tag").call();
  216. assertNull(result);
  217. assertEquals(initialCommit.getId(), db.resolve(Constants.HEAD));
  218. assertHeadDetached();
  219. }
  220. @Test
  221. public void testCheckoutRemoteTrackingWithUpstream() throws Exception {
  222. Repository db2 = createRepositoryWithRemote();
  223. Git.wrap(db2).checkout().setCreateBranch(true).setName("test")
  224. .setStartPoint("origin/test")
  225. .setUpstreamMode(SetupUpstreamMode.TRACK).call();
  226. assertEquals("refs/heads/test",
  227. db2.exactRef(Constants.HEAD).getTarget().getName());
  228. StoredConfig config = db2.getConfig();
  229. assertEquals("origin", config.getString(
  230. ConfigConstants.CONFIG_BRANCH_SECTION, "test",
  231. ConfigConstants.CONFIG_KEY_REMOTE));
  232. assertEquals("refs/heads/test", config.getString(
  233. ConfigConstants.CONFIG_BRANCH_SECTION, "test",
  234. ConfigConstants.CONFIG_KEY_MERGE));
  235. }
  236. @Test
  237. public void testCheckoutRemoteTrackingWithoutLocalBranch() throws Exception {
  238. Repository db2 = createRepositoryWithRemote();
  239. // checkout remote tracking branch in second repository
  240. // (no local branches exist yet in second repository)
  241. Git.wrap(db2).checkout().setName("remotes/origin/test").call();
  242. assertEquals("[Test.txt, mode:100644, content:Some change]",
  243. indexState(db2, CONTENT));
  244. }
  245. @Test
  246. public void testCheckoutOfFileWithInexistentParentDir() throws Exception {
  247. File a = writeTrashFile("dir/a.txt", "A");
  248. writeTrashFile("dir/b.txt", "A");
  249. git.add().addFilepattern("dir/a.txt").addFilepattern("dir/b.txt")
  250. .call();
  251. git.commit().setMessage("Added dir").call();
  252. File dir = new File(db.getWorkTree(), "dir");
  253. FileUtils.delete(dir, FileUtils.RECURSIVE);
  254. git.checkout().addPath("dir/a.txt").call();
  255. assertTrue(a.exists());
  256. }
  257. @Test
  258. public void testCheckoutOfDirectoryShouldBeRecursive() throws Exception {
  259. File a = writeTrashFile("dir/a.txt", "A");
  260. File b = writeTrashFile("dir/sub/b.txt", "B");
  261. git.add().addFilepattern("dir").call();
  262. git.commit().setMessage("Added dir").call();
  263. write(a, "modified");
  264. write(b, "modified");
  265. git.checkout().addPath("dir").call();
  266. assertThat(read(a), is("A"));
  267. assertThat(read(b), is("B"));
  268. }
  269. @Test
  270. public void testCheckoutAllPaths() throws Exception {
  271. File a = writeTrashFile("dir/a.txt", "A");
  272. File b = writeTrashFile("dir/sub/b.txt", "B");
  273. git.add().addFilepattern("dir").call();
  274. git.commit().setMessage("Added dir").call();
  275. write(a, "modified");
  276. write(b, "modified");
  277. git.checkout().setAllPaths(true).call();
  278. assertThat(read(a), is("A"));
  279. assertThat(read(b), is("B"));
  280. }
  281. @Test
  282. public void testCheckoutWithStartPoint() throws Exception {
  283. File a = writeTrashFile("a.txt", "A");
  284. git.add().addFilepattern("a.txt").call();
  285. RevCommit first = git.commit().setMessage("Added a").call();
  286. write(a, "other");
  287. git.commit().setAll(true).setMessage("Other").call();
  288. git.checkout().setCreateBranch(true).setName("a")
  289. .setStartPoint(first.getId().getName()).call();
  290. assertThat(read(a), is("A"));
  291. }
  292. @Test
  293. public void testCheckoutWithStartPointOnlyCertainFiles() throws Exception {
  294. File a = writeTrashFile("a.txt", "A");
  295. File b = writeTrashFile("b.txt", "B");
  296. git.add().addFilepattern("a.txt").addFilepattern("b.txt").call();
  297. RevCommit first = git.commit().setMessage("First").call();
  298. write(a, "other");
  299. write(b, "other");
  300. git.commit().setAll(true).setMessage("Other").call();
  301. git.checkout().setCreateBranch(true).setName("a")
  302. .setStartPoint(first.getId().getName()).addPath("a.txt").call();
  303. assertThat(read(a), is("A"));
  304. assertThat(read(b), is("other"));
  305. }
  306. @Test
  307. public void testDetachedHeadOnCheckout() throws JGitInternalException,
  308. IOException, GitAPIException {
  309. CheckoutCommand co = git.checkout();
  310. co.setName("master").call();
  311. String commitId = db.exactRef(R_HEADS + MASTER).getObjectId().name();
  312. co = git.checkout();
  313. co.setName(commitId).call();
  314. assertHeadDetached();
  315. }
  316. @Test
  317. public void testUpdateSmudgedEntries() throws Exception {
  318. git.branchCreate().setName("test2").call();
  319. RefUpdate rup = db.updateRef(Constants.HEAD);
  320. rup.link("refs/heads/test2");
  321. File file = new File(db.getWorkTree(), "Test.txt");
  322. long size = file.length();
  323. long mTime = file.lastModified() - 5000L;
  324. assertTrue(file.setLastModified(mTime));
  325. DirCache cache = DirCache.lock(db.getIndexFile(), db.getFS());
  326. DirCacheEntry entry = cache.getEntry("Test.txt");
  327. assertNotNull(entry);
  328. entry.setLength(0);
  329. entry.setLastModified(0);
  330. cache.write();
  331. assertTrue(cache.commit());
  332. cache = DirCache.read(db.getIndexFile(), db.getFS());
  333. entry = cache.getEntry("Test.txt");
  334. assertNotNull(entry);
  335. assertEquals(0, entry.getLength());
  336. assertEquals(0, entry.getLastModified());
  337. db.getIndexFile().setLastModified(
  338. db.getIndexFile().lastModified() - 5000);
  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.getLastModified());
  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. RefSpec spec = new RefSpec("+refs/heads/*:refs/remotes/origin/*");
  375. git2.fetch().setRemote("origin").setRefSpecs(spec).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("AddCommandTest_", "");
  711. JGitTestUtil.write(f, body);
  712. return f;
  713. }
  714. }