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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 String reflogPrefix = "cherry-pick:"; //$NON-NLS-1$
  83. private List<Ref> commits = new LinkedList<Ref>();
  84. private String ourCommitName = null;
  85. /**
  86. * @param repo
  87. */
  88. protected CherryPickCommand(Repository repo) {
  89. super(repo);
  90. }
  91. /**
  92. * Executes the {@code Cherry-Pick} command with all the options and
  93. * parameters collected by the setter methods (e.g. {@link #include(Ref)} of
  94. * this class. Each instance of this class should only be used for one
  95. * invocation of the command. Don't call this method twice on an instance.
  96. *
  97. * @return the result of the cherry-pick
  98. * @throws GitAPIException
  99. * @throws WrongRepositoryStateException
  100. * @throws ConcurrentRefUpdateException
  101. * @throws UnmergedPathsException
  102. * @throws NoMessageException
  103. * @throws NoHeadException
  104. */
  105. public CherryPickResult call() throws GitAPIException, NoMessageException,
  106. UnmergedPathsException, ConcurrentRefUpdateException,
  107. WrongRepositoryStateException, NoHeadException {
  108. RevCommit newHead = null;
  109. List<Ref> cherryPickedRefs = new LinkedList<Ref>();
  110. checkCallable();
  111. RevWalk revWalk = new RevWalk(repo);
  112. try {
  113. // get the head commit
  114. Ref headRef = repo.getRef(Constants.HEAD);
  115. if (headRef == null)
  116. throw new NoHeadException(
  117. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  118. newHead = revWalk.parseCommit(headRef.getObjectId());
  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.RECURSIVE
  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(newHead, srcCommit)) {
  146. if (AnyObjectId.equals(newHead.getTree().getId(), merger
  147. .getResultTreeId()))
  148. continue;
  149. DirCacheCheckout dco = new DirCacheCheckout(repo,
  150. newHead.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(reflogPrefix + " " //$NON-NLS-1$
  157. + srcCommit.getShortMessage())
  158. .setAuthor(srcCommit.getAuthorIdent()).call();
  159. cherryPickedRefs.add(src);
  160. } else {
  161. if (merger.failed())
  162. return new CherryPickResult(merger.getFailingPaths());
  163. // there are merge conflicts
  164. String message = new MergeMessageFormatter()
  165. .formatWithConflicts(srcCommit.getFullMessage(),
  166. merger.getUnmergedPaths());
  167. repo.writeCherryPickHead(srcCommit.getId());
  168. repo.writeMergeCommitMsg(message);
  169. return CherryPickResult.CONFLICT;
  170. }
  171. }
  172. } catch (IOException e) {
  173. throw new JGitInternalException(
  174. MessageFormat.format(
  175. JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand,
  176. e), e);
  177. } finally {
  178. revWalk.release();
  179. }
  180. return new CherryPickResult(newHead, cherryPickedRefs);
  181. }
  182. /**
  183. * @param commit
  184. * a reference to a commit which is cherry-picked to the current
  185. * head
  186. * @return {@code this}
  187. */
  188. public CherryPickCommand include(Ref commit) {
  189. checkCallable();
  190. commits.add(commit);
  191. return this;
  192. }
  193. /**
  194. * @param commit
  195. * the Id of a commit which is cherry-picked to the current head
  196. * @return {@code this}
  197. */
  198. public CherryPickCommand include(AnyObjectId commit) {
  199. return include(commit.getName(), commit);
  200. }
  201. /**
  202. * @param name
  203. * a name given to the commit
  204. * @param commit
  205. * the Id of a commit which is cherry-picked to the current head
  206. * @return {@code this}
  207. */
  208. public CherryPickCommand include(String name, AnyObjectId commit) {
  209. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  210. commit.copy()));
  211. }
  212. /**
  213. * @param ourCommitName
  214. * the name that should be used in the "OURS" place for conflict
  215. * markers
  216. * @return {@code this}
  217. */
  218. public CherryPickCommand setOurCommitName(String ourCommitName) {
  219. this.ourCommitName = ourCommitName;
  220. return this;
  221. }
  222. /**
  223. * Set the prefix to use in the reflog.
  224. * <p>
  225. * This is primarily needed for implementing rebase in terms of
  226. * cherry-picking
  227. *
  228. * @param prefix
  229. * including ":"
  230. * @return {@code this}
  231. */
  232. public CherryPickCommand setReflogPrefix(final String prefix) {
  233. this.reflogPrefix = prefix;
  234. return this;
  235. }
  236. private String calculateOurName(Ref headRef) {
  237. if (ourCommitName != null)
  238. return ourCommitName;
  239. String targetRefName = headRef.getTarget().getName();
  240. String headName = Repository.shortenRefName(targetRefName);
  241. return headName;
  242. }
  243. }