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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. private boolean noCommit = false;
  89. /**
  90. * @param repo
  91. */
  92. protected CherryPickCommand(Repository repo) {
  93. super(repo);
  94. }
  95. /**
  96. * Executes the {@code Cherry-Pick} command with all the options and
  97. * parameters collected by the setter methods (e.g. {@link #include(Ref)} of
  98. * this class. Each instance of this class should only be used for one
  99. * invocation of the command. Don't call this method twice on an instance.
  100. *
  101. * @return the result of the cherry-pick
  102. * @throws GitAPIException
  103. * @throws WrongRepositoryStateException
  104. * @throws ConcurrentRefUpdateException
  105. * @throws UnmergedPathsException
  106. * @throws NoMessageException
  107. * @throws NoHeadException
  108. */
  109. public CherryPickResult call() throws GitAPIException, NoMessageException,
  110. UnmergedPathsException, ConcurrentRefUpdateException,
  111. WrongRepositoryStateException, NoHeadException {
  112. RevCommit newHead = null;
  113. List<Ref> cherryPickedRefs = new LinkedList<Ref>();
  114. checkCallable();
  115. try (RevWalk revWalk = new RevWalk(repo)) {
  116. // get the head commit
  117. Ref headRef = repo.exactRef(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, //$NON-NLS-1$
  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. if (!noCommit)
  150. newHead = new Git(getRepository()).commit()
  151. .setMessage(srcCommit.getFullMessage())
  152. .setReflogComment(reflogPrefix + " " //$NON-NLS-1$
  153. + srcCommit.getShortMessage())
  154. .setAuthor(srcCommit.getAuthorIdent())
  155. .setNoVerify(true).call();
  156. cherryPickedRefs.add(src);
  157. } else {
  158. if (merger.failed())
  159. return new CherryPickResult(merger.getFailingPaths());
  160. // there are merge conflicts
  161. String message = new MergeMessageFormatter()
  162. .formatWithConflicts(srcCommit.getFullMessage(),
  163. merger.getUnmergedPaths());
  164. if (!noCommit)
  165. repo.writeCherryPickHead(srcCommit.getId());
  166. repo.writeMergeCommitMsg(message);
  167. return CherryPickResult.CONFLICT;
  168. }
  169. }
  170. } catch (IOException e) {
  171. throw new JGitInternalException(
  172. MessageFormat.format(
  173. JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand,
  174. e), e);
  175. }
  176. return new CherryPickResult(newHead, cherryPickedRefs);
  177. }
  178. private RevCommit getParentCommit(RevCommit srcCommit, RevWalk revWalk)
  179. throws MultipleParentsNotAllowedException, MissingObjectException,
  180. IOException {
  181. final RevCommit srcParent;
  182. if (mainlineParentNumber == null) {
  183. if (srcCommit.getParentCount() != 1)
  184. throw new MultipleParentsNotAllowedException(
  185. MessageFormat.format(
  186. JGitText.get().canOnlyCherryPickCommitsWithOneParent,
  187. srcCommit.name(),
  188. Integer.valueOf(srcCommit.getParentCount())));
  189. srcParent = srcCommit.getParent(0);
  190. } else {
  191. if (mainlineParentNumber.intValue() > srcCommit.getParentCount())
  192. throw new JGitInternalException(MessageFormat.format(
  193. JGitText.get().commitDoesNotHaveGivenParent, srcCommit,
  194. mainlineParentNumber));
  195. srcParent = srcCommit
  196. .getParent(mainlineParentNumber.intValue() - 1);
  197. }
  198. revWalk.parseHeaders(srcParent);
  199. return srcParent;
  200. }
  201. /**
  202. * @param commit
  203. * a reference to a commit which is cherry-picked to the current
  204. * head
  205. * @return {@code this}
  206. */
  207. public CherryPickCommand include(Ref commit) {
  208. checkCallable();
  209. commits.add(commit);
  210. return this;
  211. }
  212. /**
  213. * @param commit
  214. * the Id of a commit which is cherry-picked to the current head
  215. * @return {@code this}
  216. */
  217. public CherryPickCommand include(AnyObjectId commit) {
  218. return include(commit.getName(), commit);
  219. }
  220. /**
  221. * @param name
  222. * a name given to the commit
  223. * @param commit
  224. * the Id of a commit which is cherry-picked to the current head
  225. * @return {@code this}
  226. */
  227. public CherryPickCommand include(String name, AnyObjectId commit) {
  228. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  229. commit.copy()));
  230. }
  231. /**
  232. * @param ourCommitName
  233. * the name that should be used in the "OURS" place for conflict
  234. * markers
  235. * @return {@code this}
  236. */
  237. public CherryPickCommand setOurCommitName(String ourCommitName) {
  238. this.ourCommitName = ourCommitName;
  239. return this;
  240. }
  241. /**
  242. * Set the prefix to use in the reflog.
  243. * <p>
  244. * This is primarily needed for implementing rebase in terms of
  245. * cherry-picking
  246. *
  247. * @param prefix
  248. * including ":"
  249. * @return {@code this}
  250. * @since 3.1
  251. */
  252. public CherryPickCommand setReflogPrefix(final String prefix) {
  253. this.reflogPrefix = prefix;
  254. return this;
  255. }
  256. /**
  257. * @param strategy
  258. * The merge strategy to use during this Cherry-pick.
  259. * @return {@code this}
  260. * @since 3.4
  261. */
  262. public CherryPickCommand setStrategy(MergeStrategy strategy) {
  263. this.strategy = strategy;
  264. return this;
  265. }
  266. /**
  267. * @param mainlineParentNumber
  268. * the (1-based) parent number to diff against. This allows
  269. * cherry-picking of merges.
  270. * @return {@code this}
  271. * @since 3.4
  272. */
  273. public CherryPickCommand setMainlineParentNumber(int mainlineParentNumber) {
  274. this.mainlineParentNumber = Integer.valueOf(mainlineParentNumber);
  275. return this;
  276. }
  277. /**
  278. * Allows cherry-picking changes without committing them.
  279. * <p>
  280. * NOTE: The behavior of cherry-pick is undefined if you pick multiple
  281. * commits or if HEAD does not match the index state before cherry-picking.
  282. *
  283. * @param noCommit
  284. * true to cherry-pick without committing, false to commit after
  285. * each pick (default)
  286. * @return {@code this}
  287. * @since 3.5
  288. */
  289. public CherryPickCommand setNoCommit(boolean noCommit) {
  290. this.noCommit = noCommit;
  291. return this;
  292. }
  293. private String calculateOurName(Ref headRef) {
  294. if (ourCommitName != null)
  295. return ourCommitName;
  296. String targetRefName = headRef.getTarget().getName();
  297. String headName = Repository.shortenRefName(targetRefName);
  298. return headName;
  299. }
  300. }