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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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.File;
  45. import java.io.IOException;
  46. import java.text.MessageFormat;
  47. import java.util.LinkedList;
  48. import java.util.List;
  49. import org.eclipse.jgit.JGitText;
  50. import org.eclipse.jgit.dircache.DirCache;
  51. import org.eclipse.jgit.errors.UnmergedPathException;
  52. import org.eclipse.jgit.lib.Commit;
  53. import org.eclipse.jgit.lib.Constants;
  54. import org.eclipse.jgit.lib.ObjectId;
  55. import org.eclipse.jgit.lib.ObjectWriter;
  56. import org.eclipse.jgit.lib.PersonIdent;
  57. import org.eclipse.jgit.lib.Ref;
  58. import org.eclipse.jgit.lib.RefUpdate;
  59. import org.eclipse.jgit.lib.RefUpdate.Result;
  60. import org.eclipse.jgit.lib.Repository;
  61. import org.eclipse.jgit.lib.RepositoryState;
  62. import org.eclipse.jgit.revwalk.RevCommit;
  63. import org.eclipse.jgit.revwalk.RevWalk;
  64. /**
  65. * A class used to execute a {@code Commit} command. It has setters for all
  66. * supported options and arguments of this command and a {@link #call()} method
  67. * to finally execute the command.
  68. *
  69. * @see <a
  70. * href="http://www.kernel.org/pub/software/scm/git/docs/git-commit.html"
  71. * >Git documentation about Commit</a>
  72. */
  73. public class CommitCommand extends GitCommand<RevCommit> {
  74. private PersonIdent author;
  75. private PersonIdent committer;
  76. private String message;
  77. /**
  78. * parents this commit should have. The current HEAD will be in this list
  79. * and also all commits mentioned in .git/MERGE_HEAD
  80. */
  81. private List<ObjectId> parents = new LinkedList<ObjectId>();
  82. /**
  83. * @param repo
  84. */
  85. protected CommitCommand(Repository repo) {
  86. super(repo);
  87. }
  88. /**
  89. * Executes the {@code commit} command with all the options and parameters
  90. * collected by the setter methods of this class. Each instance of this
  91. * class should only be used for one invocation of the command (means: one
  92. * call to {@link #call()})
  93. *
  94. * @return a {@link Commit} object representing the successful commit
  95. * @throws NoHeadException
  96. * when called on a git repo without a HEAD reference
  97. * @throws NoMessageException
  98. * when called without specifying a commit message
  99. * @throws UnmergedPathException
  100. * when the current index contained unmerged pathes (conflicts)
  101. * @throws WrongRepositoryStateException
  102. * when repository is not in the right state for committing
  103. * @throws JGitInternalException
  104. * a low-level exception of JGit has occurred. The original
  105. * exception can be retrieved by calling
  106. * {@link Exception#getCause()}. Expect only
  107. * {@code IOException's} to be wrapped. Subclasses of
  108. * {@link IOException} (e.g. {@link UnmergedPathException}) are
  109. * typically not wrapped here but thrown as original exception
  110. */
  111. public RevCommit call() throws NoHeadException, NoMessageException,
  112. UnmergedPathException, ConcurrentRefUpdateException,
  113. JGitInternalException, WrongRepositoryStateException {
  114. checkCallable();
  115. RepositoryState state = repo.getRepositoryState();
  116. if (!state.canCommit())
  117. throw new WrongRepositoryStateException(MessageFormat.format(
  118. JGitText.get().cannotCommitOnARepoWithState, state.name()));
  119. processOptions(state);
  120. try {
  121. Ref head = repo.getRef(Constants.HEAD);
  122. if (head == null)
  123. throw new NoHeadException(
  124. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  125. // determine the current HEAD and the commit it is referring to
  126. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}");
  127. if (headId != null)
  128. parents.add(0, headId);
  129. // lock the index
  130. DirCache index = DirCache.lock(repo);
  131. try {
  132. ObjectWriter repoWriter = new ObjectWriter(repo);
  133. // Write the index as tree to the object database. This may fail
  134. // for example when the index contains unmerged pathes
  135. // (unresolved conflicts)
  136. ObjectId indexTreeId = index.writeTree(repoWriter);
  137. // Create a Commit object, populate it and write it
  138. Commit commit = new Commit(repo);
  139. commit.setCommitter(committer);
  140. commit.setAuthor(author);
  141. commit.setMessage(message);
  142. commit.setParentIds(parents.toArray(new ObjectId[]{}));
  143. commit.setTreeId(indexTreeId);
  144. ObjectId commitId = repoWriter.writeCommit(commit);
  145. RevCommit revCommit = new RevWalk(repo).parseCommit(commitId);
  146. RefUpdate ru = repo.updateRef(Constants.HEAD);
  147. ru.setNewObjectId(commitId);
  148. ru.setRefLogMessage("commit : " + revCommit.getShortMessage(),
  149. false);
  150. ru.setExpectedOldObjectId(headId);
  151. Result rc = ru.update();
  152. switch (rc) {
  153. case NEW:
  154. case FAST_FORWARD:
  155. setCallable(false);
  156. if (state == RepositoryState.MERGING_RESOLVED) {
  157. // Commit was successful. Now delete the files
  158. // used for merge commits
  159. new File(repo.getDirectory(), Constants.MERGE_HEAD)
  160. .delete();
  161. new File(repo.getDirectory(), Constants.MERGE_MSG)
  162. .delete();
  163. }
  164. return revCommit;
  165. case REJECTED:
  166. case LOCK_FAILURE:
  167. throw new ConcurrentRefUpdateException(
  168. JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
  169. default:
  170. throw new JGitInternalException(MessageFormat.format(
  171. JGitText.get().updatingRefFailed
  172. , Constants.HEAD, commitId.toString(), rc));
  173. }
  174. } finally {
  175. index.unlock();
  176. }
  177. } catch (UnmergedPathException e) {
  178. // since UnmergedPathException is a subclass of IOException
  179. // which should not be wrapped by a JGitInternalException we
  180. // have to catch and re-throw it here
  181. throw e;
  182. } catch (IOException e) {
  183. throw new JGitInternalException(
  184. JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
  185. }
  186. }
  187. /**
  188. * Sets default values for not explicitly specified options. Then validates
  189. * that all required data has been provided.
  190. *
  191. * @param state
  192. * the state of the repository we are working on
  193. *
  194. * @throws NoMessageException
  195. * if the commit message has not been specified
  196. */
  197. private void processOptions(RepositoryState state) throws NoMessageException {
  198. if (committer == null)
  199. committer = new PersonIdent(repo);
  200. if (author == null)
  201. author = committer;
  202. // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
  203. if (state == RepositoryState.MERGING_RESOLVED) {
  204. try {
  205. parents = repo.readMergeHeads();
  206. } catch (IOException e) {
  207. throw new JGitInternalException(MessageFormat.format(
  208. JGitText.get().exceptionOccuredDuringReadingOfGIT_DIR,
  209. Constants.MERGE_HEAD, e));
  210. }
  211. if (message == null) {
  212. try {
  213. message = repo.readMergeCommitMsg();
  214. } catch (IOException e) {
  215. throw new JGitInternalException(MessageFormat.format(
  216. JGitText.get().exceptionOccuredDuringReadingOfGIT_DIR,
  217. Constants.MERGE_MSG, e));
  218. }
  219. }
  220. }
  221. if (message == null)
  222. // as long as we don't suppport -C option we have to have
  223. // an explicit message
  224. throw new NoMessageException(JGitText.get().commitMessageNotSpecified);
  225. }
  226. /**
  227. * @param message
  228. * the commit message used for the {@code commit}
  229. * @return {@code this}
  230. */
  231. public CommitCommand setMessage(String message) {
  232. checkCallable();
  233. this.message = message;
  234. return this;
  235. }
  236. /**
  237. * @return the commit message used for the <code>commit</code>
  238. */
  239. public String getMessage() {
  240. return message;
  241. }
  242. /**
  243. * Sets the committer for this {@code commit}. If no committer is explicitly
  244. * specified because this method is never called or called with {@code null}
  245. * value then the committer will be deduced from config info in repository,
  246. * with current time.
  247. *
  248. * @param committer
  249. * the committer used for the {@code commit}
  250. * @return {@code this}
  251. */
  252. public CommitCommand setCommitter(PersonIdent committer) {
  253. checkCallable();
  254. this.committer = committer;
  255. return this;
  256. }
  257. /**
  258. * Sets the committer for this {@code commit}. If no committer is explicitly
  259. * specified because this method is never called or called with {@code null}
  260. * value then the committer will be deduced from config info in repository,
  261. * with current time.
  262. *
  263. * @param name
  264. * the name of the committer used for the {@code commit}
  265. * @param email
  266. * the email of the committer used for the {@code commit}
  267. * @return {@code this}
  268. */
  269. public CommitCommand setCommitter(String name, String email) {
  270. checkCallable();
  271. return setCommitter(new PersonIdent(name, email));
  272. }
  273. /**
  274. * @return the committer used for the {@code commit}. If no committer was
  275. * specified {@code null} is returned and the default
  276. * {@link PersonIdent} of this repo is used during execution of the
  277. * command
  278. */
  279. public PersonIdent getCommitter() {
  280. return committer;
  281. }
  282. /**
  283. * Sets the author for this {@code commit}. If no author is explicitly
  284. * specified because this method is never called or called with {@code null}
  285. * value then the author will be set to the committer.
  286. *
  287. * @param author
  288. * the author used for the {@code commit}
  289. * @return {@code this}
  290. */
  291. public CommitCommand setAuthor(PersonIdent author) {
  292. checkCallable();
  293. this.author = author;
  294. return this;
  295. }
  296. /**
  297. * Sets the author for this {@code commit}. If no author is explicitly
  298. * specified because this method is never called or called with {@code null}
  299. * value then the author will be set to the committer.
  300. *
  301. * @param name
  302. * the name of the author used for the {@code commit}
  303. * @param email
  304. * the email of the author used for the {@code commit}
  305. * @return {@code this}
  306. */
  307. public CommitCommand setAuthor(String name, String email) {
  308. checkCallable();
  309. return setAuthor(new PersonIdent(name, email));
  310. }
  311. /**
  312. * @return the author used for the {@code commit}. If no author was
  313. * specified {@code null} is returned and the default
  314. * {@link PersonIdent} of this repo is used during execution of the
  315. * command
  316. */
  317. public PersonIdent getAuthor() {
  318. return author;
  319. }
  320. }