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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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.errors.EmptyCommitException;
  57. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  58. import org.eclipse.jgit.diff.DiffEntry;
  59. import org.eclipse.jgit.dircache.DirCache;
  60. import org.eclipse.jgit.dircache.DirCacheBuilder;
  61. import org.eclipse.jgit.dircache.DirCacheEntry;
  62. import org.eclipse.jgit.junit.RepositoryTestCase;
  63. import org.eclipse.jgit.lib.CommitBuilder;
  64. import org.eclipse.jgit.lib.ConfigConstants;
  65. import org.eclipse.jgit.lib.Constants;
  66. import org.eclipse.jgit.lib.FileMode;
  67. import org.eclipse.jgit.lib.GpgSigner;
  68. import org.eclipse.jgit.lib.ObjectId;
  69. import org.eclipse.jgit.lib.PersonIdent;
  70. import org.eclipse.jgit.lib.RefUpdate;
  71. import org.eclipse.jgit.lib.RefUpdate.Result;
  72. import org.eclipse.jgit.lib.ReflogEntry;
  73. import org.eclipse.jgit.lib.Repository;
  74. import org.eclipse.jgit.lib.StoredConfig;
  75. import org.eclipse.jgit.revwalk.RevCommit;
  76. import org.eclipse.jgit.submodule.SubmoduleWalk;
  77. import org.eclipse.jgit.transport.CredentialsProvider;
  78. import org.eclipse.jgit.treewalk.TreeWalk;
  79. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  80. import org.eclipse.jgit.util.FS;
  81. import org.junit.Ignore;
  82. import org.junit.Test;
  83. /**
  84. * Unit tests of {@link CommitCommand}.
  85. */
  86. public class CommitCommandTest extends RepositoryTestCase {
  87. @Test
  88. public void testExecutableRetention() throws Exception {
  89. StoredConfig config = db.getConfig();
  90. config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  91. ConfigConstants.CONFIG_KEY_FILEMODE, true);
  92. config.save();
  93. FS executableFs = new FS() {
  94. @Override
  95. public boolean supportsExecute() {
  96. return true;
  97. }
  98. @Override
  99. public boolean setExecute(File f, boolean canExec) {
  100. return true;
  101. }
  102. @Override
  103. public ProcessBuilder runInShell(String cmd, String[] args) {
  104. return null;
  105. }
  106. @Override
  107. public boolean retryFailedLockFileCommit() {
  108. return false;
  109. }
  110. @Override
  111. public FS newInstance() {
  112. return this;
  113. }
  114. @Override
  115. protected File discoverGitExe() {
  116. return null;
  117. }
  118. @Override
  119. public boolean canExecute(File f) {
  120. return true;
  121. }
  122. @Override
  123. public boolean isCaseSensitive() {
  124. return true;
  125. }
  126. };
  127. Git git = Git.open(db.getDirectory(), executableFs);
  128. String path = "a.txt";
  129. writeTrashFile(path, "content");
  130. git.add().addFilepattern(path).call();
  131. RevCommit commit1 = git.commit().setMessage("commit").call();
  132. TreeWalk walk = TreeWalk.forPath(db, path, commit1.getTree());
  133. assertNotNull(walk);
  134. assertEquals(FileMode.EXECUTABLE_FILE, walk.getFileMode(0));
  135. FS nonExecutableFs = new FS() {
  136. @Override
  137. public boolean supportsExecute() {
  138. return false;
  139. }
  140. @Override
  141. public boolean setExecute(File f, boolean canExec) {
  142. return false;
  143. }
  144. @Override
  145. public ProcessBuilder runInShell(String cmd, String[] args) {
  146. return null;
  147. }
  148. @Override
  149. public boolean retryFailedLockFileCommit() {
  150. return false;
  151. }
  152. @Override
  153. public FS newInstance() {
  154. return this;
  155. }
  156. @Override
  157. protected File discoverGitExe() {
  158. return null;
  159. }
  160. @Override
  161. public boolean canExecute(File f) {
  162. return false;
  163. }
  164. @Override
  165. public boolean isCaseSensitive() {
  166. return true;
  167. }
  168. };
  169. config = db.getConfig();
  170. config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null,
  171. ConfigConstants.CONFIG_KEY_FILEMODE, false);
  172. config.save();
  173. Git git2 = Git.open(db.getDirectory(), nonExecutableFs);
  174. writeTrashFile(path, "content2");
  175. RevCommit commit2 = git2.commit().setOnly(path).setMessage("commit2")
  176. .call();
  177. walk = TreeWalk.forPath(db, path, commit2.getTree());
  178. assertNotNull(walk);
  179. assertEquals(FileMode.EXECUTABLE_FILE, walk.getFileMode(0));
  180. }
  181. @Test
  182. public void commitNewSubmodule() throws Exception {
  183. try (Git git = new Git(db)) {
  184. writeTrashFile("file.txt", "content");
  185. git.add().addFilepattern("file.txt").call();
  186. RevCommit commit = git.commit().setMessage("create file").call();
  187. SubmoduleAddCommand command = new SubmoduleAddCommand(db);
  188. String path = "sub";
  189. command.setPath(path);
  190. String uri = db.getDirectory().toURI().toString();
  191. command.setURI(uri);
  192. Repository repo = command.call();
  193. assertNotNull(repo);
  194. addRepoToClose(repo);
  195. SubmoduleWalk generator = SubmoduleWalk.forIndex(db);
  196. assertTrue(generator.next());
  197. assertEquals(path, generator.getPath());
  198. assertEquals(commit, generator.getObjectId());
  199. assertEquals(uri, generator.getModulesUrl());
  200. assertEquals(path, generator.getModulesPath());
  201. assertEquals(uri, generator.getConfigUrl());
  202. try (Repository subModRepo = generator.getRepository()) {
  203. assertNotNull(subModRepo);
  204. }
  205. assertEquals(commit, repo.resolve(Constants.HEAD));
  206. RevCommit submoduleCommit = git.commit().setMessage("submodule add")
  207. .setOnly(path).call();
  208. assertNotNull(submoduleCommit);
  209. try (TreeWalk walk = new TreeWalk(db)) {
  210. walk.addTree(commit.getTree());
  211. walk.addTree(submoduleCommit.getTree());
  212. walk.setFilter(TreeFilter.ANY_DIFF);
  213. List<DiffEntry> diffs = DiffEntry.scan(walk);
  214. assertEquals(1, diffs.size());
  215. DiffEntry subDiff = diffs.get(0);
  216. assertEquals(FileMode.MISSING, subDiff.getOldMode());
  217. assertEquals(FileMode.GITLINK, subDiff.getNewMode());
  218. assertEquals(ObjectId.zeroId(), subDiff.getOldId().toObjectId());
  219. assertEquals(commit, subDiff.getNewId().toObjectId());
  220. assertEquals(path, subDiff.getNewPath());
  221. }
  222. }
  223. }
  224. @Test
  225. public void commitSubmoduleUpdate() throws Exception {
  226. try (Git git = new Git(db)) {
  227. writeTrashFile("file.txt", "content");
  228. git.add().addFilepattern("file.txt").call();
  229. RevCommit commit = git.commit().setMessage("create file").call();
  230. writeTrashFile("file.txt", "content2");
  231. git.add().addFilepattern("file.txt").call();
  232. RevCommit commit2 = git.commit().setMessage("edit file").call();
  233. SubmoduleAddCommand command = new SubmoduleAddCommand(db);
  234. String path = "sub";
  235. command.setPath(path);
  236. String uri = db.getDirectory().toURI().toString();
  237. command.setURI(uri);
  238. Repository repo = command.call();
  239. assertNotNull(repo);
  240. addRepoToClose(repo);
  241. SubmoduleWalk generator = SubmoduleWalk.forIndex(db);
  242. assertTrue(generator.next());
  243. assertEquals(path, generator.getPath());
  244. assertEquals(commit2, generator.getObjectId());
  245. assertEquals(uri, generator.getModulesUrl());
  246. assertEquals(path, generator.getModulesPath());
  247. assertEquals(uri, generator.getConfigUrl());
  248. try (Repository subModRepo = generator.getRepository()) {
  249. assertNotNull(subModRepo);
  250. }
  251. assertEquals(commit2, repo.resolve(Constants.HEAD));
  252. RevCommit submoduleAddCommit = git.commit().setMessage("submodule add")
  253. .setOnly(path).call();
  254. assertNotNull(submoduleAddCommit);
  255. RefUpdate update = repo.updateRef(Constants.HEAD);
  256. update.setNewObjectId(commit);
  257. assertEquals(Result.FORCED, update.forceUpdate());
  258. RevCommit submoduleEditCommit = git.commit()
  259. .setMessage("submodule add").setOnly(path).call();
  260. assertNotNull(submoduleEditCommit);
  261. try (TreeWalk walk = new TreeWalk(db)) {
  262. walk.addTree(submoduleAddCommit.getTree());
  263. walk.addTree(submoduleEditCommit.getTree());
  264. walk.setFilter(TreeFilter.ANY_DIFF);
  265. List<DiffEntry> diffs = DiffEntry.scan(walk);
  266. assertEquals(1, diffs.size());
  267. DiffEntry subDiff = diffs.get(0);
  268. assertEquals(FileMode.GITLINK, subDiff.getOldMode());
  269. assertEquals(FileMode.GITLINK, subDiff.getNewMode());
  270. assertEquals(commit2, subDiff.getOldId().toObjectId());
  271. assertEquals(commit, subDiff.getNewId().toObjectId());
  272. assertEquals(path, subDiff.getNewPath());
  273. assertEquals(path, subDiff.getOldPath());
  274. }
  275. }
  276. }
  277. @Ignore("very flaky when run with Hudson")
  278. @Test
  279. public void commitUpdatesSmudgedEntries() throws Exception {
  280. try (Git git = new Git(db)) {
  281. File file1 = writeTrashFile("file1.txt", "content1");
  282. assertTrue(file1.setLastModified(file1.lastModified() - 5000));
  283. File file2 = writeTrashFile("file2.txt", "content2");
  284. assertTrue(file2.setLastModified(file2.lastModified() - 5000));
  285. File file3 = writeTrashFile("file3.txt", "content3");
  286. assertTrue(file3.setLastModified(file3.lastModified() - 5000));
  287. assertNotNull(git.add().addFilepattern("file1.txt")
  288. .addFilepattern("file2.txt").addFilepattern("file3.txt").call());
  289. RevCommit commit = git.commit().setMessage("add files").call();
  290. assertNotNull(commit);
  291. DirCache cache = DirCache.read(db.getIndexFile(), db.getFS());
  292. int file1Size = cache.getEntry("file1.txt").getLength();
  293. int file2Size = cache.getEntry("file2.txt").getLength();
  294. int file3Size = cache.getEntry("file3.txt").getLength();
  295. ObjectId file2Id = cache.getEntry("file2.txt").getObjectId();
  296. ObjectId file3Id = cache.getEntry("file3.txt").getObjectId();
  297. assertTrue(file1Size > 0);
  298. assertTrue(file2Size > 0);
  299. assertTrue(file3Size > 0);
  300. // Smudge entries
  301. cache = DirCache.lock(db.getIndexFile(), db.getFS());
  302. cache.getEntry("file1.txt").setLength(0);
  303. cache.getEntry("file2.txt").setLength(0);
  304. cache.getEntry("file3.txt").setLength(0);
  305. cache.write();
  306. assertTrue(cache.commit());
  307. // Verify entries smudged
  308. cache = DirCache.read(db.getIndexFile(), db.getFS());
  309. assertEquals(0, cache.getEntry("file1.txt").getLength());
  310. assertEquals(0, cache.getEntry("file2.txt").getLength());
  311. assertEquals(0, cache.getEntry("file3.txt").getLength());
  312. long indexTime = db.getIndexFile().lastModified();
  313. db.getIndexFile().setLastModified(indexTime - 5000);
  314. write(file1, "content4");
  315. assertTrue(file1.setLastModified(file1.lastModified() + 2500));
  316. assertNotNull(git.commit().setMessage("edit file").setOnly("file1.txt")
  317. .call());
  318. cache = db.readDirCache();
  319. assertEquals(file1Size, cache.getEntry("file1.txt").getLength());
  320. assertEquals(file2Size, cache.getEntry("file2.txt").getLength());
  321. assertEquals(file3Size, cache.getEntry("file3.txt").getLength());
  322. assertEquals(file2Id, cache.getEntry("file2.txt").getObjectId());
  323. assertEquals(file3Id, cache.getEntry("file3.txt").getObjectId());
  324. }
  325. }
  326. @Ignore("very flaky when run with Hudson")
  327. @Test
  328. public void commitIgnoresSmudgedEntryWithDifferentId() throws Exception {
  329. try (Git git = new Git(db)) {
  330. File file1 = writeTrashFile("file1.txt", "content1");
  331. assertTrue(file1.setLastModified(file1.lastModified() - 5000));
  332. File file2 = writeTrashFile("file2.txt", "content2");
  333. assertTrue(file2.setLastModified(file2.lastModified() - 5000));
  334. assertNotNull(git.add().addFilepattern("file1.txt")
  335. .addFilepattern("file2.txt").call());
  336. RevCommit commit = git.commit().setMessage("add files").call();
  337. assertNotNull(commit);
  338. DirCache cache = DirCache.read(db.getIndexFile(), db.getFS());
  339. int file1Size = cache.getEntry("file1.txt").getLength();
  340. int file2Size = cache.getEntry("file2.txt").getLength();
  341. assertTrue(file1Size > 0);
  342. assertTrue(file2Size > 0);
  343. writeTrashFile("file2.txt", "content3");
  344. assertNotNull(git.add().addFilepattern("file2.txt").call());
  345. writeTrashFile("file2.txt", "content4");
  346. // Smudge entries
  347. cache = DirCache.lock(db.getIndexFile(), db.getFS());
  348. cache.getEntry("file1.txt").setLength(0);
  349. cache.getEntry("file2.txt").setLength(0);
  350. cache.write();
  351. assertTrue(cache.commit());
  352. // Verify entries smudged
  353. cache = db.readDirCache();
  354. assertEquals(0, cache.getEntry("file1.txt").getLength());
  355. assertEquals(0, cache.getEntry("file2.txt").getLength());
  356. long indexTime = db.getIndexFile().lastModified();
  357. db.getIndexFile().setLastModified(indexTime - 5000);
  358. write(file1, "content5");
  359. assertTrue(file1.setLastModified(file1.lastModified() + 1000));
  360. assertNotNull(git.commit().setMessage("edit file").setOnly("file1.txt")
  361. .call());
  362. cache = db.readDirCache();
  363. assertEquals(file1Size, cache.getEntry("file1.txt").getLength());
  364. assertEquals(0, cache.getEntry("file2.txt").getLength());
  365. }
  366. }
  367. @Test
  368. public void commitAfterSquashMerge() throws Exception {
  369. try (Git git = new Git(db)) {
  370. writeTrashFile("file1", "file1");
  371. git.add().addFilepattern("file1").call();
  372. RevCommit first = git.commit().setMessage("initial commit").call();
  373. assertTrue(new File(db.getWorkTree(), "file1").exists());
  374. createBranch(first, "refs/heads/branch1");
  375. checkoutBranch("refs/heads/branch1");
  376. writeTrashFile("file2", "file2");
  377. git.add().addFilepattern("file2").call();
  378. git.commit().setMessage("second commit").call();
  379. assertTrue(new File(db.getWorkTree(), "file2").exists());
  380. checkoutBranch("refs/heads/master");
  381. MergeResult result = git.merge()
  382. .include(db.exactRef("refs/heads/branch1"))
  383. .setSquash(true)
  384. .call();
  385. assertTrue(new File(db.getWorkTree(), "file1").exists());
  386. assertTrue(new File(db.getWorkTree(), "file2").exists());
  387. assertEquals(MergeResult.MergeStatus.FAST_FORWARD_SQUASHED,
  388. result.getMergeStatus());
  389. // comment not set, should be inferred from SQUASH_MSG
  390. RevCommit squashedCommit = git.commit().call();
  391. assertEquals(1, squashedCommit.getParentCount());
  392. assertNull(db.readSquashCommitMsg());
  393. assertEquals("commit: Squashed commit of the following:", db
  394. .getReflogReader(Constants.HEAD).getLastEntry().getComment());
  395. assertEquals("commit: Squashed commit of the following:", db
  396. .getReflogReader(db.getBranch()).getLastEntry().getComment());
  397. }
  398. }
  399. @Test
  400. public void testReflogs() throws Exception {
  401. try (Git git = new Git(db)) {
  402. writeTrashFile("f", "1");
  403. git.add().addFilepattern("f").call();
  404. git.commit().setMessage("c1").call();
  405. writeTrashFile("f", "2");
  406. git.commit().setMessage("c2").setAll(true).setReflogComment(null)
  407. .call();
  408. writeTrashFile("f", "3");
  409. git.commit().setMessage("c3").setAll(true)
  410. .setReflogComment("testRl").call();
  411. db.getReflogReader(Constants.HEAD).getReverseEntries();
  412. assertEquals("testRl;commit (initial): c1;", reflogComments(
  413. db.getReflogReader(Constants.HEAD).getReverseEntries()));
  414. assertEquals("testRl;commit (initial): c1;", reflogComments(
  415. db.getReflogReader(db.getBranch()).getReverseEntries()));
  416. }
  417. }
  418. private static String reflogComments(List<ReflogEntry> entries) {
  419. StringBuffer b = new StringBuffer();
  420. for (ReflogEntry e : entries) {
  421. b.append(e.getComment()).append(";");
  422. }
  423. return b.toString();
  424. }
  425. @Test(expected = WrongRepositoryStateException.class)
  426. public void commitAmendOnInitialShouldFail() throws Exception {
  427. try (Git git = new Git(db)) {
  428. git.commit().setAmend(true).setMessage("initial commit").call();
  429. }
  430. }
  431. @Test
  432. public void commitAmendWithoutAuthorShouldSetOriginalAuthorAndAuthorTime()
  433. throws Exception {
  434. try (Git git = new Git(db)) {
  435. writeTrashFile("file1", "file1");
  436. git.add().addFilepattern("file1").call();
  437. final String authorName = "First Author";
  438. final String authorEmail = "author@example.org";
  439. final Date authorDate = new Date(1349621117000L);
  440. PersonIdent firstAuthor = new PersonIdent(authorName, authorEmail,
  441. authorDate, TimeZone.getTimeZone("UTC"));
  442. git.commit().setMessage("initial commit").setAuthor(firstAuthor).call();
  443. RevCommit amended = git.commit().setAmend(true)
  444. .setMessage("amend commit").call();
  445. PersonIdent amendedAuthor = amended.getAuthorIdent();
  446. assertEquals(authorName, amendedAuthor.getName());
  447. assertEquals(authorEmail, amendedAuthor.getEmailAddress());
  448. assertEquals(authorDate.getTime(), amendedAuthor.getWhen().getTime());
  449. }
  450. }
  451. @Test
  452. public void commitAmendWithAuthorShouldUseIt() throws Exception {
  453. try (Git git = new Git(db)) {
  454. writeTrashFile("file1", "file1");
  455. git.add().addFilepattern("file1").call();
  456. git.commit().setMessage("initial commit").call();
  457. RevCommit amended = git.commit().setAmend(true)
  458. .setAuthor("New Author", "newauthor@example.org")
  459. .setMessage("amend commit").call();
  460. PersonIdent amendedAuthor = amended.getAuthorIdent();
  461. assertEquals("New Author", amendedAuthor.getName());
  462. assertEquals("newauthor@example.org", amendedAuthor.getEmailAddress());
  463. }
  464. }
  465. @Test
  466. public void commitEmptyCommits() throws Exception {
  467. try (Git git = new Git(db)) {
  468. writeTrashFile("file1", "file1");
  469. git.add().addFilepattern("file1").call();
  470. RevCommit initial = git.commit().setMessage("initial commit")
  471. .call();
  472. RevCommit emptyFollowUp = git.commit()
  473. .setAuthor("New Author", "newauthor@example.org")
  474. .setMessage("no change").call();
  475. assertNotEquals(initial.getId(), emptyFollowUp.getId());
  476. assertEquals(initial.getTree().getId(),
  477. emptyFollowUp.getTree().getId());
  478. try {
  479. git.commit().setAuthor("New Author", "newauthor@example.org")
  480. .setMessage("again no change").setAllowEmpty(false)
  481. .call();
  482. fail("Didn't get the expected EmptyCommitException");
  483. } catch (EmptyCommitException e) {
  484. // expect this exception
  485. }
  486. // Allow empty commits also when setOnly was set
  487. git.commit().setAuthor("New Author", "newauthor@example.org")
  488. .setMessage("again no change").setOnly("file1")
  489. .setAllowEmpty(true).call();
  490. }
  491. }
  492. @Test
  493. public void commitOnlyShouldCommitUnmergedPathAndNotAffectOthers()
  494. throws Exception {
  495. DirCache index = db.lockDirCache();
  496. DirCacheBuilder builder = index.builder();
  497. addUnmergedEntry("unmerged1", builder);
  498. addUnmergedEntry("unmerged2", builder);
  499. DirCacheEntry other = new DirCacheEntry("other");
  500. other.setFileMode(FileMode.REGULAR_FILE);
  501. builder.add(other);
  502. builder.commit();
  503. writeTrashFile("unmerged1", "unmerged1 data");
  504. writeTrashFile("unmerged2", "unmerged2 data");
  505. writeTrashFile("other", "other data");
  506. assertEquals("[other, mode:100644]"
  507. + "[unmerged1, mode:100644, stage:1]"
  508. + "[unmerged1, mode:100644, stage:2]"
  509. + "[unmerged1, mode:100644, stage:3]"
  510. + "[unmerged2, mode:100644, stage:1]"
  511. + "[unmerged2, mode:100644, stage:2]"
  512. + "[unmerged2, mode:100644, stage:3]",
  513. indexState(0));
  514. try (Git git = new Git(db)) {
  515. RevCommit commit = git.commit().setOnly("unmerged1")
  516. .setMessage("Only one file").call();
  517. assertEquals("[other, mode:100644]" + "[unmerged1, mode:100644]"
  518. + "[unmerged2, mode:100644, stage:1]"
  519. + "[unmerged2, mode:100644, stage:2]"
  520. + "[unmerged2, mode:100644, stage:3]",
  521. indexState(0));
  522. try (TreeWalk walk = TreeWalk.forPath(db, "unmerged1", commit.getTree())) {
  523. assertEquals(FileMode.REGULAR_FILE, walk.getFileMode(0));
  524. }
  525. }
  526. }
  527. @Test
  528. public void commitOnlyShouldHandleIgnored() throws Exception {
  529. try (Git git = new Git(db)) {
  530. writeTrashFile("subdir/foo", "Hello World");
  531. writeTrashFile("subdir/bar", "Hello World");
  532. writeTrashFile(".gitignore", "bar");
  533. git.add().addFilepattern("subdir").call();
  534. git.commit().setOnly("subdir").setMessage("first commit").call();
  535. }
  536. }
  537. private static void addUnmergedEntry(String file, DirCacheBuilder builder) {
  538. DirCacheEntry stage1 = new DirCacheEntry(file, DirCacheEntry.STAGE_1);
  539. DirCacheEntry stage2 = new DirCacheEntry(file, DirCacheEntry.STAGE_2);
  540. DirCacheEntry stage3 = new DirCacheEntry(file, DirCacheEntry.STAGE_3);
  541. stage1.setFileMode(FileMode.REGULAR_FILE);
  542. stage2.setFileMode(FileMode.REGULAR_FILE);
  543. stage3.setFileMode(FileMode.REGULAR_FILE);
  544. builder.add(stage1);
  545. builder.add(stage2);
  546. builder.add(stage3);
  547. }
  548. @Test
  549. public void callSignerWithProperSigningKey() throws Exception {
  550. try (Git git = new Git(db)) {
  551. writeTrashFile("file1", "file1");
  552. git.add().addFilepattern("file1").call();
  553. String[] signingKey = new String[1];
  554. PersonIdent[] signingCommitters = new PersonIdent[1];
  555. AtomicInteger callCount = new AtomicInteger();
  556. GpgSigner.setDefault(new GpgSigner() {
  557. @Override
  558. public void sign(CommitBuilder commit, String gpgSigningKey,
  559. PersonIdent signingCommitter, CredentialsProvider credentialsProvider) {
  560. signingKey[0] = gpgSigningKey;
  561. signingCommitters[0] = signingCommitter;
  562. callCount.incrementAndGet();
  563. }
  564. });
  565. // first call should use config, which is expected to be null at
  566. // this time
  567. git.commit().setCommitter(committer).setSign(Boolean.TRUE)
  568. .setMessage("initial commit")
  569. .call();
  570. assertNull(signingKey[0]);
  571. assertEquals(1, callCount.get());
  572. assertSame(committer, signingCommitters[0]);
  573. writeTrashFile("file2", "file2");
  574. git.add().addFilepattern("file2").call();
  575. // second commit applies config value
  576. String expectedConfigSigningKey = "config-" + System.nanoTime();
  577. StoredConfig config = git.getRepository().getConfig();
  578. config.setString("user", null, "signingKey",
  579. expectedConfigSigningKey);
  580. config.save();
  581. git.commit().setCommitter(committer).setSign(Boolean.TRUE)
  582. .setMessage("initial commit")
  583. .call();
  584. assertEquals(expectedConfigSigningKey, signingKey[0]);
  585. assertEquals(2, callCount.get());
  586. assertSame(committer, signingCommitters[0]);
  587. writeTrashFile("file3", "file3");
  588. git.add().addFilepattern("file3").call();
  589. // now use specific on api
  590. String expectedSigningKey = "my-" + System.nanoTime();
  591. git.commit().setCommitter(committer).setSign(Boolean.TRUE)
  592. .setSigningKey(expectedSigningKey)
  593. .setMessage("initial commit").call();
  594. assertEquals(expectedSigningKey, signingKey[0]);
  595. assertEquals(3, callCount.get());
  596. assertSame(committer, signingCommitters[0]);
  597. }
  598. }
  599. @Test
  600. public void callSignerOnlyWhenSigning() throws Exception {
  601. try (Git git = new Git(db)) {
  602. writeTrashFile("file1", "file1");
  603. git.add().addFilepattern("file1").call();
  604. AtomicInteger callCount = new AtomicInteger();
  605. GpgSigner.setDefault(new GpgSigner() {
  606. @Override
  607. public void sign(CommitBuilder commit, String gpgSigningKey,
  608. PersonIdent signingCommitter, CredentialsProvider credentialsProvider) {
  609. callCount.incrementAndGet();
  610. }
  611. });
  612. // first call should use config, which is expected to be null at
  613. // this time
  614. git.commit().setMessage("initial commit").call();
  615. assertEquals(0, callCount.get());
  616. writeTrashFile("file2", "file2");
  617. git.add().addFilepattern("file2").call();
  618. // now force signing
  619. git.commit().setSign(Boolean.TRUE).setMessage("commit").call();
  620. assertEquals(1, callCount.get());
  621. writeTrashFile("file3", "file3");
  622. git.add().addFilepattern("file3").call();
  623. // now rely on config
  624. StoredConfig config = git.getRepository().getConfig();
  625. config.setBoolean("commit", null, "gpgSign", true);
  626. config.save();
  627. git.commit().setMessage("commit").call();
  628. assertEquals(2, callCount.get());
  629. writeTrashFile("file4", "file4");
  630. git.add().addFilepattern("file4").call();
  631. // now force "no-sign" (even though config is true)
  632. git.commit().setSign(Boolean.FALSE).setMessage("commit").call();
  633. assertEquals(2, callCount.get());
  634. }
  635. }
  636. }