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

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