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

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