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.

CommitCommandTest.java 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. /*
  2. * Copyright (C) 2011-2012, GitHub Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.api;
  44. import static org.junit.Assert.assertEquals;
  45. import static org.junit.Assert.assertNotEquals;
  46. import static org.junit.Assert.assertNotNull;
  47. import static org.junit.Assert.assertNull;
  48. import static org.junit.Assert.assertSame;
  49. import static org.junit.Assert.assertTrue;
  50. import static org.junit.Assert.fail;
  51. import java.io.File;
  52. import java.util.Date;
  53. import java.util.List;
  54. import java.util.TimeZone;
  55. import java.util.concurrent.atomic.AtomicInteger;
  56. import org.eclipse.jgit.api.CherryPickResult.CherryPickStatus;
  57. import org.eclipse.jgit.api.errors.CanceledException;
  58. import org.eclipse.jgit.api.errors.EmptyCommitException;
  59. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  60. import org.eclipse.jgit.diff.DiffEntry;
  61. import org.eclipse.jgit.dircache.DirCache;
  62. import org.eclipse.jgit.dircache.DirCacheBuilder;
  63. import org.eclipse.jgit.dircache.DirCacheEntry;
  64. import org.eclipse.jgit.junit.RepositoryTestCase;
  65. import org.eclipse.jgit.lib.CommitBuilder;
  66. import org.eclipse.jgit.lib.ConfigConstants;
  67. import org.eclipse.jgit.lib.Constants;
  68. import org.eclipse.jgit.lib.FileMode;
  69. import org.eclipse.jgit.lib.GpgSigner;
  70. import org.eclipse.jgit.lib.ObjectId;
  71. import org.eclipse.jgit.lib.PersonIdent;
  72. import org.eclipse.jgit.lib.RefUpdate;
  73. import org.eclipse.jgit.lib.RefUpdate.Result;
  74. import org.eclipse.jgit.lib.ReflogEntry;
  75. import org.eclipse.jgit.lib.Repository;
  76. import org.eclipse.jgit.lib.StoredConfig;
  77. import org.eclipse.jgit.revwalk.RevCommit;
  78. import org.eclipse.jgit.storage.file.FileBasedConfig;
  79. import org.eclipse.jgit.submodule.SubmoduleWalk;
  80. import org.eclipse.jgit.transport.CredentialsProvider;
  81. import org.eclipse.jgit.treewalk.TreeWalk;
  82. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  83. import org.eclipse.jgit.util.FS;
  84. import org.junit.Ignore;
  85. import org.junit.Test;
  86. /**
  87. * Unit tests of {@link CommitCommand}.
  88. */
  89. public class CommitCommandTest extends RepositoryTestCase {
  90. @Test
  91. public void testExecutableRetention() throws Exception {
  92. StoredConfig config = db.getConfig();
  93. config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  94. ConfigConstants.CONFIG_KEY_FILEMODE, true);
  95. config.save();
  96. FS executableFs = new FS() {
  97. @Override
  98. public boolean supportsExecute() {
  99. return true;
  100. }
  101. @Override
  102. public boolean setExecute(File f, boolean canExec) {
  103. return true;
  104. }
  105. @Override
  106. public ProcessBuilder runInShell(String cmd, String[] args) {
  107. return null;
  108. }
  109. @Override
  110. public boolean retryFailedLockFileCommit() {
  111. return false;
  112. }
  113. @Override
  114. public FS newInstance() {
  115. return this;
  116. }
  117. @Override
  118. protected File discoverGitExe() {
  119. return null;
  120. }
  121. @Override
  122. public boolean canExecute(File f) {
  123. return true;
  124. }
  125. @Override
  126. public boolean isCaseSensitive() {
  127. return true;
  128. }
  129. };
  130. Git git = Git.open(db.getDirectory(), executableFs);
  131. String path = "a.txt";
  132. writeTrashFile(path, "content");
  133. git.add().addFilepattern(path).call();
  134. RevCommit commit1 = git.commit().setMessage("commit").call();
  135. TreeWalk walk = TreeWalk.forPath(db, path, commit1.getTree());
  136. assertNotNull(walk);
  137. assertEquals(FileMode.EXECUTABLE_FILE, walk.getFileMode(0));
  138. FS nonExecutableFs = new FS() {
  139. @Override
  140. public boolean supportsExecute() {
  141. return false;
  142. }
  143. @Override
  144. public boolean setExecute(File f, boolean canExec) {
  145. return false;
  146. }
  147. @Override
  148. public ProcessBuilder runInShell(String cmd, String[] args) {
  149. return null;
  150. }
  151. @Override
  152. public boolean retryFailedLockFileCommit() {
  153. return false;
  154. }
  155. @Override
  156. public FS newInstance() {
  157. return this;
  158. }
  159. @Override
  160. protected File discoverGitExe() {
  161. return null;
  162. }
  163. @Override
  164. public boolean canExecute(File f) {
  165. return false;
  166. }
  167. @Override
  168. public boolean isCaseSensitive() {
  169. return true;
  170. }
  171. };
  172. config = db.getConfig();
  173. config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  174. ConfigConstants.CONFIG_KEY_FILEMODE, false);
  175. config.save();
  176. Git git2 = Git.open(db.getDirectory(), nonExecutableFs);
  177. writeTrashFile(path, "content2");
  178. RevCommit commit2 = git2.commit().setOnly(path).setMessage("commit2")
  179. .call();
  180. walk = TreeWalk.forPath(db, path, commit2.getTree());
  181. assertNotNull(walk);
  182. assertEquals(FileMode.EXECUTABLE_FILE, walk.getFileMode(0));
  183. }
  184. @Test
  185. public void commitNewSubmodule() throws Exception {
  186. try (Git git = new Git(db)) {
  187. writeTrashFile("file.txt", "content");
  188. git.add().addFilepattern("file.txt").call();
  189. RevCommit commit = git.commit().setMessage("create file").call();
  190. SubmoduleAddCommand command = new SubmoduleAddCommand(db);
  191. String path = "sub";
  192. command.setPath(path);
  193. String uri = db.getDirectory().toURI().toString();
  194. command.setURI(uri);
  195. Repository repo = command.call();
  196. assertNotNull(repo);
  197. addRepoToClose(repo);
  198. SubmoduleWalk generator = SubmoduleWalk.forIndex(db);
  199. assertTrue(generator.next());
  200. assertEquals(path, generator.getPath());
  201. assertEquals(commit, generator.getObjectId());
  202. assertEquals(uri, generator.getModulesUrl());
  203. assertEquals(path, generator.getModulesPath());
  204. assertEquals(uri, generator.getConfigUrl());
  205. try (Repository subModRepo = generator.getRepository()) {
  206. assertNotNull(subModRepo);
  207. }
  208. assertEquals(commit, repo.resolve(Constants.HEAD));
  209. RevCommit submoduleCommit = git.commit().setMessage("submodule add")
  210. .setOnly(path).call();
  211. assertNotNull(submoduleCommit);
  212. try (TreeWalk walk = new TreeWalk(db)) {
  213. walk.addTree(commit.getTree());
  214. walk.addTree(submoduleCommit.getTree());
  215. walk.setFilter(TreeFilter.ANY_DIFF);
  216. List<DiffEntry> diffs = DiffEntry.scan(walk);
  217. assertEquals(1, diffs.size());
  218. DiffEntry subDiff = diffs.get(0);
  219. assertEquals(FileMode.MISSING, subDiff.getOldMode());
  220. assertEquals(FileMode.GITLINK, subDiff.getNewMode());
  221. assertEquals(ObjectId.zeroId(), subDiff.getOldId().toObjectId());
  222. assertEquals(commit, subDiff.getNewId().toObjectId());
  223. assertEquals(path, subDiff.getNewPath());
  224. }
  225. }
  226. }
  227. @Test
  228. public void commitSubmoduleUpdate() throws Exception {
  229. try (Git git = new Git(db)) {
  230. writeTrashFile("file.txt", "content");
  231. git.add().addFilepattern("file.txt").call();
  232. RevCommit commit = git.commit().setMessage("create file").call();
  233. writeTrashFile("file.txt", "content2");
  234. git.add().addFilepattern("file.txt").call();
  235. RevCommit commit2 = git.commit().setMessage("edit file").call();
  236. SubmoduleAddCommand command = new SubmoduleAddCommand(db);
  237. String path = "sub";
  238. command.setPath(path);
  239. String uri = db.getDirectory().toURI().toString();
  240. command.setURI(uri);
  241. Repository repo = command.call();
  242. assertNotNull(repo);
  243. addRepoToClose(repo);
  244. SubmoduleWalk generator = SubmoduleWalk.forIndex(db);
  245. assertTrue(generator.next());
  246. assertEquals(path, generator.getPath());
  247. assertEquals(commit2, generator.getObjectId());
  248. assertEquals(uri, generator.getModulesUrl());
  249. assertEquals(path, generator.getModulesPath());
  250. assertEquals(uri, generator.getConfigUrl());
  251. try (Repository subModRepo = generator.getRepository()) {
  252. assertNotNull(subModRepo);
  253. }
  254. assertEquals(commit2, repo.resolve(Constants.HEAD));
  255. RevCommit submoduleAddCommit = git.commit().setMessage("submodule add")
  256. .setOnly(path).call();
  257. assertNotNull(submoduleAddCommit);
  258. RefUpdate update = repo.updateRef(Constants.HEAD);
  259. update.setNewObjectId(commit);
  260. assertEquals(Result.FORCED, update.forceUpdate());
  261. RevCommit submoduleEditCommit = git.commit()
  262. .setMessage("submodule add").setOnly(path).call();
  263. assertNotNull(submoduleEditCommit);
  264. try (TreeWalk walk = new TreeWalk(db)) {
  265. walk.addTree(submoduleAddCommit.getTree());
  266. walk.addTree(submoduleEditCommit.getTree());
  267. walk.setFilter(TreeFilter.ANY_DIFF);
  268. List<DiffEntry> diffs = DiffEntry.scan(walk);
  269. assertEquals(1, diffs.size());
  270. DiffEntry subDiff = diffs.get(0);
  271. assertEquals(FileMode.GITLINK, subDiff.getOldMode());
  272. assertEquals(FileMode.GITLINK, subDiff.getNewMode());
  273. assertEquals(commit2, subDiff.getOldId().toObjectId());
  274. assertEquals(commit, subDiff.getNewId().toObjectId());
  275. assertEquals(path, subDiff.getNewPath());
  276. assertEquals(path, subDiff.getOldPath());
  277. }
  278. }
  279. }
  280. @Ignore("very flaky when run with Hudson")
  281. @Test
  282. public void commitUpdatesSmudgedEntries() throws Exception {
  283. try (Git git = new Git(db)) {
  284. File file1 = writeTrashFile("file1.txt", "content1");
  285. assertTrue(file1.setLastModified(file1.lastModified() - 5000));
  286. File file2 = writeTrashFile("file2.txt", "content2");
  287. assertTrue(file2.setLastModified(file2.lastModified() - 5000));
  288. File file3 = writeTrashFile("file3.txt", "content3");
  289. assertTrue(file3.setLastModified(file3.lastModified() - 5000));
  290. assertNotNull(git.add().addFilepattern("file1.txt")
  291. .addFilepattern("file2.txt").addFilepattern("file3.txt").call());
  292. RevCommit commit = git.commit().setMessage("add files").call();
  293. assertNotNull(commit);
  294. DirCache cache = DirCache.read(db.getIndexFile(), db.getFS());
  295. int file1Size = cache.getEntry("file1.txt").getLength();
  296. int file2Size = cache.getEntry("file2.txt").getLength();
  297. int file3Size = cache.getEntry("file3.txt").getLength();
  298. ObjectId file2Id = cache.getEntry("file2.txt").getObjectId();
  299. ObjectId file3Id = cache.getEntry("file3.txt").getObjectId();
  300. assertTrue(file1Size > 0);
  301. assertTrue(file2Size > 0);
  302. assertTrue(file3Size > 0);
  303. // Smudge entries
  304. cache = DirCache.lock(db.getIndexFile(), db.getFS());
  305. cache.getEntry("file1.txt").setLength(0);
  306. cache.getEntry("file2.txt").setLength(0);
  307. cache.getEntry("file3.txt").setLength(0);
  308. cache.write();
  309. assertTrue(cache.commit());
  310. // Verify entries smudged
  311. cache = DirCache.read(db.getIndexFile(), db.getFS());
  312. assertEquals(0, cache.getEntry("file1.txt").getLength());
  313. assertEquals(0, cache.getEntry("file2.txt").getLength());
  314. assertEquals(0, cache.getEntry("file3.txt").getLength());
  315. long indexTime = db.getIndexFile().lastModified();
  316. db.getIndexFile().setLastModified(indexTime - 5000);
  317. write(file1, "content4");
  318. assertTrue(file1.setLastModified(file1.lastModified() + 2500));
  319. assertNotNull(git.commit().setMessage("edit file").setOnly("file1.txt")
  320. .call());
  321. cache = db.readDirCache();
  322. assertEquals(file1Size, cache.getEntry("file1.txt").getLength());
  323. assertEquals(file2Size, cache.getEntry("file2.txt").getLength());
  324. assertEquals(file3Size, cache.getEntry("file3.txt").getLength());
  325. assertEquals(file2Id, cache.getEntry("file2.txt").getObjectId());
  326. assertEquals(file3Id, cache.getEntry("file3.txt").getObjectId());
  327. }
  328. }
  329. @Ignore("very flaky when run with Hudson")
  330. @Test
  331. public void commitIgnoresSmudgedEntryWithDifferentId() throws Exception {
  332. try (Git git = new Git(db)) {
  333. File file1 = writeTrashFile("file1.txt", "content1");
  334. assertTrue(file1.setLastModified(file1.lastModified() - 5000));
  335. File file2 = writeTrashFile("file2.txt", "content2");
  336. assertTrue(file2.setLastModified(file2.lastModified() - 5000));
  337. assertNotNull(git.add().addFilepattern("file1.txt")
  338. .addFilepattern("file2.txt").call());
  339. RevCommit commit = git.commit().setMessage("add files").call();
  340. assertNotNull(commit);
  341. DirCache cache = DirCache.read(db.getIndexFile(), db.getFS());
  342. int file1Size = cache.getEntry("file1.txt").getLength();
  343. int file2Size = cache.getEntry("file2.txt").getLength();
  344. assertTrue(file1Size > 0);
  345. assertTrue(file2Size > 0);
  346. writeTrashFile("file2.txt", "content3");
  347. assertNotNull(git.add().addFilepattern("file2.txt").call());
  348. writeTrashFile("file2.txt", "content4");
  349. // Smudge entries
  350. cache = DirCache.lock(db.getIndexFile(), db.getFS());
  351. cache.getEntry("file1.txt").setLength(0);
  352. cache.getEntry("file2.txt").setLength(0);
  353. cache.write();
  354. assertTrue(cache.commit());
  355. // Verify entries smudged
  356. cache = db.readDirCache();
  357. assertEquals(0, cache.getEntry("file1.txt").getLength());
  358. assertEquals(0, cache.getEntry("file2.txt").getLength());
  359. long indexTime = db.getIndexFile().lastModified();
  360. db.getIndexFile().setLastModified(indexTime - 5000);
  361. write(file1, "content5");
  362. assertTrue(file1.setLastModified(file1.lastModified() + 1000));
  363. assertNotNull(git.commit().setMessage("edit file").setOnly("file1.txt")
  364. .call());
  365. cache = db.readDirCache();
  366. assertEquals(file1Size, cache.getEntry("file1.txt").getLength());
  367. assertEquals(0, cache.getEntry("file2.txt").getLength());
  368. }
  369. }
  370. @Test
  371. public void commitAfterSquashMerge() throws Exception {
  372. try (Git git = new Git(db)) {
  373. writeTrashFile("file1", "file1");
  374. git.add().addFilepattern("file1").call();
  375. RevCommit first = git.commit().setMessage("initial commit").call();
  376. assertTrue(new File(db.getWorkTree(), "file1").exists());
  377. createBranch(first, "refs/heads/branch1");
  378. checkoutBranch("refs/heads/branch1");
  379. writeTrashFile("file2", "file2");
  380. git.add().addFilepattern("file2").call();
  381. git.commit().setMessage("second commit").call();
  382. assertTrue(new File(db.getWorkTree(), "file2").exists());
  383. checkoutBranch("refs/heads/master");
  384. MergeResult result = git.merge()
  385. .include(db.exactRef("refs/heads/branch1"))
  386. .setSquash(true)
  387. .call();
  388. assertTrue(new File(db.getWorkTree(), "file1").exists());
  389. assertTrue(new File(db.getWorkTree(), "file2").exists());
  390. assertEquals(MergeResult.MergeStatus.FAST_FORWARD_SQUASHED,
  391. result.getMergeStatus());
  392. // comment not set, should be inferred from SQUASH_MSG
  393. RevCommit squashedCommit = git.commit().call();
  394. assertEquals(1, squashedCommit.getParentCount());
  395. assertNull(db.readSquashCommitMsg());
  396. assertEquals("commit: Squashed commit of the following:", db
  397. .getReflogReader(Constants.HEAD).getLastEntry().getComment());
  398. assertEquals("commit: Squashed commit of the following:", db
  399. .getReflogReader(db.getBranch()).getLastEntry().getComment());
  400. }
  401. }
  402. @Test
  403. public void testReflogs() throws Exception {
  404. try (Git git = new Git(db)) {
  405. writeTrashFile("f", "1");
  406. git.add().addFilepattern("f").call();
  407. git.commit().setMessage("c1").call();
  408. writeTrashFile("f", "2");
  409. git.commit().setMessage("c2").setAll(true).setReflogComment(null)
  410. .call();
  411. writeTrashFile("f", "3");
  412. git.commit().setMessage("c3").setAll(true)
  413. .setReflogComment("testRl").call();
  414. db.getReflogReader(Constants.HEAD).getReverseEntries();
  415. assertEquals("testRl;commit (initial): c1;", reflogComments(
  416. db.getReflogReader(Constants.HEAD).getReverseEntries()));
  417. assertEquals("testRl;commit (initial): c1;", reflogComments(
  418. db.getReflogReader(db.getBranch()).getReverseEntries()));
  419. }
  420. }
  421. private static String reflogComments(List<ReflogEntry> entries) {
  422. StringBuffer b = new StringBuffer();
  423. for (ReflogEntry e : entries) {
  424. b.append(e.getComment()).append(";");
  425. }
  426. return b.toString();
  427. }
  428. @Test(expected = WrongRepositoryStateException.class)
  429. public void commitAmendOnInitialShouldFail() throws Exception {
  430. try (Git git = new Git(db)) {
  431. git.commit().setAmend(true).setMessage("initial commit").call();
  432. }
  433. }
  434. @Test
  435. public void commitAmendWithoutAuthorShouldSetOriginalAuthorAndAuthorTime()
  436. throws Exception {
  437. try (Git git = new Git(db)) {
  438. writeTrashFile("file1", "file1");
  439. git.add().addFilepattern("file1").call();
  440. final String authorName = "First Author";
  441. final String authorEmail = "author@example.org";
  442. final Date authorDate = new Date(1349621117000L);
  443. PersonIdent firstAuthor = new PersonIdent(authorName, authorEmail,
  444. authorDate, TimeZone.getTimeZone("UTC"));
  445. git.commit().setMessage("initial commit").setAuthor(firstAuthor).call();
  446. RevCommit amended = git.commit().setAmend(true)
  447. .setMessage("amend commit").call();
  448. PersonIdent amendedAuthor = amended.getAuthorIdent();
  449. assertEquals(authorName, amendedAuthor.getName());
  450. assertEquals(authorEmail, amendedAuthor.getEmailAddress());
  451. assertEquals(authorDate.getTime(), amendedAuthor.getWhen().getTime());
  452. }
  453. }
  454. @Test
  455. public void commitAmendWithAuthorShouldUseIt() throws Exception {
  456. try (Git git = new Git(db)) {
  457. writeTrashFile("file1", "file1");
  458. git.add().addFilepattern("file1").call();
  459. git.commit().setMessage("initial commit").call();
  460. RevCommit amended = git.commit().setAmend(true)
  461. .setAuthor("New Author", "newauthor@example.org")
  462. .setMessage("amend commit").call();
  463. PersonIdent amendedAuthor = amended.getAuthorIdent();
  464. assertEquals("New Author", amendedAuthor.getName());
  465. assertEquals("newauthor@example.org", amendedAuthor.getEmailAddress());
  466. }
  467. }
  468. @Test
  469. public void commitEmptyCommits() throws Exception {
  470. try (Git git = new Git(db)) {
  471. writeTrashFile("file1", "file1");
  472. git.add().addFilepattern("file1").call();
  473. RevCommit initial = git.commit().setMessage("initial commit")
  474. .call();
  475. RevCommit emptyFollowUp = git.commit()
  476. .setAuthor("New Author", "newauthor@example.org")
  477. .setMessage("no change").call();
  478. assertNotEquals(initial.getId(), emptyFollowUp.getId());
  479. assertEquals(initial.getTree().getId(),
  480. emptyFollowUp.getTree().getId());
  481. try {
  482. git.commit().setAuthor("New Author", "newauthor@example.org")
  483. .setMessage("again no change").setAllowEmpty(false)
  484. .call();
  485. fail("Didn't get the expected EmptyCommitException");
  486. } catch (EmptyCommitException e) {
  487. // expect this exception
  488. }
  489. // Allow empty commits also when setOnly was set
  490. git.commit().setAuthor("New Author", "newauthor@example.org")
  491. .setMessage("again no change").setOnly("file1")
  492. .setAllowEmpty(true).call();
  493. }
  494. }
  495. @Test
  496. public void commitOnlyShouldCommitUnmergedPathAndNotAffectOthers()
  497. throws Exception {
  498. DirCache index = db.lockDirCache();
  499. DirCacheBuilder builder = index.builder();
  500. addUnmergedEntry("unmerged1", builder);
  501. addUnmergedEntry("unmerged2", builder);
  502. DirCacheEntry other = new DirCacheEntry("other");
  503. other.setFileMode(FileMode.REGULAR_FILE);
  504. builder.add(other);
  505. builder.commit();
  506. writeTrashFile("unmerged1", "unmerged1 data");
  507. writeTrashFile("unmerged2", "unmerged2 data");
  508. writeTrashFile("other", "other data");
  509. assertEquals("[other, mode:100644]"
  510. + "[unmerged1, mode:100644, stage:1]"
  511. + "[unmerged1, mode:100644, stage:2]"
  512. + "[unmerged1, mode:100644, stage:3]"
  513. + "[unmerged2, mode:100644, stage:1]"
  514. + "[unmerged2, mode:100644, stage:2]"
  515. + "[unmerged2, mode:100644, stage:3]",
  516. indexState(0));
  517. try (Git git = new Git(db)) {
  518. RevCommit commit = git.commit().setOnly("unmerged1")
  519. .setMessage("Only one file").call();
  520. assertEquals("[other, mode:100644]" + "[unmerged1, mode:100644]"
  521. + "[unmerged2, mode:100644, stage:1]"
  522. + "[unmerged2, mode:100644, stage:2]"
  523. + "[unmerged2, mode:100644, stage:3]",
  524. indexState(0));
  525. try (TreeWalk walk = TreeWalk.forPath(db, "unmerged1", commit.getTree())) {
  526. assertEquals(FileMode.REGULAR_FILE, walk.getFileMode(0));
  527. }
  528. }
  529. }
  530. @Test
  531. public void commitOnlyShouldHandleIgnored() throws Exception {
  532. try (Git git = new Git(db)) {
  533. writeTrashFile("subdir/foo", "Hello World");
  534. writeTrashFile("subdir/bar", "Hello World");
  535. writeTrashFile(".gitignore", "bar");
  536. git.add().addFilepattern("subdir").call();
  537. git.commit().setOnly("subdir").setMessage("first commit").call();
  538. assertEquals("[subdir/foo, mode:100644, content:Hello World]",
  539. indexState(CONTENT));
  540. }
  541. }
  542. @Test
  543. public void commitWithAutoCrlfAndNonNormalizedIndex() throws Exception {
  544. try (Git git = new Git(db)) {
  545. // Commit a file with CR/LF into the index
  546. FileBasedConfig config = db.getConfig();
  547. config.setString("core", null, "autocrlf", "false");
  548. config.save();
  549. writeTrashFile("file.txt", "line 1\r\nline 2\r\n");
  550. git.add().addFilepattern("file.txt").call();
  551. git.commit().setMessage("Initial").call();
  552. assertEquals(
  553. "[file.txt, mode:100644, content:line 1\r\nline 2\r\n]",
  554. indexState(CONTENT));
  555. config.setString("core", null, "autocrlf", "true");
  556. config.save();
  557. writeTrashFile("file.txt", "line 1\r\nline 1.5\r\nline 2\r\n");
  558. writeTrashFile("file2.txt", "new\r\nfile\r\n");
  559. git.add().addFilepattern("file.txt").addFilepattern("file2.txt")
  560. .call();
  561. git.commit().setMessage("Second").call();
  562. assertEquals(
  563. "[file.txt, mode:100644, content:line 1\r\nline 1.5\r\nline 2\r\n]"
  564. + "[file2.txt, mode:100644, content:new\nfile\n]",
  565. indexState(CONTENT));
  566. writeTrashFile("file2.txt", "new\r\nfile\r\ncontent\r\n");
  567. git.add().addFilepattern("file2.txt").call();
  568. git.commit().setMessage("Third").call();
  569. assertEquals(
  570. "[file.txt, mode:100644, content:line 1\r\nline 1.5\r\nline 2\r\n]"
  571. + "[file2.txt, mode:100644, content:new\nfile\ncontent\n]",
  572. indexState(CONTENT));
  573. }
  574. }
  575. private void testConflictWithAutoCrlf(String baseLf, String lf)
  576. throws Exception {
  577. try (Git git = new Git(db)) {
  578. // Commit a file with CR/LF into the index
  579. FileBasedConfig config = db.getConfig();
  580. config.setString("core", null, "autocrlf", "false");
  581. config.save();
  582. writeTrashFile("file.txt", "foo" + baseLf);
  583. git.add().addFilepattern("file.txt").call();
  584. git.commit().setMessage("Initial").call();
  585. // Switch to side branch
  586. git.checkout().setCreateBranch(true).setName("side").call();
  587. writeTrashFile("file.txt", "bar\r\n");
  588. git.add().addFilepattern("file.txt").call();
  589. RevCommit side = git.commit().setMessage("Side").call();
  590. // Switch back to master and commit a conflict with the given lf
  591. git.checkout().setName("master");
  592. writeTrashFile("file.txt", "foob" + lf);
  593. git.add().addFilepattern("file.txt").call();
  594. git.commit().setMessage("Second").call();
  595. // Switch on autocrlf=true
  596. config.setString("core", null, "autocrlf", "true");
  597. config.save();
  598. // Cherry pick side: conflict. Resolve with CR-LF and commit.
  599. CherryPickResult pick = git.cherryPick().include(side).call();
  600. assertEquals("Expected a cherry-pick conflict",
  601. CherryPickStatus.CONFLICTING, pick.getStatus());
  602. writeTrashFile("file.txt", "foobar\r\n");
  603. git.add().addFilepattern("file.txt").call();
  604. git.commit().setMessage("Second").call();
  605. assertEquals("[file.txt, mode:100644, content:foobar" + lf + "]",
  606. indexState(CONTENT));
  607. }
  608. }
  609. @Test
  610. public void commitConflictWithAutoCrlfBaseCrLfOursLf() throws Exception {
  611. testConflictWithAutoCrlf("\r\n", "\n");
  612. }
  613. @Test
  614. public void commitConflictWithAutoCrlfBaseLfOursLf() throws Exception {
  615. testConflictWithAutoCrlf("\n", "\n");
  616. }
  617. @Test
  618. public void commitConflictWithAutoCrlfBasCrLfOursCrLf() throws Exception {
  619. testConflictWithAutoCrlf("\r\n", "\r\n");
  620. }
  621. @Test
  622. public void commitConflictWithAutoCrlfBaseLfOursCrLf() throws Exception {
  623. testConflictWithAutoCrlf("\n", "\r\n");
  624. }
  625. private static void addUnmergedEntry(String file, DirCacheBuilder builder) {
  626. DirCacheEntry stage1 = new DirCacheEntry(file, DirCacheEntry.STAGE_1);
  627. DirCacheEntry stage2 = new DirCacheEntry(file, DirCacheEntry.STAGE_2);
  628. DirCacheEntry stage3 = new DirCacheEntry(file, DirCacheEntry.STAGE_3);
  629. stage1.setFileMode(FileMode.REGULAR_FILE);
  630. stage2.setFileMode(FileMode.REGULAR_FILE);
  631. stage3.setFileMode(FileMode.REGULAR_FILE);
  632. builder.add(stage1);
  633. builder.add(stage2);
  634. builder.add(stage3);
  635. }
  636. @Test
  637. public void callSignerWithProperSigningKey() throws Exception {
  638. try (Git git = new Git(db)) {
  639. writeTrashFile("file1", "file1");
  640. git.add().addFilepattern("file1").call();
  641. String[] signingKey = new String[1];
  642. PersonIdent[] signingCommitters = new PersonIdent[1];
  643. AtomicInteger callCount = new AtomicInteger();
  644. GpgSigner.setDefault(new GpgSigner() {
  645. @Override
  646. public void sign(CommitBuilder commit, String gpgSigningKey,
  647. PersonIdent signingCommitter, CredentialsProvider credentialsProvider) {
  648. signingKey[0] = gpgSigningKey;
  649. signingCommitters[0] = signingCommitter;
  650. callCount.incrementAndGet();
  651. }
  652. @Override
  653. public boolean canLocateSigningKey(String gpgSigningKey,
  654. PersonIdent signingCommitter,
  655. CredentialsProvider credentialsProvider)
  656. throws CanceledException {
  657. return false;
  658. }
  659. });
  660. // first call should use config, which is expected to be null at
  661. // this time
  662. git.commit().setCommitter(committer).setSign(Boolean.TRUE)
  663. .setMessage("initial commit")
  664. .call();
  665. assertNull(signingKey[0]);
  666. assertEquals(1, callCount.get());
  667. assertSame(committer, signingCommitters[0]);
  668. writeTrashFile("file2", "file2");
  669. git.add().addFilepattern("file2").call();
  670. // second commit applies config value
  671. String expectedConfigSigningKey = "config-" + System.nanoTime();
  672. StoredConfig config = git.getRepository().getConfig();
  673. config.setString("user", null, "signingKey",
  674. expectedConfigSigningKey);
  675. config.save();
  676. git.commit().setCommitter(committer).setSign(Boolean.TRUE)
  677. .setMessage("initial commit")
  678. .call();
  679. assertEquals(expectedConfigSigningKey, signingKey[0]);
  680. assertEquals(2, callCount.get());
  681. assertSame(committer, signingCommitters[0]);
  682. writeTrashFile("file3", "file3");
  683. git.add().addFilepattern("file3").call();
  684. // now use specific on api
  685. String expectedSigningKey = "my-" + System.nanoTime();
  686. git.commit().setCommitter(committer).setSign(Boolean.TRUE)
  687. .setSigningKey(expectedSigningKey)
  688. .setMessage("initial commit").call();
  689. assertEquals(expectedSigningKey, signingKey[0]);
  690. assertEquals(3, callCount.get());
  691. assertSame(committer, signingCommitters[0]);
  692. }
  693. }
  694. @Test
  695. public void callSignerOnlyWhenSigning() throws Exception {
  696. try (Git git = new Git(db)) {
  697. writeTrashFile("file1", "file1");
  698. git.add().addFilepattern("file1").call();
  699. AtomicInteger callCount = new AtomicInteger();
  700. GpgSigner.setDefault(new GpgSigner() {
  701. @Override
  702. public void sign(CommitBuilder commit, String gpgSigningKey,
  703. PersonIdent signingCommitter, CredentialsProvider credentialsProvider) {
  704. callCount.incrementAndGet();
  705. }
  706. @Override
  707. public boolean canLocateSigningKey(String gpgSigningKey,
  708. PersonIdent signingCommitter,
  709. CredentialsProvider credentialsProvider)
  710. throws CanceledException {
  711. return false;
  712. }
  713. });
  714. // first call should use config, which is expected to be null at
  715. // this time
  716. git.commit().setMessage("initial commit").call();
  717. assertEquals(0, callCount.get());
  718. writeTrashFile("file2", "file2");
  719. git.add().addFilepattern("file2").call();
  720. // now force signing
  721. git.commit().setSign(Boolean.TRUE).setMessage("commit").call();
  722. assertEquals(1, callCount.get());
  723. writeTrashFile("file3", "file3");
  724. git.add().addFilepattern("file3").call();
  725. // now rely on config
  726. StoredConfig config = git.getRepository().getConfig();
  727. config.setBoolean("commit", null, "gpgSign", true);
  728. config.save();
  729. git.commit().setMessage("commit").call();
  730. assertEquals(2, callCount.get());
  731. writeTrashFile("file4", "file4");
  732. git.add().addFilepattern("file4").call();
  733. // now force "no-sign" (even though config is true)
  734. git.commit().setSign(Boolean.FALSE).setMessage("commit").call();
  735. assertEquals(2, callCount.get());
  736. }
  737. }
  738. }