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

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