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

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