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.

CherryPickCommand.java 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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.api.errors.ConcurrentRefUpdateException;
  49. import org.eclipse.jgit.api.errors.GitAPIException;
  50. import org.eclipse.jgit.api.errors.JGitInternalException;
  51. import org.eclipse.jgit.api.errors.MultipleParentsNotAllowedException;
  52. import org.eclipse.jgit.api.errors.NoHeadException;
  53. import org.eclipse.jgit.api.errors.NoMessageException;
  54. import org.eclipse.jgit.api.errors.UnmergedPathsException;
  55. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  56. import org.eclipse.jgit.dircache.DirCacheCheckout;
  57. import org.eclipse.jgit.internal.JGitText;
  58. import org.eclipse.jgit.lib.AnyObjectId;
  59. import org.eclipse.jgit.lib.Constants;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.ObjectIdRef;
  62. import org.eclipse.jgit.lib.Ref;
  63. import org.eclipse.jgit.lib.Ref.Storage;
  64. import org.eclipse.jgit.lib.Repository;
  65. import org.eclipse.jgit.merge.MergeMessageFormatter;
  66. import org.eclipse.jgit.merge.MergeStrategy;
  67. import org.eclipse.jgit.merge.ResolveMerger;
  68. import org.eclipse.jgit.revwalk.RevCommit;
  69. import org.eclipse.jgit.revwalk.RevWalk;
  70. import org.eclipse.jgit.treewalk.FileTreeIterator;
  71. /**
  72. * A class used to execute a {@code cherry-pick} command. It has setters for all
  73. * supported options and arguments of this command and a {@link #call()} method
  74. * to finally execute the command. Each instance of this class should only be
  75. * used for one invocation of the command (means: one call to {@link #call()})
  76. *
  77. * @see <a
  78. * href="http://www.kernel.org/pub/software/scm/git/docs/git-cherry-pick.html"
  79. * >Git documentation about cherry-pick</a>
  80. */
  81. public class CherryPickCommand extends GitCommand<CherryPickResult> {
  82. private List<Ref> commits = new LinkedList<Ref>();
  83. /**
  84. * @param repo
  85. */
  86. protected CherryPickCommand(Repository repo) {
  87. super(repo);
  88. }
  89. /**
  90. * Executes the {@code Cherry-Pick} command with all the options and
  91. * parameters collected by the setter methods (e.g. {@link #include(Ref)} of
  92. * this class. Each instance of this class should only be used for one
  93. * invocation of the command. Don't call this method twice on an instance.
  94. *
  95. * @return the result of the cherry-pick
  96. * @throws GitAPIException
  97. * @throws WrongRepositoryStateException
  98. * @throws ConcurrentRefUpdateException
  99. * @throws UnmergedPathsException
  100. * @throws NoMessageException
  101. * @throws NoHeadException
  102. */
  103. public CherryPickResult call() throws GitAPIException, NoMessageException,
  104. UnmergedPathsException, ConcurrentRefUpdateException,
  105. WrongRepositoryStateException, NoHeadException {
  106. RevCommit newHead = null;
  107. List<Ref> cherryPickedRefs = new LinkedList<Ref>();
  108. checkCallable();
  109. RevWalk revWalk = new RevWalk(repo);
  110. try {
  111. // get the head commit
  112. Ref headRef = repo.getRef(Constants.HEAD);
  113. if (headRef == null)
  114. throw new NoHeadException(
  115. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  116. RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId());
  117. newHead = headCommit;
  118. // loop through all refs to be cherry-picked
  119. for (Ref src : commits) {
  120. // get the commit to be cherry-picked
  121. // handle annotated tags
  122. ObjectId srcObjectId = src.getPeeledObjectId();
  123. if (srcObjectId == null)
  124. srcObjectId = src.getObjectId();
  125. RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
  126. // get the parent of the commit to cherry-pick
  127. if (srcCommit.getParentCount() != 1)
  128. throw new MultipleParentsNotAllowedException(
  129. MessageFormat.format(
  130. JGitText.get().canOnlyCherryPickCommitsWithOneParent,
  131. srcCommit.name(),
  132. Integer.valueOf(srcCommit.getParentCount())));
  133. RevCommit srcParent = srcCommit.getParent(0);
  134. revWalk.parseHeaders(srcParent);
  135. ResolveMerger merger = (ResolveMerger) MergeStrategy.RESOLVE
  136. .newMerger(repo);
  137. merger.setWorkingTreeIterator(new FileTreeIterator(repo));
  138. merger.setBase(srcParent.getTree());
  139. if (merger.merge(headCommit, srcCommit)) {
  140. if (AnyObjectId.equals(headCommit.getTree().getId(), merger
  141. .getResultTreeId()))
  142. continue;
  143. DirCacheCheckout dco = new DirCacheCheckout(repo,
  144. headCommit.getTree(), repo.lockDirCache(),
  145. merger.getResultTreeId());
  146. dco.setFailOnConflict(true);
  147. dco.checkout();
  148. newHead = new Git(getRepository()).commit()
  149. .setMessage(srcCommit.getFullMessage())
  150. .setReflogComment(
  151. "cherry-pick: "
  152. + srcCommit.getShortMessage())
  153. .setAuthor(srcCommit.getAuthorIdent()).call();
  154. cherryPickedRefs.add(src);
  155. } else {
  156. if (merger.failed())
  157. return new CherryPickResult(merger.getFailingPaths());
  158. // there are merge conflicts
  159. String message = new MergeMessageFormatter()
  160. .formatWithConflicts(srcCommit.getFullMessage(),
  161. merger.getUnmergedPaths());
  162. repo.writeCherryPickHead(srcCommit.getId());
  163. repo.writeMergeCommitMsg(message);
  164. return CherryPickResult.CONFLICT;
  165. }
  166. }
  167. } catch (IOException e) {
  168. throw new JGitInternalException(
  169. MessageFormat.format(
  170. JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand,
  171. e), e);
  172. } finally {
  173. revWalk.release();
  174. }
  175. return new CherryPickResult(newHead, cherryPickedRefs);
  176. }
  177. /**
  178. * @param commit
  179. * a reference to a commit which is cherry-picked to the current
  180. * head
  181. * @return {@code this}
  182. */
  183. public CherryPickCommand include(Ref commit) {
  184. checkCallable();
  185. commits.add(commit);
  186. return this;
  187. }
  188. /**
  189. * @param commit
  190. * the Id of a commit which is cherry-picked to the current head
  191. * @return {@code this}
  192. */
  193. public CherryPickCommand include(AnyObjectId commit) {
  194. return include(commit.getName(), commit);
  195. }
  196. /**
  197. * @param name
  198. * a name given to the commit
  199. * @param commit
  200. * the Id of a commit which is cherry-picked to the current head
  201. * @return {@code this}
  202. */
  203. public CherryPickCommand include(String name, AnyObjectId commit) {
  204. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  205. commit.copy()));
  206. }
  207. }