Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

CommitCommand.java 13KB

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