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

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