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.

CommitCommand.java 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. /*
  2. * Copyright (C) 2010-2012, Christian Halstrick <christian.halstrick@sap.com>
  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 java.io.IOException;
  45. import java.io.InputStream;
  46. import java.io.PrintStream;
  47. import java.text.MessageFormat;
  48. import java.util.ArrayList;
  49. import java.util.Collections;
  50. import java.util.LinkedList;
  51. import java.util.List;
  52. import org.eclipse.jgit.api.errors.AbortedByHookException;
  53. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  54. import org.eclipse.jgit.api.errors.EmtpyCommitException;
  55. import org.eclipse.jgit.api.errors.GitAPIException;
  56. import org.eclipse.jgit.api.errors.JGitInternalException;
  57. import org.eclipse.jgit.api.errors.NoFilepatternException;
  58. import org.eclipse.jgit.api.errors.NoHeadException;
  59. import org.eclipse.jgit.api.errors.NoMessageException;
  60. import org.eclipse.jgit.api.errors.UnmergedPathsException;
  61. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  62. import org.eclipse.jgit.dircache.DirCache;
  63. import org.eclipse.jgit.dircache.DirCacheBuildIterator;
  64. import org.eclipse.jgit.dircache.DirCacheBuilder;
  65. import org.eclipse.jgit.dircache.DirCacheEntry;
  66. import org.eclipse.jgit.dircache.DirCacheIterator;
  67. import org.eclipse.jgit.errors.UnmergedPathException;
  68. import org.eclipse.jgit.hooks.Hooks;
  69. import org.eclipse.jgit.internal.JGitText;
  70. import org.eclipse.jgit.lib.CommitBuilder;
  71. import org.eclipse.jgit.lib.Constants;
  72. import org.eclipse.jgit.lib.FileMode;
  73. import org.eclipse.jgit.lib.ObjectId;
  74. import org.eclipse.jgit.lib.ObjectInserter;
  75. import org.eclipse.jgit.lib.PersonIdent;
  76. import org.eclipse.jgit.lib.Ref;
  77. import org.eclipse.jgit.lib.RefUpdate;
  78. import org.eclipse.jgit.lib.RefUpdate.Result;
  79. import org.eclipse.jgit.lib.Repository;
  80. import org.eclipse.jgit.lib.RepositoryState;
  81. import org.eclipse.jgit.revwalk.RevCommit;
  82. import org.eclipse.jgit.revwalk.RevObject;
  83. import org.eclipse.jgit.revwalk.RevTag;
  84. import org.eclipse.jgit.revwalk.RevWalk;
  85. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  86. import org.eclipse.jgit.treewalk.FileTreeIterator;
  87. import org.eclipse.jgit.treewalk.TreeWalk;
  88. import org.eclipse.jgit.treewalk.TreeWalk.OperationType;
  89. import org.eclipse.jgit.util.ChangeIdUtil;
  90. /**
  91. * A class used to execute a {@code Commit} command. It has setters for all
  92. * supported options and arguments of this command and a {@link #call()} method
  93. * to finally execute the command.
  94. *
  95. * @see <a
  96. * href="http://www.kernel.org/pub/software/scm/git/docs/git-commit.html"
  97. * >Git documentation about Commit</a>
  98. */
  99. public class CommitCommand extends GitCommand<RevCommit> {
  100. private PersonIdent author;
  101. private PersonIdent committer;
  102. private String message;
  103. private boolean all;
  104. private List<String> only = new ArrayList<String>();
  105. private boolean[] onlyProcessed;
  106. private boolean amend;
  107. private boolean insertChangeId;
  108. /**
  109. * parents this commit should have. The current HEAD will be in this list
  110. * and also all commits mentioned in .git/MERGE_HEAD
  111. */
  112. private List<ObjectId> parents = new LinkedList<ObjectId>();
  113. private String reflogComment;
  114. private boolean useDefaultReflogMessage = true;
  115. /**
  116. * Setting this option bypasses the pre-commit and commit-msg hooks.
  117. */
  118. private boolean noVerify;
  119. private PrintStream hookOutRedirect;
  120. private Boolean allowEmpty;
  121. /**
  122. * @param repo
  123. */
  124. protected CommitCommand(Repository repo) {
  125. super(repo);
  126. }
  127. /**
  128. * Executes the {@code commit} command with all the options and parameters
  129. * collected by the setter methods of this class. Each instance of this
  130. * class should only be used for one invocation of the command (means: one
  131. * call to {@link #call()})
  132. *
  133. * @return a {@link RevCommit} object representing the successful commit.
  134. * @throws NoHeadException
  135. * when called on a git repo without a HEAD reference
  136. * @throws NoMessageException
  137. * when called without specifying a commit message
  138. * @throws UnmergedPathsException
  139. * when the current index contained unmerged paths (conflicts)
  140. * @throws ConcurrentRefUpdateException
  141. * when HEAD or branch ref is updated concurrently by someone
  142. * else
  143. * @throws WrongRepositoryStateException
  144. * when repository is not in the right state for committing
  145. * @throws AbortedByHookException
  146. * if there are either pre-commit or commit-msg hooks present in
  147. * the repository and one of them rejects the commit.
  148. */
  149. public RevCommit call() throws GitAPIException, NoHeadException,
  150. NoMessageException, UnmergedPathsException,
  151. ConcurrentRefUpdateException, WrongRepositoryStateException,
  152. AbortedByHookException {
  153. checkCallable();
  154. Collections.sort(only);
  155. try (RevWalk rw = new RevWalk(repo)) {
  156. RepositoryState state = repo.getRepositoryState();
  157. if (!state.canCommit())
  158. throw new WrongRepositoryStateException(MessageFormat.format(
  159. JGitText.get().cannotCommitOnARepoWithState,
  160. state.name()));
  161. if (!noVerify) {
  162. Hooks.preCommit(repo, hookOutRedirect).call();
  163. }
  164. processOptions(state, rw);
  165. if (all && !repo.isBare()) {
  166. try (Git git = new Git(repo)) {
  167. git.add()
  168. .addFilepattern(".") //$NON-NLS-1$
  169. .setUpdate(true).call();
  170. } catch (NoFilepatternException e) {
  171. // should really not happen
  172. throw new JGitInternalException(e.getMessage(), e);
  173. }
  174. }
  175. Ref head = repo.exactRef(Constants.HEAD);
  176. if (head == null)
  177. throw new NoHeadException(
  178. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  179. // determine the current HEAD and the commit it is referring to
  180. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
  181. if (headId == null && amend)
  182. throw new WrongRepositoryStateException(
  183. JGitText.get().commitAmendOnInitialNotPossible);
  184. if (headId != null)
  185. if (amend) {
  186. RevCommit previousCommit = rw.parseCommit(headId);
  187. for (RevCommit p : previousCommit.getParents())
  188. parents.add(p.getId());
  189. if (author == null)
  190. author = previousCommit.getAuthorIdent();
  191. } else {
  192. parents.add(0, headId);
  193. }
  194. if (!noVerify) {
  195. message = Hooks.commitMsg(repo, hookOutRedirect)
  196. .setCommitMessage(message).call();
  197. }
  198. // lock the index
  199. DirCache index = repo.lockDirCache();
  200. try (ObjectInserter odi = repo.newObjectInserter()) {
  201. if (!only.isEmpty())
  202. index = createTemporaryIndex(headId, index, rw);
  203. // Write the index as tree to the object database. This may
  204. // fail for example when the index contains unmerged paths
  205. // (unresolved conflicts)
  206. ObjectId indexTreeId = index.writeTree(odi);
  207. if (insertChangeId)
  208. insertChangeId(indexTreeId);
  209. // Check for empty commits
  210. if (headId != null && !allowEmpty.booleanValue()) {
  211. RevCommit headCommit = rw.parseCommit(headId);
  212. headCommit.getTree();
  213. if (indexTreeId.equals(headCommit.getTree())) {
  214. throw new EmtpyCommitException(
  215. JGitText.get().emptyCommit);
  216. }
  217. }
  218. // Create a Commit object, populate it and write it
  219. CommitBuilder commit = new CommitBuilder();
  220. commit.setCommitter(committer);
  221. commit.setAuthor(author);
  222. commit.setMessage(message);
  223. commit.setParentIds(parents);
  224. commit.setTreeId(indexTreeId);
  225. ObjectId commitId = odi.insert(commit);
  226. odi.flush();
  227. RevCommit revCommit = rw.parseCommit(commitId);
  228. RefUpdate ru = repo.updateRef(Constants.HEAD);
  229. ru.setNewObjectId(commitId);
  230. if (!useDefaultReflogMessage) {
  231. ru.setRefLogMessage(reflogComment, false);
  232. } else {
  233. String prefix = amend ? "commit (amend): " //$NON-NLS-1$
  234. : parents.size() == 0 ? "commit (initial): " //$NON-NLS-1$
  235. : "commit: "; //$NON-NLS-1$
  236. ru.setRefLogMessage(prefix + revCommit.getShortMessage(),
  237. false);
  238. }
  239. if (headId != null)
  240. ru.setExpectedOldObjectId(headId);
  241. else
  242. ru.setExpectedOldObjectId(ObjectId.zeroId());
  243. Result rc = ru.forceUpdate();
  244. switch (rc) {
  245. case NEW:
  246. case FORCED:
  247. case FAST_FORWARD: {
  248. setCallable(false);
  249. if (state == RepositoryState.MERGING_RESOLVED
  250. || isMergeDuringRebase(state)) {
  251. // Commit was successful. Now delete the files
  252. // used for merge commits
  253. repo.writeMergeCommitMsg(null);
  254. repo.writeMergeHeads(null);
  255. } else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
  256. repo.writeMergeCommitMsg(null);
  257. repo.writeCherryPickHead(null);
  258. } else if (state == RepositoryState.REVERTING_RESOLVED) {
  259. repo.writeMergeCommitMsg(null);
  260. repo.writeRevertHead(null);
  261. }
  262. return revCommit;
  263. }
  264. case REJECTED:
  265. case LOCK_FAILURE:
  266. throw new ConcurrentRefUpdateException(
  267. JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
  268. default:
  269. throw new JGitInternalException(MessageFormat.format(
  270. JGitText.get().updatingRefFailed, Constants.HEAD,
  271. commitId.toString(), rc));
  272. }
  273. } finally {
  274. index.unlock();
  275. }
  276. } catch (UnmergedPathException e) {
  277. throw new UnmergedPathsException(e);
  278. } catch (IOException e) {
  279. throw new JGitInternalException(
  280. JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
  281. }
  282. }
  283. private void insertChangeId(ObjectId treeId) {
  284. ObjectId firstParentId = null;
  285. if (!parents.isEmpty())
  286. firstParentId = parents.get(0);
  287. ObjectId changeId = ChangeIdUtil.computeChangeId(treeId, firstParentId,
  288. author, committer, message);
  289. message = ChangeIdUtil.insertId(message, changeId);
  290. if (changeId != null)
  291. message = message.replaceAll("\nChange-Id: I" //$NON-NLS-1$
  292. + ObjectId.zeroId().getName() + "\n", "\nChange-Id: I" //$NON-NLS-1$ //$NON-NLS-2$
  293. + changeId.getName() + "\n"); //$NON-NLS-1$
  294. }
  295. private DirCache createTemporaryIndex(ObjectId headId, DirCache index,
  296. RevWalk rw)
  297. throws IOException {
  298. ObjectInserter inserter = null;
  299. // get DirCacheBuilder for existing index
  300. DirCacheBuilder existingBuilder = index.builder();
  301. // get DirCacheBuilder for newly created in-core index to build a
  302. // temporary index for this commit
  303. DirCache inCoreIndex = DirCache.newInCore();
  304. DirCacheBuilder tempBuilder = inCoreIndex.builder();
  305. onlyProcessed = new boolean[only.size()];
  306. boolean emptyCommit = true;
  307. try (TreeWalk treeWalk = new TreeWalk(repo)) {
  308. treeWalk.setOperationType(OperationType.CHECKIN_OP);
  309. int dcIdx = treeWalk
  310. .addTree(new DirCacheBuildIterator(existingBuilder));
  311. FileTreeIterator fti = new FileTreeIterator(repo);
  312. fti.setDirCacheIterator(treeWalk, 0);
  313. int fIdx = treeWalk.addTree(fti);
  314. int hIdx = -1;
  315. if (headId != null)
  316. hIdx = treeWalk.addTree(rw.parseTree(headId));
  317. treeWalk.setRecursive(true);
  318. String lastAddedFile = null;
  319. while (treeWalk.next()) {
  320. String path = treeWalk.getPathString();
  321. // check if current entry's path matches a specified path
  322. int pos = lookupOnly(path);
  323. CanonicalTreeParser hTree = null;
  324. if (hIdx != -1)
  325. hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
  326. DirCacheIterator dcTree = treeWalk.getTree(dcIdx,
  327. DirCacheIterator.class);
  328. if (pos >= 0) {
  329. // include entry in commit
  330. FileTreeIterator fTree = treeWalk.getTree(fIdx,
  331. FileTreeIterator.class);
  332. // check if entry refers to a tracked file
  333. boolean tracked = dcTree != null || hTree != null;
  334. if (!tracked)
  335. continue;
  336. // for an unmerged path, DirCacheBuildIterator will yield 3
  337. // entries, we only want to add one
  338. if (path.equals(lastAddedFile))
  339. continue;
  340. lastAddedFile = path;
  341. if (fTree != null) {
  342. // create a new DirCacheEntry with data retrieved from
  343. // disk
  344. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  345. long entryLength = fTree.getEntryLength();
  346. dcEntry.setLength(entryLength);
  347. dcEntry.setLastModified(fTree.getEntryLastModified());
  348. dcEntry.setFileMode(fTree.getIndexFileMode(dcTree));
  349. boolean objectExists = (dcTree != null
  350. && fTree.idEqual(dcTree))
  351. || (hTree != null && fTree.idEqual(hTree));
  352. if (objectExists) {
  353. dcEntry.setObjectId(fTree.getEntryObjectId());
  354. } else {
  355. if (FileMode.GITLINK.equals(dcEntry.getFileMode()))
  356. dcEntry.setObjectId(fTree.getEntryObjectId());
  357. else {
  358. // insert object
  359. if (inserter == null)
  360. inserter = repo.newObjectInserter();
  361. long contentLength = fTree
  362. .getEntryContentLength();
  363. InputStream inputStream = fTree
  364. .openEntryStream();
  365. try {
  366. dcEntry.setObjectId(inserter.insert(
  367. Constants.OBJ_BLOB, contentLength,
  368. inputStream));
  369. } finally {
  370. inputStream.close();
  371. }
  372. }
  373. }
  374. // add to existing index
  375. existingBuilder.add(dcEntry);
  376. // add to temporary in-core index
  377. tempBuilder.add(dcEntry);
  378. if (emptyCommit
  379. && (hTree == null || !hTree.idEqual(fTree)
  380. || hTree.getEntryRawMode() != fTree
  381. .getEntryRawMode()))
  382. // this is a change
  383. emptyCommit = false;
  384. } else {
  385. // if no file exists on disk, neither add it to
  386. // index nor to temporary in-core index
  387. if (emptyCommit && hTree != null)
  388. // this is a change
  389. emptyCommit = false;
  390. }
  391. // keep track of processed path
  392. onlyProcessed[pos] = true;
  393. } else {
  394. // add entries from HEAD for all other paths
  395. if (hTree != null) {
  396. // create a new DirCacheEntry with data retrieved from
  397. // HEAD
  398. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  399. dcEntry.setObjectId(hTree.getEntryObjectId());
  400. dcEntry.setFileMode(hTree.getEntryFileMode());
  401. // add to temporary in-core index
  402. tempBuilder.add(dcEntry);
  403. }
  404. // preserve existing entry in index
  405. if (dcTree != null)
  406. existingBuilder.add(dcTree.getDirCacheEntry());
  407. }
  408. }
  409. }
  410. // there must be no unprocessed paths left at this point; otherwise an
  411. // untracked or unknown path has been specified
  412. for (int i = 0; i < onlyProcessed.length; i++)
  413. if (!onlyProcessed[i])
  414. throw new JGitInternalException(MessageFormat.format(
  415. JGitText.get().entryNotFoundByPath, only.get(i)));
  416. // there must be at least one change
  417. if (emptyCommit)
  418. // Would like to throw a EmptyCommitException. But this would break the API
  419. // TODO(ch): Change this in the next release
  420. throw new JGitInternalException(JGitText.get().emptyCommit);
  421. // update index
  422. existingBuilder.commit();
  423. // finish temporary in-core index used for this commit
  424. tempBuilder.finish();
  425. return inCoreIndex;
  426. }
  427. /**
  428. * Look an entry's path up in the list of paths specified by the --only/ -o
  429. * option
  430. *
  431. * In case the complete (file) path (e.g. "d1/d2/f1") cannot be found in
  432. * <code>only</code>, lookup is also tried with (parent) directory paths
  433. * (e.g. "d1/d2" and "d1").
  434. *
  435. * @param pathString
  436. * entry's path
  437. * @return the item's index in <code>only</code>; -1 if no item matches
  438. */
  439. private int lookupOnly(String pathString) {
  440. String p = pathString;
  441. while (true) {
  442. int position = Collections.binarySearch(only, p);
  443. if (position >= 0)
  444. return position;
  445. int l = p.lastIndexOf("/"); //$NON-NLS-1$
  446. if (l < 1)
  447. break;
  448. p = p.substring(0, l);
  449. }
  450. return -1;
  451. }
  452. /**
  453. * Sets default values for not explicitly specified options. Then validates
  454. * that all required data has been provided.
  455. *
  456. * @param state
  457. * the state of the repository we are working on
  458. * @param rw
  459. * the RevWalk to use
  460. *
  461. * @throws NoMessageException
  462. * if the commit message has not been specified
  463. */
  464. private void processOptions(RepositoryState state, RevWalk rw)
  465. throws NoMessageException {
  466. if (committer == null)
  467. committer = new PersonIdent(repo);
  468. if (author == null && !amend)
  469. author = committer;
  470. if (allowEmpty == null)
  471. // JGit allows empty commits by default. Only when pathes are
  472. // specified the commit should not be empty. This behaviour differs
  473. // from native git but can only be adapted in the next release.
  474. // TODO(ch) align the defaults with native git
  475. allowEmpty = (only.isEmpty()) ? Boolean.TRUE : Boolean.FALSE;
  476. // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
  477. if (state == RepositoryState.MERGING_RESOLVED
  478. || isMergeDuringRebase(state)) {
  479. try {
  480. parents = repo.readMergeHeads();
  481. if (parents != null)
  482. for (int i = 0; i < parents.size(); i++) {
  483. RevObject ro = rw.parseAny(parents.get(i));
  484. if (ro instanceof RevTag)
  485. parents.set(i, rw.peel(ro));
  486. }
  487. } catch (IOException e) {
  488. throw new JGitInternalException(MessageFormat.format(
  489. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  490. Constants.MERGE_HEAD, e), e);
  491. }
  492. if (message == null) {
  493. try {
  494. message = repo.readMergeCommitMsg();
  495. } catch (IOException e) {
  496. throw new JGitInternalException(MessageFormat.format(
  497. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  498. Constants.MERGE_MSG, e), e);
  499. }
  500. }
  501. } else if (state == RepositoryState.SAFE && message == null) {
  502. try {
  503. message = repo.readSquashCommitMsg();
  504. if (message != null)
  505. repo.writeSquashCommitMsg(null /* delete */);
  506. } catch (IOException e) {
  507. throw new JGitInternalException(MessageFormat.format(
  508. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  509. Constants.MERGE_MSG, e), e);
  510. }
  511. }
  512. if (message == null)
  513. // as long as we don't support -C option we have to have
  514. // an explicit message
  515. throw new NoMessageException(JGitText.get().commitMessageNotSpecified);
  516. }
  517. private boolean isMergeDuringRebase(RepositoryState state) {
  518. if (state != RepositoryState.REBASING_INTERACTIVE
  519. && state != RepositoryState.REBASING_MERGE)
  520. return false;
  521. try {
  522. return repo.readMergeHeads() != null;
  523. } catch (IOException e) {
  524. throw new JGitInternalException(MessageFormat.format(
  525. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  526. Constants.MERGE_HEAD, e), e);
  527. }
  528. }
  529. /**
  530. * @param message
  531. * the commit message used for the {@code commit}
  532. * @return {@code this}
  533. */
  534. public CommitCommand setMessage(String message) {
  535. checkCallable();
  536. this.message = message;
  537. return this;
  538. }
  539. /**
  540. * @param allowEmpty
  541. * whether it should be allowed to create a commit which has the
  542. * same tree as it's sole predecessor (a commit which doesn't
  543. * change anything). By default when creating standard commits
  544. * (without specifying paths) JGit allows to create such commits.
  545. * When this flag is set to false an attempt to create an "empty"
  546. * standard commit will lead to an EmptyCommitException.
  547. * <p>
  548. * By default when creating a commit containing only specified
  549. * paths an attempt to create an empty commit leads to a
  550. * {@link JGitInternalException}. By setting this flag to
  551. * <code>true</code> this exception will not be thrown.
  552. * @return {@code this}
  553. * @since 4.2
  554. */
  555. public CommitCommand setAllowEmpty(boolean allowEmpty) {
  556. this.allowEmpty = Boolean.valueOf(allowEmpty);
  557. return this;
  558. }
  559. /**
  560. * @return the commit message used for the <code>commit</code>
  561. */
  562. public String getMessage() {
  563. return message;
  564. }
  565. /**
  566. * Sets the committer for this {@code commit}. If no committer is explicitly
  567. * specified because this method is never called or called with {@code null}
  568. * value then the committer will be deduced from config info in repository,
  569. * with current time.
  570. *
  571. * @param committer
  572. * the committer used for the {@code commit}
  573. * @return {@code this}
  574. */
  575. public CommitCommand setCommitter(PersonIdent committer) {
  576. checkCallable();
  577. this.committer = committer;
  578. return this;
  579. }
  580. /**
  581. * Sets the committer for this {@code commit}. If no committer is explicitly
  582. * specified because this method is never called then the committer will be
  583. * deduced from config info in repository, with current time.
  584. *
  585. * @param name
  586. * the name of the committer used for the {@code commit}
  587. * @param email
  588. * the email of the committer used for the {@code commit}
  589. * @return {@code this}
  590. */
  591. public CommitCommand setCommitter(String name, String email) {
  592. checkCallable();
  593. return setCommitter(new PersonIdent(name, email));
  594. }
  595. /**
  596. * @return the committer used for the {@code commit}. If no committer was
  597. * specified {@code null} is returned and the default
  598. * {@link PersonIdent} of this repo is used during execution of the
  599. * command
  600. */
  601. public PersonIdent getCommitter() {
  602. return committer;
  603. }
  604. /**
  605. * Sets the author for this {@code commit}. If no author is explicitly
  606. * specified because this method is never called or called with {@code null}
  607. * value then the author will be set to the committer or to the original
  608. * author when amending.
  609. *
  610. * @param author
  611. * the author used for the {@code commit}
  612. * @return {@code this}
  613. */
  614. public CommitCommand setAuthor(PersonIdent author) {
  615. checkCallable();
  616. this.author = author;
  617. return this;
  618. }
  619. /**
  620. * Sets the author for this {@code commit}. If no author is explicitly
  621. * specified because this method is never called then the author will be set
  622. * to the committer or to the original author when amending.
  623. *
  624. * @param name
  625. * the name of the author used for the {@code commit}
  626. * @param email
  627. * the email of the author used for the {@code commit}
  628. * @return {@code this}
  629. */
  630. public CommitCommand setAuthor(String name, String email) {
  631. checkCallable();
  632. return setAuthor(new PersonIdent(name, email));
  633. }
  634. /**
  635. * @return the author used for the {@code commit}. If no author was
  636. * specified {@code null} is returned and the default
  637. * {@link PersonIdent} of this repo is used during execution of the
  638. * command
  639. */
  640. public PersonIdent getAuthor() {
  641. return author;
  642. }
  643. /**
  644. * If set to true the Commit command automatically stages files that have
  645. * been modified and deleted, but new files not known by the repository are
  646. * not affected. This corresponds to the parameter -a on the command line.
  647. *
  648. * @param all
  649. * @return {@code this}
  650. * @throws JGitInternalException
  651. * in case of an illegal combination of arguments/ options
  652. */
  653. public CommitCommand setAll(boolean all) {
  654. checkCallable();
  655. if (all && !only.isEmpty())
  656. throw new JGitInternalException(MessageFormat.format(
  657. JGitText.get().illegalCombinationOfArguments, "--all", //$NON-NLS-1$
  658. "--only")); //$NON-NLS-1$
  659. this.all = all;
  660. return this;
  661. }
  662. /**
  663. * Used to amend the tip of the current branch. If set to true, the previous
  664. * commit will be amended. This is equivalent to --amend on the command
  665. * line.
  666. *
  667. * @param amend
  668. * @return {@code this}
  669. */
  670. public CommitCommand setAmend(boolean amend) {
  671. checkCallable();
  672. this.amend = amend;
  673. return this;
  674. }
  675. /**
  676. * Commit dedicated path only.
  677. * <p>
  678. * This method can be called several times to add multiple paths. Full file
  679. * paths are supported as well as directory paths; in the latter case this
  680. * commits all files/directories below the specified path.
  681. *
  682. * @param only
  683. * path to commit (with <code>/</code> as separator)
  684. * @return {@code this}
  685. */
  686. public CommitCommand setOnly(String only) {
  687. checkCallable();
  688. if (all)
  689. throw new JGitInternalException(MessageFormat.format(
  690. JGitText.get().illegalCombinationOfArguments, "--only", //$NON-NLS-1$
  691. "--all")); //$NON-NLS-1$
  692. String o = only.endsWith("/") ? only.substring(0, only.length() - 1) //$NON-NLS-1$
  693. : only;
  694. // ignore duplicates
  695. if (!this.only.contains(o))
  696. this.only.add(o);
  697. return this;
  698. }
  699. /**
  700. * If set to true a change id will be inserted into the commit message
  701. *
  702. * An existing change id is not replaced. An initial change id (I000...)
  703. * will be replaced by the change id.
  704. *
  705. * @param insertChangeId
  706. *
  707. * @return {@code this}
  708. */
  709. public CommitCommand setInsertChangeId(boolean insertChangeId) {
  710. checkCallable();
  711. this.insertChangeId = insertChangeId;
  712. return this;
  713. }
  714. /**
  715. * Override the message written to the reflog
  716. *
  717. * @param reflogComment
  718. * the comment to be written into the reflog or <code>null</code>
  719. * to specify that no reflog should be written
  720. * @return {@code this}
  721. */
  722. public CommitCommand setReflogComment(String reflogComment) {
  723. this.reflogComment = reflogComment;
  724. useDefaultReflogMessage = false;
  725. return this;
  726. }
  727. /**
  728. * Sets the {@link #noVerify} option on this commit command.
  729. * <p>
  730. * Both the pre-commit and commit-msg hooks can block a commit by their
  731. * return value; setting this option to <code>true</code> will bypass these
  732. * two hooks.
  733. * </p>
  734. *
  735. * @param noVerify
  736. * Whether this commit should be verified by the pre-commit and
  737. * commit-msg hooks.
  738. * @return {@code this}
  739. * @since 3.7
  740. */
  741. public CommitCommand setNoVerify(boolean noVerify) {
  742. this.noVerify = noVerify;
  743. return this;
  744. }
  745. /**
  746. * Set the output stream for hook scripts executed by this command. If not
  747. * set it defaults to {@code System.out}.
  748. *
  749. * @param hookStdOut
  750. * the output stream for hook scripts executed by this command
  751. * @return {@code this}
  752. * @since 3.7
  753. */
  754. public CommitCommand setHookOutputStream(PrintStream hookStdOut) {
  755. this.hookOutRedirect = hookStdOut;
  756. return this;
  757. }
  758. }