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

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