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.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. private String ourCommitName = null;
  84. /**
  85. * @param repo
  86. */
  87. protected CherryPickCommand(Repository repo) {
  88. super(repo);
  89. }
  90. /**
  91. * Executes the {@code Cherry-Pick} command with all the options and
  92. * parameters collected by the setter methods (e.g. {@link #include(Ref)} of
  93. * this class. Each instance of this class should only be used for one
  94. * invocation of the command. Don't call this method twice on an instance.
  95. *
  96. * @return the result of the cherry-pick
  97. * @throws GitAPIException
  98. * @throws WrongRepositoryStateException
  99. * @throws ConcurrentRefUpdateException
  100. * @throws UnmergedPathsException
  101. * @throws NoMessageException
  102. * @throws NoHeadException
  103. */
  104. public CherryPickResult call() throws GitAPIException, NoMessageException,
  105. UnmergedPathsException, ConcurrentRefUpdateException,
  106. WrongRepositoryStateException, NoHeadException {
  107. RevCommit newHead = null;
  108. List<Ref> cherryPickedRefs = new LinkedList<Ref>();
  109. checkCallable();
  110. RevWalk revWalk = new RevWalk(repo);
  111. try {
  112. // get the head commit
  113. Ref headRef = repo.getRef(Constants.HEAD);
  114. if (headRef == null)
  115. throw new NoHeadException(
  116. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  117. RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId());
  118. newHead = headCommit;
  119. // loop through all refs to be cherry-picked
  120. for (Ref src : commits) {
  121. // get the commit to be cherry-picked
  122. // handle annotated tags
  123. ObjectId srcObjectId = src.getPeeledObjectId();
  124. if (srcObjectId == null)
  125. srcObjectId = src.getObjectId();
  126. RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
  127. // get the parent of the commit to cherry-pick
  128. if (srcCommit.getParentCount() != 1)
  129. throw new MultipleParentsNotAllowedException(
  130. MessageFormat.format(
  131. JGitText.get().canOnlyCherryPickCommitsWithOneParent,
  132. srcCommit.name(),
  133. Integer.valueOf(srcCommit.getParentCount())));
  134. RevCommit srcParent = srcCommit.getParent(0);
  135. revWalk.parseHeaders(srcParent);
  136. String ourName = calculateOurName(headRef);
  137. String cherryPickName = srcCommit.getId().abbreviate(7).name()
  138. + " " + srcCommit.getShortMessage(); //$NON-NLS-1$
  139. ResolveMerger merger = (ResolveMerger) MergeStrategy.RESOLVE
  140. .newMerger(repo);
  141. merger.setWorkingTreeIterator(new FileTreeIterator(repo));
  142. merger.setBase(srcParent.getTree());
  143. merger.setCommitNames(new String[] { "BASE", ourName,
  144. cherryPickName });
  145. if (merger.merge(headCommit, srcCommit)) {
  146. if (AnyObjectId.equals(headCommit.getTree().getId(), merger
  147. .getResultTreeId()))
  148. continue;
  149. DirCacheCheckout dco = new DirCacheCheckout(repo,
  150. headCommit.getTree(), repo.lockDirCache(),
  151. merger.getResultTreeId());
  152. dco.setFailOnConflict(true);
  153. dco.checkout();
  154. newHead = new Git(getRepository()).commit()
  155. .setMessage(srcCommit.getFullMessage())
  156. .setReflogComment(
  157. "cherry-pick: " //$NON-NLS-1$
  158. + srcCommit.getShortMessage())
  159. .setAuthor(srcCommit.getAuthorIdent()).call();
  160. cherryPickedRefs.add(src);
  161. } else {
  162. if (merger.failed())
  163. return new CherryPickResult(merger.getFailingPaths());
  164. // there are merge conflicts
  165. String message = new MergeMessageFormatter()
  166. .formatWithConflicts(srcCommit.getFullMessage(),
  167. merger.getUnmergedPaths());
  168. repo.writeCherryPickHead(srcCommit.getId());
  169. repo.writeMergeCommitMsg(message);
  170. return CherryPickResult.CONFLICT;
  171. }
  172. }
  173. } catch (IOException e) {
  174. throw new JGitInternalException(
  175. MessageFormat.format(
  176. JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand,
  177. e), e);
  178. } finally {
  179. revWalk.release();
  180. }
  181. return new CherryPickResult(newHead, cherryPickedRefs);
  182. }
  183. /**
  184. * @param commit
  185. * a reference to a commit which is cherry-picked to the current
  186. * head
  187. * @return {@code this}
  188. */
  189. public CherryPickCommand include(Ref commit) {
  190. checkCallable();
  191. commits.add(commit);
  192. return this;
  193. }
  194. /**
  195. * @param commit
  196. * the Id of a commit which is cherry-picked to the current head
  197. * @return {@code this}
  198. */
  199. public CherryPickCommand include(AnyObjectId commit) {
  200. return include(commit.getName(), commit);
  201. }
  202. /**
  203. * @param name
  204. * a name given to the commit
  205. * @param commit
  206. * the Id of a commit which is cherry-picked to the current head
  207. * @return {@code this}
  208. */
  209. public CherryPickCommand include(String name, AnyObjectId commit) {
  210. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  211. commit.copy()));
  212. }
  213. /**
  214. * @param ourCommitName
  215. * the name that should be used in the "OURS" place for conflict
  216. * markers
  217. * @return {@code this}
  218. */
  219. public CherryPickCommand setOurCommitName(String ourCommitName) {
  220. this.ourCommitName = ourCommitName;
  221. return this;
  222. }
  223. private String calculateOurName(Ref headRef) {
  224. if (ourCommitName != null)
  225. return ourCommitName;
  226. String targetRefName = headRef.getTarget().getName();
  227. String headName = Repository.shortenRefName(targetRefName);
  228. return headName;
  229. }
  230. }