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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /*
  2. * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.api;
  44. import java.io.IOException;
  45. import java.text.MessageFormat;
  46. import java.util.LinkedList;
  47. import java.util.List;
  48. import org.eclipse.jgit.JGitText;
  49. import org.eclipse.jgit.dircache.DirCache;
  50. import org.eclipse.jgit.errors.UnmergedPathException;
  51. import org.eclipse.jgit.lib.CommitBuilder;
  52. import org.eclipse.jgit.lib.Constants;
  53. import org.eclipse.jgit.lib.ObjectId;
  54. import org.eclipse.jgit.lib.ObjectInserter;
  55. import org.eclipse.jgit.lib.PersonIdent;
  56. import org.eclipse.jgit.lib.Ref;
  57. import org.eclipse.jgit.lib.RefUpdate;
  58. import org.eclipse.jgit.lib.Repository;
  59. import org.eclipse.jgit.lib.RepositoryState;
  60. import org.eclipse.jgit.lib.RefUpdate.Result;
  61. import org.eclipse.jgit.revwalk.RevCommit;
  62. import org.eclipse.jgit.revwalk.RevWalk;
  63. /**
  64. * A class used to execute a {@code Commit} command. It has setters for all
  65. * supported options and arguments of this command and a {@link #call()} method
  66. * to finally execute the command.
  67. *
  68. * @see <a
  69. * href="http://www.kernel.org/pub/software/scm/git/docs/git-commit.html"
  70. * >Git documentation about Commit</a>
  71. */
  72. public class CommitCommand extends GitCommand<RevCommit> {
  73. private PersonIdent author;
  74. private PersonIdent committer;
  75. private String message;
  76. private boolean all;
  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 RevCommit} 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. if (all && !repo.isBare() && repo.getWorkTree() != null) {
  122. Git git = new Git(repo);
  123. try {
  124. git.add()
  125. .addFilepattern(".")
  126. .setUpdate(true).call();
  127. } catch (NoFilepatternException e) {
  128. // should really not happen
  129. throw new JGitInternalException(e.getMessage(), e);
  130. }
  131. }
  132. Ref head = repo.getRef(Constants.HEAD);
  133. if (head == null)
  134. throw new NoHeadException(
  135. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  136. // determine the current HEAD and the commit it is referring to
  137. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}");
  138. if (headId != null)
  139. parents.add(0, headId);
  140. // lock the index
  141. DirCache index = repo.lockDirCache();
  142. try {
  143. ObjectInserter odi = repo.newObjectInserter();
  144. try {
  145. // Write the index as tree to the object database. This may
  146. // fail for example when the index contains unmerged paths
  147. // (unresolved conflicts)
  148. ObjectId indexTreeId = index.writeTree(odi);
  149. // Create a Commit object, populate it and write it
  150. CommitBuilder commit = new CommitBuilder();
  151. commit.setCommitter(committer);
  152. commit.setAuthor(author);
  153. commit.setMessage(message);
  154. commit.setParentIds(parents);
  155. commit.setTreeId(indexTreeId);
  156. ObjectId commitId = odi.insert(commit);
  157. odi.flush();
  158. RevWalk revWalk = new RevWalk(repo);
  159. try {
  160. RevCommit revCommit = revWalk.parseCommit(commitId);
  161. RefUpdate ru = repo.updateRef(Constants.HEAD);
  162. ru.setNewObjectId(commitId);
  163. ru.setRefLogMessage("commit : "
  164. + revCommit.getShortMessage(), false);
  165. ru.setExpectedOldObjectId(headId);
  166. Result rc = ru.update();
  167. switch (rc) {
  168. case NEW:
  169. case FAST_FORWARD: {
  170. setCallable(false);
  171. if (state == RepositoryState.MERGING_RESOLVED) {
  172. // Commit was successful. Now delete the files
  173. // used for merge commits
  174. repo.writeMergeCommitMsg(null);
  175. repo.writeMergeHeads(null);
  176. }
  177. return revCommit;
  178. }
  179. case REJECTED:
  180. case LOCK_FAILURE:
  181. throw new ConcurrentRefUpdateException(JGitText
  182. .get().couldNotLockHEAD, ru.getRef(), rc);
  183. default:
  184. throw new JGitInternalException(MessageFormat
  185. .format(JGitText.get().updatingRefFailed,
  186. Constants.HEAD,
  187. commitId.toString(), rc));
  188. }
  189. } finally {
  190. revWalk.release();
  191. }
  192. } finally {
  193. odi.release();
  194. }
  195. } finally {
  196. index.unlock();
  197. }
  198. } catch (UnmergedPathException e) {
  199. // since UnmergedPathException is a subclass of IOException
  200. // which should not be wrapped by a JGitInternalException we
  201. // have to catch and re-throw it here
  202. throw e;
  203. } catch (IOException e) {
  204. throw new JGitInternalException(
  205. JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
  206. }
  207. }
  208. /**
  209. * Sets default values for not explicitly specified options. Then validates
  210. * that all required data has been provided.
  211. *
  212. * @param state
  213. * the state of the repository we are working on
  214. *
  215. * @throws NoMessageException
  216. * if the commit message has not been specified
  217. */
  218. private void processOptions(RepositoryState state) throws NoMessageException {
  219. if (committer == null)
  220. committer = new PersonIdent(repo);
  221. if (author == null)
  222. author = committer;
  223. // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
  224. if (state == RepositoryState.MERGING_RESOLVED) {
  225. try {
  226. parents = repo.readMergeHeads();
  227. } catch (IOException e) {
  228. throw new JGitInternalException(MessageFormat.format(
  229. JGitText.get().exceptionOccuredDuringReadingOfGIT_DIR,
  230. Constants.MERGE_HEAD, e), e);
  231. }
  232. if (message == null) {
  233. try {
  234. message = repo.readMergeCommitMsg();
  235. } catch (IOException e) {
  236. throw new JGitInternalException(MessageFormat.format(
  237. JGitText.get().exceptionOccuredDuringReadingOfGIT_DIR,
  238. Constants.MERGE_MSG, e), e);
  239. }
  240. }
  241. }
  242. if (message == null)
  243. // as long as we don't suppport -C option we have to have
  244. // an explicit message
  245. throw new NoMessageException(JGitText.get().commitMessageNotSpecified);
  246. }
  247. /**
  248. * @param message
  249. * the commit message used for the {@code commit}
  250. * @return {@code this}
  251. */
  252. public CommitCommand setMessage(String message) {
  253. checkCallable();
  254. this.message = message;
  255. return this;
  256. }
  257. /**
  258. * @return the commit message used for the <code>commit</code>
  259. */
  260. public String getMessage() {
  261. return message;
  262. }
  263. /**
  264. * Sets the committer for this {@code commit}. If no committer is explicitly
  265. * specified because this method is never called or called with {@code null}
  266. * value then the committer will be deduced from config info in repository,
  267. * with current time.
  268. *
  269. * @param committer
  270. * the committer used for the {@code commit}
  271. * @return {@code this}
  272. */
  273. public CommitCommand setCommitter(PersonIdent committer) {
  274. checkCallable();
  275. this.committer = committer;
  276. return this;
  277. }
  278. /**
  279. * Sets the committer for this {@code commit}. If no committer is explicitly
  280. * specified because this method is never called or called with {@code null}
  281. * value then the committer will be deduced from config info in repository,
  282. * with current time.
  283. *
  284. * @param name
  285. * the name of the committer used for the {@code commit}
  286. * @param email
  287. * the email of the committer used for the {@code commit}
  288. * @return {@code this}
  289. */
  290. public CommitCommand setCommitter(String name, String email) {
  291. checkCallable();
  292. return setCommitter(new PersonIdent(name, email));
  293. }
  294. /**
  295. * @return the committer used for the {@code commit}. If no committer was
  296. * specified {@code null} is returned and the default
  297. * {@link PersonIdent} of this repo is used during execution of the
  298. * command
  299. */
  300. public PersonIdent getCommitter() {
  301. return committer;
  302. }
  303. /**
  304. * Sets the author for this {@code commit}. If no author is explicitly
  305. * specified because this method is never called or called with {@code null}
  306. * value then the author will be set to the committer.
  307. *
  308. * @param author
  309. * the author used for the {@code commit}
  310. * @return {@code this}
  311. */
  312. public CommitCommand setAuthor(PersonIdent author) {
  313. checkCallable();
  314. this.author = author;
  315. return this;
  316. }
  317. /**
  318. * Sets the author for this {@code commit}. If no author is explicitly
  319. * specified because this method is never called or called with {@code null}
  320. * value then the author will be set to the committer.
  321. *
  322. * @param name
  323. * the name of the author used for the {@code commit}
  324. * @param email
  325. * the email of the author used for the {@code commit}
  326. * @return {@code this}
  327. */
  328. public CommitCommand setAuthor(String name, String email) {
  329. checkCallable();
  330. return setAuthor(new PersonIdent(name, email));
  331. }
  332. /**
  333. * @return the author used for the {@code commit}. If no author was
  334. * specified {@code null} is returned and the default
  335. * {@link PersonIdent} of this repo is used during execution of the
  336. * command
  337. */
  338. public PersonIdent getAuthor() {
  339. return author;
  340. }
  341. /**
  342. * If set to true the Commit command automatically stages files that have
  343. * been modified and deleted, but new files you not known by the repository
  344. * are not affected. This corresponds to the parameter -a on the command
  345. * line.
  346. *
  347. * @param all
  348. * @return {@code this}
  349. */
  350. public CommitCommand setAll(boolean all) {
  351. this.all = all;
  352. return this;
  353. }
  354. }