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

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