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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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.errors.MissingObjectException;
  58. import org.eclipse.jgit.internal.JGitText;
  59. import org.eclipse.jgit.lib.AnyObjectId;
  60. import org.eclipse.jgit.lib.Constants;
  61. import org.eclipse.jgit.lib.ObjectId;
  62. import org.eclipse.jgit.lib.ObjectIdRef;
  63. import org.eclipse.jgit.lib.Ref;
  64. import org.eclipse.jgit.lib.Ref.Storage;
  65. import org.eclipse.jgit.lib.Repository;
  66. import org.eclipse.jgit.merge.MergeMessageFormatter;
  67. import org.eclipse.jgit.merge.MergeStrategy;
  68. import org.eclipse.jgit.merge.ResolveMerger;
  69. import org.eclipse.jgit.revwalk.RevCommit;
  70. import org.eclipse.jgit.revwalk.RevWalk;
  71. import org.eclipse.jgit.treewalk.FileTreeIterator;
  72. /**
  73. * A class used to execute a {@code cherry-pick} command. It has setters for all
  74. * supported options and arguments of this command and a {@link #call()} method
  75. * to finally execute the command. Each instance of this class should only be
  76. * used for one invocation of the command (means: one call to {@link #call()})
  77. *
  78. * @see <a
  79. * href="http://www.kernel.org/pub/software/scm/git/docs/git-cherry-pick.html"
  80. * >Git documentation about cherry-pick</a>
  81. */
  82. public class CherryPickCommand extends GitCommand<CherryPickResult> {
  83. private String reflogPrefix = "cherry-pick:"; //$NON-NLS-1$
  84. private List<Ref> commits = new LinkedList<Ref>();
  85. private String ourCommitName = null;
  86. private MergeStrategy strategy = MergeStrategy.RECURSIVE;
  87. private Integer mainlineParentNumber;
  88. /**
  89. * @param repo
  90. */
  91. protected CherryPickCommand(Repository repo) {
  92. super(repo);
  93. }
  94. /**
  95. * Executes the {@code Cherry-Pick} command with all the options and
  96. * parameters collected by the setter methods (e.g. {@link #include(Ref)} of
  97. * this class. Each instance of this class should only be used for one
  98. * invocation of the command. Don't call this method twice on an instance.
  99. *
  100. * @return the result of the cherry-pick
  101. * @throws GitAPIException
  102. * @throws WrongRepositoryStateException
  103. * @throws ConcurrentRefUpdateException
  104. * @throws UnmergedPathsException
  105. * @throws NoMessageException
  106. * @throws NoHeadException
  107. */
  108. public CherryPickResult call() throws GitAPIException, NoMessageException,
  109. UnmergedPathsException, ConcurrentRefUpdateException,
  110. WrongRepositoryStateException, NoHeadException {
  111. RevCommit newHead = null;
  112. List<Ref> cherryPickedRefs = new LinkedList<Ref>();
  113. checkCallable();
  114. RevWalk revWalk = new RevWalk(repo);
  115. try {
  116. // get the head commit
  117. Ref headRef = repo.getRef(Constants.HEAD);
  118. if (headRef == null)
  119. throw new NoHeadException(
  120. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  121. newHead = revWalk.parseCommit(headRef.getObjectId());
  122. // loop through all refs to be cherry-picked
  123. for (Ref src : commits) {
  124. // get the commit to be cherry-picked
  125. // handle annotated tags
  126. ObjectId srcObjectId = src.getPeeledObjectId();
  127. if (srcObjectId == null)
  128. srcObjectId = src.getObjectId();
  129. RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
  130. // get the parent of the commit to cherry-pick
  131. final RevCommit srcParent = getParentCommit(srcCommit, revWalk);
  132. String ourName = calculateOurName(headRef);
  133. String cherryPickName = srcCommit.getId().abbreviate(7).name()
  134. + " " + srcCommit.getShortMessage(); //$NON-NLS-1$
  135. ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
  136. merger.setWorkingTreeIterator(new FileTreeIterator(repo));
  137. merger.setBase(srcParent.getTree());
  138. merger.setCommitNames(new String[] { "BASE", ourName,
  139. cherryPickName });
  140. if (merger.merge(newHead, srcCommit)) {
  141. if (AnyObjectId.equals(newHead.getTree().getId(), merger
  142. .getResultTreeId()))
  143. continue;
  144. DirCacheCheckout dco = new DirCacheCheckout(repo,
  145. newHead.getTree(), repo.lockDirCache(),
  146. merger.getResultTreeId());
  147. dco.setFailOnConflict(true);
  148. dco.checkout();
  149. newHead = new Git(getRepository()).commit()
  150. .setMessage(srcCommit.getFullMessage())
  151. .setReflogComment(reflogPrefix + " " //$NON-NLS-1$
  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. private RevCommit getParentCommit(RevCommit srcCommit, RevWalk revWalk)
  178. throws MultipleParentsNotAllowedException, MissingObjectException,
  179. IOException {
  180. final RevCommit srcParent;
  181. if (mainlineParentNumber == null) {
  182. if (srcCommit.getParentCount() != 1)
  183. throw new MultipleParentsNotAllowedException(
  184. MessageFormat.format(
  185. JGitText.get().canOnlyCherryPickCommitsWithOneParent,
  186. srcCommit.name(),
  187. Integer.valueOf(srcCommit.getParentCount())));
  188. srcParent = srcCommit.getParent(0);
  189. } else {
  190. if (mainlineParentNumber.intValue() > srcCommit.getParentCount())
  191. throw new JGitInternalException(MessageFormat.format(
  192. JGitText.get().commitDoesNotHaveGivenParent, srcCommit,
  193. mainlineParentNumber));
  194. srcParent = srcCommit
  195. .getParent(mainlineParentNumber.intValue() - 1);
  196. }
  197. revWalk.parseHeaders(srcParent);
  198. return srcParent;
  199. }
  200. /**
  201. * @param commit
  202. * a reference to a commit which is cherry-picked to the current
  203. * head
  204. * @return {@code this}
  205. */
  206. public CherryPickCommand include(Ref commit) {
  207. checkCallable();
  208. commits.add(commit);
  209. return this;
  210. }
  211. /**
  212. * @param commit
  213. * the Id of a commit which is cherry-picked to the current head
  214. * @return {@code this}
  215. */
  216. public CherryPickCommand include(AnyObjectId commit) {
  217. return include(commit.getName(), commit);
  218. }
  219. /**
  220. * @param name
  221. * a name given to the commit
  222. * @param commit
  223. * the Id of a commit which is cherry-picked to the current head
  224. * @return {@code this}
  225. */
  226. public CherryPickCommand include(String name, AnyObjectId commit) {
  227. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  228. commit.copy()));
  229. }
  230. /**
  231. * @param ourCommitName
  232. * the name that should be used in the "OURS" place for conflict
  233. * markers
  234. * @return {@code this}
  235. */
  236. public CherryPickCommand setOurCommitName(String ourCommitName) {
  237. this.ourCommitName = ourCommitName;
  238. return this;
  239. }
  240. /**
  241. * Set the prefix to use in the reflog.
  242. * <p>
  243. * This is primarily needed for implementing rebase in terms of
  244. * cherry-picking
  245. *
  246. * @param prefix
  247. * including ":"
  248. * @return {@code this}
  249. * @since 3.1
  250. */
  251. public CherryPickCommand setReflogPrefix(final String prefix) {
  252. this.reflogPrefix = prefix;
  253. return this;
  254. }
  255. /**
  256. * @param strategy
  257. * The merge strategy to use during this Cherry-pick.
  258. * @return {@code this}
  259. * @since 3.4
  260. */
  261. public CherryPickCommand setStrategy(MergeStrategy strategy) {
  262. this.strategy = strategy;
  263. return this;
  264. }
  265. /**
  266. * @param mainlineParentNumber
  267. * the (1-based) parent number to diff against. This allows
  268. * cherry-picking of merges.
  269. * @return {@code this}
  270. * @since 3.4
  271. */
  272. public CherryPickCommand setMainlineParentNumber(int mainlineParentNumber) {
  273. this.mainlineParentNumber = Integer.valueOf(mainlineParentNumber);
  274. return this;
  275. }
  276. private String calculateOurName(Ref headRef) {
  277. if (ourCommitName != null)
  278. return ourCommitName;
  279. String targetRefName = headRef.getTarget().getName();
  280. String headName = Repository.shortenRefName(targetRefName);
  281. return headName;
  282. }
  283. }