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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. /*
  2. * Copyright (C) 2010, 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.text.MessageFormat;
  47. import java.util.ArrayList;
  48. import java.util.LinkedList;
  49. import java.util.List;
  50. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  51. import org.eclipse.jgit.api.errors.JGitInternalException;
  52. import org.eclipse.jgit.api.errors.NoFilepatternException;
  53. import org.eclipse.jgit.api.errors.NoHeadException;
  54. import org.eclipse.jgit.api.errors.NoMessageException;
  55. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  56. import org.eclipse.jgit.dircache.DirCache;
  57. import org.eclipse.jgit.dircache.DirCacheBuilder;
  58. import org.eclipse.jgit.dircache.DirCacheEditor;
  59. import org.eclipse.jgit.dircache.DirCacheEditor.DeletePath;
  60. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  61. import org.eclipse.jgit.dircache.DirCacheEntry;
  62. import org.eclipse.jgit.dircache.DirCacheIterator;
  63. import org.eclipse.jgit.errors.UnmergedPathException;
  64. import org.eclipse.jgit.internal.JGitText;
  65. import org.eclipse.jgit.lib.CommitBuilder;
  66. import org.eclipse.jgit.lib.Constants;
  67. import org.eclipse.jgit.lib.FileMode;
  68. import org.eclipse.jgit.lib.ObjectId;
  69. import org.eclipse.jgit.lib.ObjectInserter;
  70. import org.eclipse.jgit.lib.PersonIdent;
  71. import org.eclipse.jgit.lib.Ref;
  72. import org.eclipse.jgit.lib.RefUpdate;
  73. import org.eclipse.jgit.lib.RefUpdate.Result;
  74. import org.eclipse.jgit.lib.Repository;
  75. import org.eclipse.jgit.lib.RepositoryState;
  76. import org.eclipse.jgit.revwalk.RevCommit;
  77. import org.eclipse.jgit.revwalk.RevWalk;
  78. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  79. import org.eclipse.jgit.treewalk.FileTreeIterator;
  80. import org.eclipse.jgit.treewalk.TreeWalk;
  81. import org.eclipse.jgit.util.ChangeIdUtil;
  82. /**
  83. * A class used to execute a {@code Commit} command. It has setters for all
  84. * supported options and arguments of this command and a {@link #call()} method
  85. * to finally execute the command.
  86. *
  87. * @see <a
  88. * href="http://www.kernel.org/pub/software/scm/git/docs/git-commit.html"
  89. * >Git documentation about Commit</a>
  90. */
  91. public class CommitCommand extends GitCommand<RevCommit> {
  92. private PersonIdent author;
  93. private PersonIdent committer;
  94. private String message;
  95. private boolean all;
  96. private List<String> only = new ArrayList<String>();
  97. private boolean[] onlyProcessed;
  98. private boolean amend;
  99. private boolean insertChangeId;
  100. /**
  101. * parents this commit should have. The current HEAD will be in this list
  102. * and also all commits mentioned in .git/MERGE_HEAD
  103. */
  104. private List<ObjectId> parents = new LinkedList<ObjectId>();
  105. private String reflogComment;
  106. /**
  107. * @param repo
  108. */
  109. protected CommitCommand(Repository repo) {
  110. super(repo);
  111. }
  112. /**
  113. * Executes the {@code commit} command with all the options and parameters
  114. * collected by the setter methods of this class. Each instance of this
  115. * class should only be used for one invocation of the command (means: one
  116. * call to {@link #call()})
  117. *
  118. * @return a {@link RevCommit} object representing the successful commit.
  119. * @throws NoHeadException
  120. * when called on a git repo without a HEAD reference
  121. * @throws NoMessageException
  122. * when called without specifying a commit message
  123. * @throws UnmergedPathException
  124. * when the current index contained unmerged paths (conflicts)
  125. * @throws WrongRepositoryStateException
  126. * when repository is not in the right state for committing
  127. * @throws JGitInternalException
  128. * a low-level exception of JGit has occurred. The original
  129. * exception can be retrieved by calling
  130. * {@link Exception#getCause()}. Expect only
  131. * {@code IOException's} to be wrapped. Subclasses of
  132. * {@link IOException} (e.g. {@link UnmergedPathException}) are
  133. * typically not wrapped here but thrown as original exception
  134. */
  135. public RevCommit call() throws NoHeadException, NoMessageException,
  136. UnmergedPathException, ConcurrentRefUpdateException,
  137. JGitInternalException, WrongRepositoryStateException {
  138. checkCallable();
  139. RepositoryState state = repo.getRepositoryState();
  140. if (!state.canCommit())
  141. throw new WrongRepositoryStateException(MessageFormat.format(
  142. JGitText.get().cannotCommitOnARepoWithState, state.name()));
  143. processOptions(state);
  144. try {
  145. if (all && !repo.isBare() && repo.getWorkTree() != null) {
  146. Git git = new Git(repo);
  147. try {
  148. git.add()
  149. .addFilepattern(".")
  150. .setUpdate(true).call();
  151. } catch (NoFilepatternException e) {
  152. // should really not happen
  153. throw new JGitInternalException(e.getMessage(), e);
  154. }
  155. }
  156. Ref head = repo.getRef(Constants.HEAD);
  157. if (head == null)
  158. throw new NoHeadException(
  159. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  160. // determine the current HEAD and the commit it is referring to
  161. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}");
  162. if (headId != null)
  163. if (amend) {
  164. RevCommit previousCommit = new RevWalk(repo)
  165. .parseCommit(headId);
  166. RevCommit[] p = previousCommit.getParents();
  167. for (int i = 0; i < p.length; i++)
  168. parents.add(0, p[i].getId());
  169. } else {
  170. parents.add(0, headId);
  171. }
  172. // lock the index
  173. DirCache index = repo.lockDirCache();
  174. try {
  175. if (!only.isEmpty())
  176. index = createTemporaryIndex(headId, index);
  177. ObjectInserter odi = repo.newObjectInserter();
  178. try {
  179. // Write the index as tree to the object database. This may
  180. // fail for example when the index contains unmerged paths
  181. // (unresolved conflicts)
  182. ObjectId indexTreeId = index.writeTree(odi);
  183. if (insertChangeId)
  184. insertChangeId(indexTreeId);
  185. // Create a Commit object, populate it and write it
  186. CommitBuilder commit = new CommitBuilder();
  187. commit.setCommitter(committer);
  188. commit.setAuthor(author);
  189. commit.setMessage(message);
  190. commit.setParentIds(parents);
  191. commit.setTreeId(indexTreeId);
  192. ObjectId commitId = odi.insert(commit);
  193. odi.flush();
  194. RevWalk revWalk = new RevWalk(repo);
  195. try {
  196. RevCommit revCommit = revWalk.parseCommit(commitId);
  197. RefUpdate ru = repo.updateRef(Constants.HEAD);
  198. ru.setNewObjectId(commitId);
  199. if (reflogComment != null) {
  200. ru.setRefLogMessage(reflogComment, false);
  201. } else {
  202. String prefix = amend ? "commit (amend): "
  203. : "commit: ";
  204. ru.setRefLogMessage(
  205. prefix + revCommit.getShortMessage(), false);
  206. }
  207. if (headId != null)
  208. ru.setExpectedOldObjectId(headId);
  209. else
  210. ru.setExpectedOldObjectId(ObjectId.zeroId());
  211. Result rc = ru.forceUpdate();
  212. switch (rc) {
  213. case NEW:
  214. case FORCED:
  215. case FAST_FORWARD: {
  216. setCallable(false);
  217. if (state == RepositoryState.MERGING_RESOLVED) {
  218. // Commit was successful. Now delete the files
  219. // used for merge commits
  220. repo.writeMergeCommitMsg(null);
  221. repo.writeMergeHeads(null);
  222. } else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
  223. repo.writeMergeCommitMsg(null);
  224. repo.writeCherryPickHead(null);
  225. }
  226. return revCommit;
  227. }
  228. case REJECTED:
  229. case LOCK_FAILURE:
  230. throw new ConcurrentRefUpdateException(JGitText
  231. .get().couldNotLockHEAD, ru.getRef(), rc);
  232. default:
  233. throw new JGitInternalException(MessageFormat
  234. .format(JGitText.get().updatingRefFailed,
  235. Constants.HEAD,
  236. commitId.toString(), rc));
  237. }
  238. } finally {
  239. revWalk.release();
  240. }
  241. } finally {
  242. odi.release();
  243. }
  244. } finally {
  245. index.unlock();
  246. }
  247. } catch (UnmergedPathException e) {
  248. // since UnmergedPathException is a subclass of IOException
  249. // which should not be wrapped by a JGitInternalException we
  250. // have to catch and re-throw it here
  251. throw e;
  252. } catch (IOException e) {
  253. throw new JGitInternalException(
  254. JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
  255. }
  256. }
  257. private void insertChangeId(ObjectId treeId) throws IOException {
  258. ObjectId firstParentId = null;
  259. if (!parents.isEmpty())
  260. firstParentId = parents.get(0);
  261. ObjectId changeId = ChangeIdUtil.computeChangeId(treeId, firstParentId,
  262. author, committer, message);
  263. message = ChangeIdUtil.insertId(message, changeId);
  264. if (changeId != null)
  265. message = message.replaceAll("\nChange-Id: I"
  266. + ObjectId.zeroId().getName() + "\n", "\nChange-Id: I"
  267. + changeId.getName() + "\n");
  268. }
  269. private DirCache createTemporaryIndex(ObjectId headId, DirCache index)
  270. throws IOException {
  271. ObjectInserter inserter = null;
  272. // get DirCacheEditor to modify the index if required
  273. DirCacheEditor dcEditor = index.editor();
  274. // get DirCacheBuilder for newly created in-core index to build a
  275. // temporary index for this commit
  276. DirCache inCoreIndex = DirCache.newInCore();
  277. DirCacheBuilder dcBuilder = inCoreIndex.builder();
  278. onlyProcessed = new boolean[only.size()];
  279. boolean emptyCommit = true;
  280. TreeWalk treeWalk = new TreeWalk(repo);
  281. int dcIdx = treeWalk.addTree(new DirCacheIterator(index));
  282. int fIdx = treeWalk.addTree(new FileTreeIterator(repo));
  283. int hIdx = -1;
  284. if (headId != null)
  285. hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
  286. treeWalk.setRecursive(true);
  287. while (treeWalk.next()) {
  288. String path = treeWalk.getPathString();
  289. // check if current entry's path matches a specified path
  290. int pos = lookupOnly(path);
  291. CanonicalTreeParser hTree = null;
  292. if (hIdx != -1)
  293. hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
  294. if (pos >= 0) {
  295. // include entry in commit
  296. DirCacheIterator dcTree = treeWalk.getTree(dcIdx,
  297. DirCacheIterator.class);
  298. FileTreeIterator fTree = treeWalk.getTree(fIdx,
  299. FileTreeIterator.class);
  300. // check if entry refers to a tracked file
  301. boolean tracked = dcTree != null || hTree != null;
  302. if (!tracked)
  303. break;
  304. if (fTree != null) {
  305. // create a new DirCacheEntry with data retrieved from disk
  306. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  307. long entryLength = fTree.getEntryLength();
  308. dcEntry.setLength(entryLength);
  309. dcEntry.setLastModified(fTree.getEntryLastModified());
  310. dcEntry.setFileMode(fTree.getIndexFileMode(dcTree));
  311. boolean objectExists = (dcTree != null && fTree
  312. .idEqual(dcTree))
  313. || (hTree != null && fTree.idEqual(hTree));
  314. if (objectExists) {
  315. dcEntry.setObjectId(fTree.getEntryObjectId());
  316. } else {
  317. if (FileMode.GITLINK.equals(dcEntry.getFileMode()))
  318. dcEntry.setObjectId(fTree.getEntryObjectId());
  319. else {
  320. // insert object
  321. if (inserter == null)
  322. inserter = repo.newObjectInserter();
  323. long contentLength = fTree.getEntryContentLength();
  324. InputStream inputStream = fTree.openEntryStream();
  325. try {
  326. dcEntry.setObjectId(inserter.insert(
  327. Constants.OBJ_BLOB, contentLength,
  328. inputStream));
  329. } finally {
  330. inputStream.close();
  331. }
  332. }
  333. }
  334. // update index
  335. dcEditor.add(new PathEdit(path) {
  336. @Override
  337. public void apply(DirCacheEntry ent) {
  338. ent.copyMetaData(dcEntry);
  339. }
  340. });
  341. // add to temporary in-core index
  342. dcBuilder.add(dcEntry);
  343. if (emptyCommit
  344. && (hTree == null || !hTree.idEqual(fTree) || hTree
  345. .getEntryRawMode() != fTree
  346. .getEntryRawMode()))
  347. // this is a change
  348. emptyCommit = false;
  349. } else {
  350. // if no file exists on disk, remove entry from index and
  351. // don't add it to temporary in-core index
  352. dcEditor.add(new DeletePath(path));
  353. if (emptyCommit && hTree != null)
  354. // this is a change
  355. emptyCommit = false;
  356. }
  357. // keep track of processed path
  358. onlyProcessed[pos] = true;
  359. } else {
  360. // add entries from HEAD for all other paths
  361. if (hTree != null) {
  362. // create a new DirCacheEntry with data retrieved from HEAD
  363. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  364. dcEntry.setObjectId(hTree.getEntryObjectId());
  365. dcEntry.setFileMode(hTree.getEntryFileMode());
  366. // add to temporary in-core index
  367. dcBuilder.add(dcEntry);
  368. }
  369. }
  370. }
  371. // there must be no unprocessed paths left at this point; otherwise an
  372. // untracked or unknown path has been specified
  373. for (int i = 0; i < onlyProcessed.length; i++)
  374. if (!onlyProcessed[i])
  375. throw new JGitInternalException(MessageFormat.format(
  376. JGitText.get().entryNotFoundByPath, only.get(i)));
  377. // there must be at least one change
  378. if (emptyCommit)
  379. throw new JGitInternalException(JGitText.get().emptyCommit);
  380. // update index
  381. dcEditor.commit();
  382. // finish temporary in-core index used for this commit
  383. dcBuilder.finish();
  384. return inCoreIndex;
  385. }
  386. /**
  387. * Look an entry's path up in the list of paths specified by the --only/ -o
  388. * option
  389. *
  390. * In case the complete (file) path (e.g. "d1/d2/f1") cannot be found in
  391. * <code>only</code>, lookup is also tried with (parent) directory paths
  392. * (e.g. "d1/d2" and "d1").
  393. *
  394. * @param pathString
  395. * entry's path
  396. * @return the item's index in <code>only</code>; -1 if no item matches
  397. */
  398. private int lookupOnly(String pathString) {
  399. int i = 0;
  400. for (String o : only) {
  401. String p = pathString;
  402. while (true) {
  403. if (p.equals(o))
  404. return i;
  405. int l = p.lastIndexOf("/");
  406. if (l < 1)
  407. break;
  408. p = p.substring(0, l);
  409. }
  410. i++;
  411. }
  412. return -1;
  413. }
  414. /**
  415. * Sets default values for not explicitly specified options. Then validates
  416. * that all required data has been provided.
  417. *
  418. * @param state
  419. * the state of the repository we are working on
  420. *
  421. * @throws NoMessageException
  422. * if the commit message has not been specified
  423. */
  424. private void processOptions(RepositoryState state) throws NoMessageException {
  425. if (committer == null)
  426. committer = new PersonIdent(repo);
  427. if (author == null)
  428. author = committer;
  429. // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
  430. if (state == RepositoryState.MERGING_RESOLVED) {
  431. try {
  432. parents = repo.readMergeHeads();
  433. } catch (IOException e) {
  434. throw new JGitInternalException(MessageFormat.format(
  435. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  436. Constants.MERGE_HEAD, e), e);
  437. }
  438. if (message == null) {
  439. try {
  440. message = repo.readMergeCommitMsg();
  441. } catch (IOException e) {
  442. throw new JGitInternalException(MessageFormat.format(
  443. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  444. Constants.MERGE_MSG, e), e);
  445. }
  446. }
  447. }
  448. if (message == null)
  449. // as long as we don't suppport -C option we have to have
  450. // an explicit message
  451. throw new NoMessageException(JGitText.get().commitMessageNotSpecified);
  452. }
  453. /**
  454. * @param message
  455. * the commit message used for the {@code commit}
  456. * @return {@code this}
  457. */
  458. public CommitCommand setMessage(String message) {
  459. checkCallable();
  460. this.message = message;
  461. return this;
  462. }
  463. /**
  464. * @return the commit message used for the <code>commit</code>
  465. */
  466. public String getMessage() {
  467. return message;
  468. }
  469. /**
  470. * Sets the committer for this {@code commit}. If no committer is explicitly
  471. * specified because this method is never called or called with {@code null}
  472. * value then the committer will be deduced from config info in repository,
  473. * with current time.
  474. *
  475. * @param committer
  476. * the committer used for the {@code commit}
  477. * @return {@code this}
  478. */
  479. public CommitCommand setCommitter(PersonIdent committer) {
  480. checkCallable();
  481. this.committer = committer;
  482. return this;
  483. }
  484. /**
  485. * Sets the committer for this {@code commit}. If no committer is explicitly
  486. * specified because this method is never called or called with {@code null}
  487. * value then the committer will be deduced from config info in repository,
  488. * with current time.
  489. *
  490. * @param name
  491. * the name of the committer used for the {@code commit}
  492. * @param email
  493. * the email of the committer used for the {@code commit}
  494. * @return {@code this}
  495. */
  496. public CommitCommand setCommitter(String name, String email) {
  497. checkCallable();
  498. return setCommitter(new PersonIdent(name, email));
  499. }
  500. /**
  501. * @return the committer used for the {@code commit}. If no committer was
  502. * specified {@code null} is returned and the default
  503. * {@link PersonIdent} of this repo is used during execution of the
  504. * command
  505. */
  506. public PersonIdent getCommitter() {
  507. return committer;
  508. }
  509. /**
  510. * Sets the author for this {@code commit}. If no author is explicitly
  511. * specified because this method is never called or called with {@code null}
  512. * value then the author will be set to the committer.
  513. *
  514. * @param author
  515. * the author used for the {@code commit}
  516. * @return {@code this}
  517. */
  518. public CommitCommand setAuthor(PersonIdent author) {
  519. checkCallable();
  520. this.author = author;
  521. return this;
  522. }
  523. /**
  524. * Sets the author for this {@code commit}. If no author is explicitly
  525. * specified because this method is never called or called with {@code null}
  526. * value then the author will be set to the committer.
  527. *
  528. * @param name
  529. * the name of the author used for the {@code commit}
  530. * @param email
  531. * the email of the author used for the {@code commit}
  532. * @return {@code this}
  533. */
  534. public CommitCommand setAuthor(String name, String email) {
  535. checkCallable();
  536. return setAuthor(new PersonIdent(name, email));
  537. }
  538. /**
  539. * @return the author used for the {@code commit}. If no author was
  540. * specified {@code null} is returned and the default
  541. * {@link PersonIdent} of this repo is used during execution of the
  542. * command
  543. */
  544. public PersonIdent getAuthor() {
  545. return author;
  546. }
  547. /**
  548. * If set to true the Commit command automatically stages files that have
  549. * been modified and deleted, but new files not known by the repository are
  550. * not affected. This corresponds to the parameter -a on the command line.
  551. *
  552. * @param all
  553. * @return {@code this}
  554. * @throws JGitInternalException
  555. * in case of an illegal combination of arguments/ options
  556. */
  557. public CommitCommand setAll(boolean all) {
  558. checkCallable();
  559. if (!only.isEmpty())
  560. throw new JGitInternalException(MessageFormat.format(
  561. JGitText.get().illegalCombinationOfArguments, "--all",
  562. "--only"));
  563. this.all = all;
  564. return this;
  565. }
  566. /**
  567. * Used to amend the tip of the current branch. If set to true, the previous
  568. * commit will be amended. This is equivalent to --amend on the command
  569. * line.
  570. *
  571. * @param amend
  572. * @return {@code this}
  573. */
  574. public CommitCommand setAmend(boolean amend) {
  575. checkCallable();
  576. this.amend = amend;
  577. return this;
  578. }
  579. /**
  580. * Commit dedicated path only
  581. *
  582. * This method can be called several times to add multiple paths. Full file
  583. * paths are supported as well as directory paths; in the latter case this
  584. * commits all files/ directories below the specified path.
  585. *
  586. * @param only
  587. * path to commit
  588. * @return {@code this}
  589. */
  590. public CommitCommand setOnly(String only) {
  591. checkCallable();
  592. if (all)
  593. throw new JGitInternalException(MessageFormat.format(
  594. JGitText.get().illegalCombinationOfArguments, "--only",
  595. "--all"));
  596. String o = only.endsWith("/") ? only.substring(0, only.length() - 1)
  597. : only;
  598. // ignore duplicates
  599. if (!this.only.contains(o))
  600. this.only.add(o);
  601. return this;
  602. }
  603. /**
  604. * If set to true a change id will be inserted into the commit message
  605. *
  606. * An existing change id is not replaced. An initial change id (I000...)
  607. * will be replaced by the change id.
  608. *
  609. * @param insertChangeId
  610. *
  611. * @return {@code this}
  612. */
  613. public CommitCommand setInsertChangeId(boolean insertChangeId) {
  614. checkCallable();
  615. this.insertChangeId = insertChangeId;
  616. return this;
  617. }
  618. /**
  619. * Override the message written to the reflog
  620. *
  621. * @param reflogComment
  622. * @return {@code this}
  623. */
  624. public CommitCommand setReflogComment(String reflogComment) {
  625. this.reflogComment = reflogComment;
  626. return this;
  627. }
  628. }