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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. RevWalk revWalk = new RevWalk(repo);
  116. try {
  117. // get the head commit
  118. Ref headRef = repo.getRef(Constants.HEAD);
  119. if (headRef == null)
  120. throw new NoHeadException(
  121. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  122. newHead = revWalk.parseCommit(headRef.getObjectId());
  123. // loop through all refs to be cherry-picked
  124. for (Ref src : commits) {
  125. // get the commit to be cherry-picked
  126. // handle annotated tags
  127. ObjectId srcObjectId = src.getPeeledObjectId();
  128. if (srcObjectId == null)
  129. srcObjectId = src.getObjectId();
  130. RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
  131. // get the parent of the commit to cherry-pick
  132. final RevCommit srcParent = getParentCommit(srcCommit, revWalk);
  133. String ourName = calculateOurName(headRef);
  134. String cherryPickName = srcCommit.getId().abbreviate(7).name()
  135. + " " + srcCommit.getShortMessage(); //$NON-NLS-1$
  136. ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
  137. merger.setWorkingTreeIterator(new FileTreeIterator(repo));
  138. merger.setBase(srcParent.getTree());
  139. merger.setCommitNames(new String[] { "BASE", ourName,
  140. cherryPickName });
  141. if (merger.merge(newHead, srcCommit)) {
  142. if (AnyObjectId.equals(newHead.getTree().getId(), merger
  143. .getResultTreeId()))
  144. continue;
  145. DirCacheCheckout dco = new DirCacheCheckout(repo,
  146. newHead.getTree(), repo.lockDirCache(),
  147. merger.getResultTreeId());
  148. dco.setFailOnConflict(true);
  149. dco.checkout();
  150. if (!noCommit)
  151. newHead = new Git(getRepository()).commit()
  152. .setMessage(srcCommit.getFullMessage())
  153. .setReflogComment(reflogPrefix + " " //$NON-NLS-1$
  154. + srcCommit.getShortMessage())
  155. .setAuthor(srcCommit.getAuthorIdent())
  156. .setNoVerify(true).call();
  157. cherryPickedRefs.add(src);
  158. } else {
  159. if (merger.failed())
  160. return new CherryPickResult(merger.getFailingPaths());
  161. // there are merge conflicts
  162. String message = new MergeMessageFormatter()
  163. .formatWithConflicts(srcCommit.getFullMessage(),
  164. merger.getUnmergedPaths());
  165. if (!noCommit)
  166. repo.writeCherryPickHead(srcCommit.getId());
  167. repo.writeMergeCommitMsg(message);
  168. return CherryPickResult.CONFLICT;
  169. }
  170. }
  171. } catch (IOException e) {
  172. throw new JGitInternalException(
  173. MessageFormat.format(
  174. JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand,
  175. e), e);
  176. } finally {
  177. revWalk.release();
  178. }
  179. return new CherryPickResult(newHead, cherryPickedRefs);
  180. }
  181. private RevCommit getParentCommit(RevCommit srcCommit, RevWalk revWalk)
  182. throws MultipleParentsNotAllowedException, MissingObjectException,
  183. IOException {
  184. final RevCommit srcParent;
  185. if (mainlineParentNumber == null) {
  186. if (srcCommit.getParentCount() != 1)
  187. throw new MultipleParentsNotAllowedException(
  188. MessageFormat.format(
  189. JGitText.get().canOnlyCherryPickCommitsWithOneParent,
  190. srcCommit.name(),
  191. Integer.valueOf(srcCommit.getParentCount())));
  192. srcParent = srcCommit.getParent(0);
  193. } else {
  194. if (mainlineParentNumber.intValue() > srcCommit.getParentCount())
  195. throw new JGitInternalException(MessageFormat.format(
  196. JGitText.get().commitDoesNotHaveGivenParent, srcCommit,
  197. mainlineParentNumber));
  198. srcParent = srcCommit
  199. .getParent(mainlineParentNumber.intValue() - 1);
  200. }
  201. revWalk.parseHeaders(srcParent);
  202. return srcParent;
  203. }
  204. /**
  205. * @param commit
  206. * a reference to a commit which is cherry-picked to the current
  207. * head
  208. * @return {@code this}
  209. */
  210. public CherryPickCommand include(Ref commit) {
  211. checkCallable();
  212. commits.add(commit);
  213. return this;
  214. }
  215. /**
  216. * @param commit
  217. * the Id of a commit which is cherry-picked to the current head
  218. * @return {@code this}
  219. */
  220. public CherryPickCommand include(AnyObjectId commit) {
  221. return include(commit.getName(), commit);
  222. }
  223. /**
  224. * @param name
  225. * a name given to the commit
  226. * @param commit
  227. * the Id of a commit which is cherry-picked to the current head
  228. * @return {@code this}
  229. */
  230. public CherryPickCommand include(String name, AnyObjectId commit) {
  231. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  232. commit.copy()));
  233. }
  234. /**
  235. * @param ourCommitName
  236. * the name that should be used in the "OURS" place for conflict
  237. * markers
  238. * @return {@code this}
  239. */
  240. public CherryPickCommand setOurCommitName(String ourCommitName) {
  241. this.ourCommitName = ourCommitName;
  242. return this;
  243. }
  244. /**
  245. * Set the prefix to use in the reflog.
  246. * <p>
  247. * This is primarily needed for implementing rebase in terms of
  248. * cherry-picking
  249. *
  250. * @param prefix
  251. * including ":"
  252. * @return {@code this}
  253. * @since 3.1
  254. */
  255. public CherryPickCommand setReflogPrefix(final String prefix) {
  256. this.reflogPrefix = prefix;
  257. return this;
  258. }
  259. /**
  260. * @param strategy
  261. * The merge strategy to use during this Cherry-pick.
  262. * @return {@code this}
  263. * @since 3.4
  264. */
  265. public CherryPickCommand setStrategy(MergeStrategy strategy) {
  266. this.strategy = strategy;
  267. return this;
  268. }
  269. /**
  270. * @param mainlineParentNumber
  271. * the (1-based) parent number to diff against. This allows
  272. * cherry-picking of merges.
  273. * @return {@code this}
  274. * @since 3.4
  275. */
  276. public CherryPickCommand setMainlineParentNumber(int mainlineParentNumber) {
  277. this.mainlineParentNumber = Integer.valueOf(mainlineParentNumber);
  278. return this;
  279. }
  280. /**
  281. * Allows cherry-picking changes without committing them.
  282. * <p>
  283. * NOTE: The behavior of cherry-pick is undefined if you pick multiple
  284. * commits or if HEAD does not match the index state before cherry-picking.
  285. *
  286. * @param noCommit
  287. * true to cherry-pick without committing, false to commit after
  288. * each pick (default)
  289. * @return {@code this}
  290. * @since 3.5
  291. */
  292. public CherryPickCommand setNoCommit(boolean noCommit) {
  293. this.noCommit = noCommit;
  294. return this;
  295. }
  296. private String calculateOurName(Ref headRef) {
  297. if (ourCommitName != null)
  298. return ourCommitName;
  299. String targetRefName = headRef.getTarget().getName();
  300. String headName = Repository.shortenRefName(targetRefName);
  301. return headName;
  302. }
  303. }