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

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