選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

CommitCommand.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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. || isMergeDuringRebase(state)) {
  224. // Commit was successful. Now delete the files
  225. // used for merge commits
  226. repo.writeMergeCommitMsg(null);
  227. repo.writeMergeHeads(null);
  228. } else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
  229. repo.writeMergeCommitMsg(null);
  230. repo.writeCherryPickHead(null);
  231. } else if (state == RepositoryState.REVERTING_RESOLVED) {
  232. repo.writeMergeCommitMsg(null);
  233. repo.writeRevertHead(null);
  234. }
  235. return revCommit;
  236. }
  237. case REJECTED:
  238. case LOCK_FAILURE:
  239. throw new ConcurrentRefUpdateException(
  240. JGitText.get().couldNotLockHEAD, ru.getRef(),
  241. rc);
  242. default:
  243. throw new JGitInternalException(MessageFormat.format(
  244. JGitText.get().updatingRefFailed,
  245. Constants.HEAD, commitId.toString(), rc));
  246. }
  247. } finally {
  248. odi.release();
  249. }
  250. } finally {
  251. index.unlock();
  252. }
  253. } catch (UnmergedPathException e) {
  254. throw new UnmergedPathsException(e);
  255. } catch (IOException e) {
  256. throw new JGitInternalException(
  257. JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
  258. } finally {
  259. rw.dispose();
  260. }
  261. }
  262. private void insertChangeId(ObjectId treeId) throws IOException {
  263. ObjectId firstParentId = null;
  264. if (!parents.isEmpty())
  265. firstParentId = parents.get(0);
  266. ObjectId changeId = ChangeIdUtil.computeChangeId(treeId, firstParentId,
  267. author, committer, message);
  268. message = ChangeIdUtil.insertId(message, changeId);
  269. if (changeId != null)
  270. message = message.replaceAll("\nChange-Id: I" //$NON-NLS-1$
  271. + ObjectId.zeroId().getName() + "\n", "\nChange-Id: I" //$NON-NLS-1$ //$NON-NLS-2$
  272. + changeId.getName() + "\n"); //$NON-NLS-1$
  273. }
  274. private DirCache createTemporaryIndex(ObjectId headId, DirCache index,
  275. RevWalk rw)
  276. throws IOException {
  277. ObjectInserter inserter = null;
  278. // get DirCacheBuilder for existing index
  279. DirCacheBuilder existingBuilder = index.builder();
  280. // get DirCacheBuilder for newly created in-core index to build a
  281. // temporary index for this commit
  282. DirCache inCoreIndex = DirCache.newInCore();
  283. DirCacheBuilder tempBuilder = inCoreIndex.builder();
  284. onlyProcessed = new boolean[only.size()];
  285. boolean emptyCommit = true;
  286. TreeWalk treeWalk = new TreeWalk(repo);
  287. int dcIdx = treeWalk.addTree(new DirCacheBuildIterator(existingBuilder));
  288. int fIdx = treeWalk.addTree(new FileTreeIterator(repo));
  289. int hIdx = -1;
  290. if (headId != null)
  291. hIdx = treeWalk.addTree(rw.parseTree(headId));
  292. treeWalk.setRecursive(true);
  293. String lastAddedFile = null;
  294. while (treeWalk.next()) {
  295. String path = treeWalk.getPathString();
  296. // check if current entry's path matches a specified path
  297. int pos = lookupOnly(path);
  298. CanonicalTreeParser hTree = null;
  299. if (hIdx != -1)
  300. hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
  301. DirCacheIterator dcTree = treeWalk.getTree(dcIdx,
  302. DirCacheIterator.class);
  303. if (pos >= 0) {
  304. // include entry in commit
  305. FileTreeIterator fTree = treeWalk.getTree(fIdx,
  306. FileTreeIterator.class);
  307. // check if entry refers to a tracked file
  308. boolean tracked = dcTree != null || hTree != null;
  309. if (!tracked)
  310. break;
  311. // for an unmerged path, DirCacheBuildIterator will yield 3
  312. // entries, we only want to add one
  313. if (path.equals(lastAddedFile))
  314. continue;
  315. lastAddedFile = path;
  316. if (fTree != null) {
  317. // create a new DirCacheEntry with data retrieved from disk
  318. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  319. long entryLength = fTree.getEntryLength();
  320. dcEntry.setLength(entryLength);
  321. dcEntry.setLastModified(fTree.getEntryLastModified());
  322. dcEntry.setFileMode(fTree.getIndexFileMode(dcTree));
  323. boolean objectExists = (dcTree != null && fTree
  324. .idEqual(dcTree))
  325. || (hTree != null && fTree.idEqual(hTree));
  326. if (objectExists) {
  327. dcEntry.setObjectId(fTree.getEntryObjectId());
  328. } else {
  329. if (FileMode.GITLINK.equals(dcEntry.getFileMode()))
  330. dcEntry.setObjectId(fTree.getEntryObjectId());
  331. else {
  332. // insert object
  333. if (inserter == null)
  334. inserter = repo.newObjectInserter();
  335. long contentLength = fTree.getEntryContentLength();
  336. InputStream inputStream = fTree.openEntryStream();
  337. try {
  338. dcEntry.setObjectId(inserter.insert(
  339. Constants.OBJ_BLOB, contentLength,
  340. inputStream));
  341. } finally {
  342. inputStream.close();
  343. }
  344. }
  345. }
  346. // add to existing index
  347. existingBuilder.add(dcEntry);
  348. // add to temporary in-core index
  349. tempBuilder.add(dcEntry);
  350. if (emptyCommit
  351. && (hTree == null || !hTree.idEqual(fTree) || hTree
  352. .getEntryRawMode() != fTree
  353. .getEntryRawMode()))
  354. // this is a change
  355. emptyCommit = false;
  356. } else {
  357. // if no file exists on disk, neither add it to
  358. // index nor to temporary in-core index
  359. if (emptyCommit && hTree != null)
  360. // this is a change
  361. emptyCommit = false;
  362. }
  363. // keep track of processed path
  364. onlyProcessed[pos] = true;
  365. } else {
  366. // add entries from HEAD for all other paths
  367. if (hTree != null) {
  368. // create a new DirCacheEntry with data retrieved from HEAD
  369. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  370. dcEntry.setObjectId(hTree.getEntryObjectId());
  371. dcEntry.setFileMode(hTree.getEntryFileMode());
  372. // add to temporary in-core index
  373. tempBuilder.add(dcEntry);
  374. }
  375. // preserve existing entry in index
  376. if (dcTree != null)
  377. existingBuilder.add(dcTree.getDirCacheEntry());
  378. }
  379. }
  380. // there must be no unprocessed paths left at this point; otherwise an
  381. // untracked or unknown path has been specified
  382. for (int i = 0; i < onlyProcessed.length; i++)
  383. if (!onlyProcessed[i])
  384. throw new JGitInternalException(MessageFormat.format(
  385. JGitText.get().entryNotFoundByPath, only.get(i)));
  386. // there must be at least one change
  387. if (emptyCommit)
  388. throw new JGitInternalException(JGitText.get().emptyCommit);
  389. // update index
  390. existingBuilder.commit();
  391. // finish temporary in-core index used for this commit
  392. tempBuilder.finish();
  393. return inCoreIndex;
  394. }
  395. /**
  396. * Look an entry's path up in the list of paths specified by the --only/ -o
  397. * option
  398. *
  399. * In case the complete (file) path (e.g. "d1/d2/f1") cannot be found in
  400. * <code>only</code>, lookup is also tried with (parent) directory paths
  401. * (e.g. "d1/d2" and "d1").
  402. *
  403. * @param pathString
  404. * entry's path
  405. * @return the item's index in <code>only</code>; -1 if no item matches
  406. */
  407. private int lookupOnly(String pathString) {
  408. String p = pathString;
  409. while (true) {
  410. int position = Collections.binarySearch(only, p);
  411. if (position >= 0)
  412. return position;
  413. int l = p.lastIndexOf("/"); //$NON-NLS-1$
  414. if (l < 1)
  415. break;
  416. p = p.substring(0, l);
  417. }
  418. return -1;
  419. }
  420. /**
  421. * Sets default values for not explicitly specified options. Then validates
  422. * that all required data has been provided.
  423. *
  424. * @param state
  425. * the state of the repository we are working on
  426. * @param rw
  427. * the RevWalk to use
  428. *
  429. * @throws NoMessageException
  430. * if the commit message has not been specified
  431. */
  432. private void processOptions(RepositoryState state, RevWalk rw)
  433. throws NoMessageException {
  434. if (committer == null)
  435. committer = new PersonIdent(repo);
  436. if (author == null && !amend)
  437. author = committer;
  438. // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
  439. if (state == RepositoryState.MERGING_RESOLVED
  440. || isMergeDuringRebase(state)) {
  441. try {
  442. parents = repo.readMergeHeads();
  443. if (parents != null)
  444. for (int i = 0; i < parents.size(); i++) {
  445. RevObject ro = rw.parseAny(parents.get(i));
  446. if (ro instanceof RevTag)
  447. parents.set(i, rw.peel(ro));
  448. }
  449. } catch (IOException e) {
  450. throw new JGitInternalException(MessageFormat.format(
  451. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  452. Constants.MERGE_HEAD, e), e);
  453. }
  454. if (message == null) {
  455. try {
  456. message = repo.readMergeCommitMsg();
  457. } catch (IOException e) {
  458. throw new JGitInternalException(MessageFormat.format(
  459. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  460. Constants.MERGE_MSG, e), e);
  461. }
  462. }
  463. } else if (state == RepositoryState.SAFE && message == null) {
  464. try {
  465. message = repo.readSquashCommitMsg();
  466. if (message != null)
  467. repo.writeSquashCommitMsg(null /* delete */);
  468. } catch (IOException e) {
  469. throw new JGitInternalException(MessageFormat.format(
  470. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  471. Constants.MERGE_MSG, e), e);
  472. }
  473. }
  474. if (message == null)
  475. // as long as we don't support -C option we have to have
  476. // an explicit message
  477. throw new NoMessageException(JGitText.get().commitMessageNotSpecified);
  478. }
  479. private boolean isMergeDuringRebase(RepositoryState state) {
  480. if (state != RepositoryState.REBASING_INTERACTIVE
  481. && state != RepositoryState.REBASING_MERGE)
  482. return false;
  483. try {
  484. return repo.readMergeHeads() != null;
  485. } catch (IOException e) {
  486. throw new JGitInternalException(MessageFormat.format(
  487. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  488. Constants.MERGE_HEAD, e), e);
  489. }
  490. }
  491. /**
  492. * @param message
  493. * the commit message used for the {@code commit}
  494. * @return {@code this}
  495. */
  496. public CommitCommand setMessage(String message) {
  497. checkCallable();
  498. this.message = message;
  499. return this;
  500. }
  501. /**
  502. * @return the commit message used for the <code>commit</code>
  503. */
  504. public String getMessage() {
  505. return message;
  506. }
  507. /**
  508. * Sets the committer for this {@code commit}. If no committer is explicitly
  509. * specified because this method is never called or called with {@code null}
  510. * value then the committer will be deduced from config info in repository,
  511. * with current time.
  512. *
  513. * @param committer
  514. * the committer used for the {@code commit}
  515. * @return {@code this}
  516. */
  517. public CommitCommand setCommitter(PersonIdent committer) {
  518. checkCallable();
  519. this.committer = committer;
  520. return this;
  521. }
  522. /**
  523. * Sets the committer for this {@code commit}. If no committer is explicitly
  524. * specified because this method is never called then the committer will be
  525. * deduced from config info in repository, with current time.
  526. *
  527. * @param name
  528. * the name of the committer used for the {@code commit}
  529. * @param email
  530. * the email of the committer used for the {@code commit}
  531. * @return {@code this}
  532. */
  533. public CommitCommand setCommitter(String name, String email) {
  534. checkCallable();
  535. return setCommitter(new PersonIdent(name, email));
  536. }
  537. /**
  538. * @return the committer used for the {@code commit}. If no committer was
  539. * specified {@code null} is returned and the default
  540. * {@link PersonIdent} of this repo is used during execution of the
  541. * command
  542. */
  543. public PersonIdent getCommitter() {
  544. return committer;
  545. }
  546. /**
  547. * Sets the author for this {@code commit}. If no author is explicitly
  548. * specified because this method is never called or called with {@code null}
  549. * value then the author will be set to the committer or to the original
  550. * author when amending.
  551. *
  552. * @param author
  553. * the author used for the {@code commit}
  554. * @return {@code this}
  555. */
  556. public CommitCommand setAuthor(PersonIdent author) {
  557. checkCallable();
  558. this.author = author;
  559. return this;
  560. }
  561. /**
  562. * Sets the author for this {@code commit}. If no author is explicitly
  563. * specified because this method is never called then the author will be set
  564. * to the committer or to the original author when amending.
  565. *
  566. * @param name
  567. * the name of the author used for the {@code commit}
  568. * @param email
  569. * the email of the author used for the {@code commit}
  570. * @return {@code this}
  571. */
  572. public CommitCommand setAuthor(String name, String email) {
  573. checkCallable();
  574. return setAuthor(new PersonIdent(name, email));
  575. }
  576. /**
  577. * @return the author used for the {@code commit}. If no author was
  578. * specified {@code null} is returned and the default
  579. * {@link PersonIdent} of this repo is used during execution of the
  580. * command
  581. */
  582. public PersonIdent getAuthor() {
  583. return author;
  584. }
  585. /**
  586. * If set to true the Commit command automatically stages files that have
  587. * been modified and deleted, but new files not known by the repository are
  588. * not affected. This corresponds to the parameter -a on the command line.
  589. *
  590. * @param all
  591. * @return {@code this}
  592. * @throws JGitInternalException
  593. * in case of an illegal combination of arguments/ options
  594. */
  595. public CommitCommand setAll(boolean all) {
  596. checkCallable();
  597. if (!only.isEmpty())
  598. throw new JGitInternalException(MessageFormat.format(
  599. JGitText.get().illegalCombinationOfArguments, "--all", //$NON-NLS-1$
  600. "--only")); //$NON-NLS-1$
  601. this.all = all;
  602. return this;
  603. }
  604. /**
  605. * Used to amend the tip of the current branch. If set to true, the previous
  606. * commit will be amended. This is equivalent to --amend on the command
  607. * line.
  608. *
  609. * @param amend
  610. * @return {@code this}
  611. */
  612. public CommitCommand setAmend(boolean amend) {
  613. checkCallable();
  614. this.amend = amend;
  615. return this;
  616. }
  617. /**
  618. * Commit dedicated path only.
  619. * <p>
  620. * This method can be called several times to add multiple paths. Full file
  621. * paths are supported as well as directory paths; in the latter case this
  622. * commits all files/directories below the specified path.
  623. *
  624. * @param only
  625. * path to commit (with <code>/</code> as separator)
  626. * @return {@code this}
  627. */
  628. public CommitCommand setOnly(String only) {
  629. checkCallable();
  630. if (all)
  631. throw new JGitInternalException(MessageFormat.format(
  632. JGitText.get().illegalCombinationOfArguments, "--only", //$NON-NLS-1$
  633. "--all")); //$NON-NLS-1$
  634. String o = only.endsWith("/") ? only.substring(0, only.length() - 1) //$NON-NLS-1$
  635. : only;
  636. // ignore duplicates
  637. if (!this.only.contains(o))
  638. this.only.add(o);
  639. return this;
  640. }
  641. /**
  642. * If set to true a change id will be inserted into the commit message
  643. *
  644. * An existing change id is not replaced. An initial change id (I000...)
  645. * will be replaced by the change id.
  646. *
  647. * @param insertChangeId
  648. *
  649. * @return {@code this}
  650. */
  651. public CommitCommand setInsertChangeId(boolean insertChangeId) {
  652. checkCallable();
  653. this.insertChangeId = insertChangeId;
  654. return this;
  655. }
  656. /**
  657. * Override the message written to the reflog
  658. *
  659. * @param reflogComment
  660. * @return {@code this}
  661. */
  662. public CommitCommand setReflogComment(String reflogComment) {
  663. this.reflogComment = reflogComment;
  664. return this;
  665. }
  666. }