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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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.NullProgressMonitor;
  62. import org.eclipse.jgit.lib.ObjectId;
  63. import org.eclipse.jgit.lib.ObjectIdRef;
  64. import org.eclipse.jgit.lib.ProgressMonitor;
  65. import org.eclipse.jgit.lib.Ref;
  66. import org.eclipse.jgit.lib.Ref.Storage;
  67. import org.eclipse.jgit.lib.Repository;
  68. import org.eclipse.jgit.merge.MergeMessageFormatter;
  69. import org.eclipse.jgit.merge.MergeStrategy;
  70. import org.eclipse.jgit.merge.ResolveMerger;
  71. import org.eclipse.jgit.revwalk.RevCommit;
  72. import org.eclipse.jgit.revwalk.RevWalk;
  73. import org.eclipse.jgit.treewalk.FileTreeIterator;
  74. /**
  75. * A class used to execute a {@code cherry-pick} command. It has setters for all
  76. * supported options and arguments of this command and a {@link #call()} method
  77. * to finally execute the command. Each instance of this class should only be
  78. * used for one invocation of the command (means: one call to {@link #call()})
  79. *
  80. * @see <a
  81. * href="http://www.kernel.org/pub/software/scm/git/docs/git-cherry-pick.html"
  82. * >Git documentation about cherry-pick</a>
  83. */
  84. public class CherryPickCommand extends GitCommand<CherryPickResult> {
  85. private String reflogPrefix = "cherry-pick:"; //$NON-NLS-1$
  86. private List<Ref> commits = new LinkedList<>();
  87. private String ourCommitName = null;
  88. private MergeStrategy strategy = MergeStrategy.RECURSIVE;
  89. private Integer mainlineParentNumber;
  90. private boolean noCommit = false;
  91. private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
  92. /**
  93. * Constructor for CherryPickCommand
  94. *
  95. * @param repo
  96. * the {@link org.eclipse.jgit.lib.Repository}
  97. */
  98. protected CherryPickCommand(Repository repo) {
  99. super(repo);
  100. }
  101. /**
  102. * {@inheritDoc}
  103. * <p>
  104. * Executes the {@code Cherry-Pick} command with all the options and
  105. * parameters collected by the setter methods (e.g. {@link #include(Ref)} of
  106. * this class. Each instance of this class should only be used for one
  107. * invocation of the command. Don't call this method twice on an instance.
  108. */
  109. @Override
  110. public CherryPickResult call() throws GitAPIException, NoMessageException,
  111. UnmergedPathsException, ConcurrentRefUpdateException,
  112. WrongRepositoryStateException, NoHeadException {
  113. RevCommit newHead = null;
  114. List<Ref> cherryPickedRefs = new LinkedList<>();
  115. checkCallable();
  116. try (RevWalk revWalk = new RevWalk(repo)) {
  117. // get the head commit
  118. Ref headRef = repo.exactRef(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, //$NON-NLS-1$
  140. cherryPickName });
  141. if (merger.merge(newHead, srcCommit)) {
  142. if (AnyObjectId.isEqual(newHead.getTree().getId(),
  143. merger.getResultTreeId()))
  144. continue;
  145. DirCacheCheckout dco = new DirCacheCheckout(repo,
  146. newHead.getTree(), repo.lockDirCache(),
  147. merger.getResultTreeId());
  148. dco.setFailOnConflict(true);
  149. dco.setProgressMonitor(monitor);
  150. dco.checkout();
  151. if (!noCommit)
  152. newHead = new Git(getRepository()).commit()
  153. .setMessage(srcCommit.getFullMessage())
  154. .setReflogComment(reflogPrefix + " " //$NON-NLS-1$
  155. + srcCommit.getShortMessage())
  156. .setAuthor(srcCommit.getAuthorIdent())
  157. .setNoVerify(true).call();
  158. cherryPickedRefs.add(src);
  159. } else {
  160. if (merger.failed())
  161. return new CherryPickResult(merger.getFailingPaths());
  162. // there are merge conflicts
  163. String message = new MergeMessageFormatter()
  164. .formatWithConflicts(srcCommit.getFullMessage(),
  165. merger.getUnmergedPaths());
  166. if (!noCommit)
  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. }
  178. return new CherryPickResult(newHead, cherryPickedRefs);
  179. }
  180. private RevCommit getParentCommit(RevCommit srcCommit, RevWalk revWalk)
  181. throws MultipleParentsNotAllowedException, MissingObjectException,
  182. IOException {
  183. final RevCommit srcParent;
  184. if (mainlineParentNumber == null) {
  185. if (srcCommit.getParentCount() != 1)
  186. throw new MultipleParentsNotAllowedException(
  187. MessageFormat.format(
  188. JGitText.get().canOnlyCherryPickCommitsWithOneParent,
  189. srcCommit.name(),
  190. Integer.valueOf(srcCommit.getParentCount())));
  191. srcParent = srcCommit.getParent(0);
  192. } else {
  193. if (mainlineParentNumber.intValue() > srcCommit.getParentCount())
  194. throw new JGitInternalException(MessageFormat.format(
  195. JGitText.get().commitDoesNotHaveGivenParent, srcCommit,
  196. mainlineParentNumber));
  197. srcParent = srcCommit
  198. .getParent(mainlineParentNumber.intValue() - 1);
  199. }
  200. revWalk.parseHeaders(srcParent);
  201. return srcParent;
  202. }
  203. /**
  204. * Include a reference to a commit
  205. *
  206. * @param commit
  207. * a reference to a commit which is cherry-picked to the current
  208. * head
  209. * @return {@code this}
  210. */
  211. public CherryPickCommand include(Ref commit) {
  212. checkCallable();
  213. commits.add(commit);
  214. return this;
  215. }
  216. /**
  217. * Include a commit
  218. *
  219. * @param commit
  220. * the Id of a commit which is cherry-picked to the current head
  221. * @return {@code this}
  222. */
  223. public CherryPickCommand include(AnyObjectId commit) {
  224. return include(commit.getName(), commit);
  225. }
  226. /**
  227. * Include a commit
  228. *
  229. * @param name
  230. * a name given to the commit
  231. * @param commit
  232. * the Id of a commit which is cherry-picked to the current head
  233. * @return {@code this}
  234. */
  235. public CherryPickCommand include(String name, AnyObjectId commit) {
  236. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  237. commit.copy()));
  238. }
  239. /**
  240. * Set the name that should be used in the "OURS" place for conflict markers
  241. *
  242. * @param ourCommitName
  243. * the name that should be used in the "OURS" place for conflict
  244. * markers
  245. * @return {@code this}
  246. */
  247. public CherryPickCommand setOurCommitName(String ourCommitName) {
  248. this.ourCommitName = ourCommitName;
  249. return this;
  250. }
  251. /**
  252. * Set the prefix to use in the reflog.
  253. * <p>
  254. * This is primarily needed for implementing rebase in terms of
  255. * cherry-picking
  256. *
  257. * @param prefix
  258. * including ":"
  259. * @return {@code this}
  260. * @since 3.1
  261. */
  262. public CherryPickCommand setReflogPrefix(String prefix) {
  263. this.reflogPrefix = prefix;
  264. return this;
  265. }
  266. /**
  267. * Set the {@code MergeStrategy}
  268. *
  269. * @param strategy
  270. * The merge strategy to use during this Cherry-pick.
  271. * @return {@code this}
  272. * @since 3.4
  273. */
  274. public CherryPickCommand setStrategy(MergeStrategy strategy) {
  275. this.strategy = strategy;
  276. return this;
  277. }
  278. /**
  279. * Set the (1-based) parent number to diff against
  280. *
  281. * @param mainlineParentNumber
  282. * the (1-based) parent number to diff against. This allows
  283. * cherry-picking of merges.
  284. * @return {@code this}
  285. * @since 3.4
  286. */
  287. public CherryPickCommand setMainlineParentNumber(int mainlineParentNumber) {
  288. this.mainlineParentNumber = Integer.valueOf(mainlineParentNumber);
  289. return this;
  290. }
  291. /**
  292. * Allows cherry-picking changes without committing them.
  293. * <p>
  294. * NOTE: The behavior of cherry-pick is undefined if you pick multiple
  295. * commits or if HEAD does not match the index state before cherry-picking.
  296. *
  297. * @param noCommit
  298. * true to cherry-pick without committing, false to commit after
  299. * each pick (default)
  300. * @return {@code this}
  301. * @since 3.5
  302. */
  303. public CherryPickCommand setNoCommit(boolean noCommit) {
  304. this.noCommit = noCommit;
  305. return this;
  306. }
  307. /**
  308. * The progress monitor associated with the cherry-pick operation. By
  309. * default, this is set to <code>NullProgressMonitor</code>
  310. *
  311. * @see NullProgressMonitor
  312. * @param monitor
  313. * a {@link org.eclipse.jgit.lib.ProgressMonitor}
  314. * @return {@code this}
  315. * @since 4.11
  316. */
  317. public CherryPickCommand setProgressMonitor(ProgressMonitor monitor) {
  318. if (monitor == null) {
  319. monitor = NullProgressMonitor.INSTANCE;
  320. }
  321. this.monitor = monitor;
  322. return this;
  323. }
  324. private String calculateOurName(Ref headRef) {
  325. if (ourCommitName != null)
  326. return ourCommitName;
  327. String targetRefName = headRef.getTarget().getName();
  328. String headName = Repository.shortenRefName(targetRefName);
  329. return headName;
  330. }
  331. /** {@inheritDoc} */
  332. @SuppressWarnings("nls")
  333. @Override
  334. public String toString() {
  335. return "CherryPickCommand [repo=" + repo + ",\ncommits=" + commits
  336. + ",\nmainlineParentNumber=" + mainlineParentNumber
  337. + ", noCommit=" + noCommit + ", ourCommitName=" + ourCommitName
  338. + ", reflogPrefix=" + reflogPrefix + ", strategy=" + strategy
  339. + "]";
  340. }
  341. }