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.

MergeCommand.java 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /*
  2. * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
  3. * Copyright (C) 2010, Stefan Lay <stefan.lay@sap.com>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.api;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.text.MessageFormat;
  48. import java.util.LinkedList;
  49. import java.util.List;
  50. import org.eclipse.jgit.JGitText;
  51. import org.eclipse.jgit.api.MergeResult.MergeStatus;
  52. import org.eclipse.jgit.lib.AnyObjectId;
  53. import org.eclipse.jgit.lib.Constants;
  54. import org.eclipse.jgit.lib.GitIndex;
  55. import org.eclipse.jgit.lib.ObjectId;
  56. import org.eclipse.jgit.lib.ObjectIdRef;
  57. import org.eclipse.jgit.lib.Ref;
  58. import org.eclipse.jgit.lib.Ref.Storage;
  59. import org.eclipse.jgit.lib.RefUpdate;
  60. import org.eclipse.jgit.lib.RefUpdate.Result;
  61. import org.eclipse.jgit.lib.Repository;
  62. import org.eclipse.jgit.lib.WorkDirCheckout;
  63. import org.eclipse.jgit.merge.MergeStrategy;
  64. import org.eclipse.jgit.revwalk.RevCommit;
  65. import org.eclipse.jgit.revwalk.RevWalk;
  66. /**
  67. * A class used to execute a {@code Merge} command. It has setters for all
  68. * supported options and arguments of this command and a {@link #call()} method
  69. * to finally execute the command. Each instance of this class should only be
  70. * used for one invocation of the command (means: one call to {@link #call()})
  71. * <p>
  72. * This is currently a very basic implementation which takes only one commits to
  73. * merge with as option. Furthermore it does supports only fast forward.
  74. *
  75. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-merge.html"
  76. * >Git documentation about Merge</a>
  77. */
  78. public class MergeCommand extends GitCommand<MergeResult> {
  79. private MergeStrategy mergeStrategy = MergeStrategy.SIMPLE_TWO_WAY_IN_CORE;
  80. private List<Ref> commits = new LinkedList<Ref>();
  81. /**
  82. * @param repo
  83. */
  84. protected MergeCommand(Repository repo) {
  85. super(repo);
  86. }
  87. /**
  88. * Executes the {@code Merge} command with all the options and parameters
  89. * collected by the setter methods (e.g. {@link #include(Ref)}) of this
  90. * class. Each instance of this class should only be used for one invocation
  91. * of the command. Don't call this method twice on an instance.
  92. *
  93. * @return the result of the merge
  94. */
  95. public MergeResult call() throws NoHeadException,
  96. ConcurrentRefUpdateException, CheckoutConflictException,
  97. InvalidMergeHeadsException {
  98. checkCallable();
  99. if (commits.size() != 1)
  100. throw new InvalidMergeHeadsException(
  101. commits.isEmpty() ? JGitText.get().noMergeHeadSpecified
  102. : MessageFormat.format(
  103. JGitText.get().mergeStrategyDoesNotSupportHeads,
  104. mergeStrategy.getName(), commits.size()));
  105. try {
  106. Ref head = repo.getRef(Constants.HEAD);
  107. if (head == null)
  108. throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  109. StringBuilder refLogMessage = new StringBuilder("merge ");
  110. // Check for FAST_FORWARD, ALREADY_UP_TO_DATE
  111. RevWalk revWalk = new RevWalk(repo);
  112. RevCommit headCommit = revWalk.lookupCommit(head.getObjectId());
  113. Ref ref = commits.get(0);
  114. refLogMessage.append(ref.getName());
  115. // handle annotated tags
  116. ObjectId objectId = ref.getPeeledObjectId();
  117. if (objectId == null)
  118. objectId = ref.getObjectId();
  119. RevCommit srcCommit = revWalk.lookupCommit(objectId);
  120. if (revWalk.isMergedInto(srcCommit, headCommit)) {
  121. setCallable(false);
  122. return new MergeResult(headCommit,
  123. MergeStatus.ALREADY_UP_TO_DATE, mergeStrategy);
  124. } else if (revWalk.isMergedInto(headCommit, srcCommit)) {
  125. // FAST_FORWARD detected: skip doing a real merge but only
  126. // update HEAD
  127. refLogMessage.append(": " + MergeStatus.FAST_FORWARD);
  128. checkoutNewHead(revWalk, headCommit, srcCommit);
  129. updateHead(refLogMessage, srcCommit, head.getObjectId());
  130. setCallable(false);
  131. return new MergeResult(srcCommit, MergeStatus.FAST_FORWARD,
  132. mergeStrategy);
  133. } else {
  134. return new MergeResult(
  135. headCommit,
  136. MergeResult.MergeStatus.NOT_SUPPORTED,
  137. mergeStrategy,
  138. JGitText.get().onlyAlreadyUpToDateAndFastForwardMergesAreAvailable);
  139. }
  140. } catch (IOException e) {
  141. throw new JGitInternalException(
  142. MessageFormat.format(
  143. JGitText.get().exceptionCaughtDuringExecutionOfMergeCommand,
  144. e));
  145. }
  146. }
  147. private void checkoutNewHead(RevWalk revWalk, RevCommit headCommit,
  148. RevCommit newHeadCommit) throws IOException, CheckoutConflictException {
  149. GitIndex index = repo.getIndex();
  150. File workDir = repo.getWorkDir();
  151. if (workDir != null) {
  152. WorkDirCheckout workDirCheckout = new WorkDirCheckout(repo,
  153. workDir, headCommit.asCommit(revWalk).getTree(), index,
  154. newHeadCommit.asCommit(revWalk).getTree());
  155. workDirCheckout.setFailOnConflict(true);
  156. try {
  157. workDirCheckout.checkout();
  158. } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
  159. throw new CheckoutConflictException(
  160. JGitText.get().couldNotCheckOutBecauseOfConflicts,
  161. workDirCheckout.getConflicts(), e);
  162. }
  163. index.write();
  164. }
  165. }
  166. private void updateHead(StringBuilder refLogMessage,
  167. ObjectId newHeadId, ObjectId oldHeadID) throws IOException,
  168. ConcurrentRefUpdateException {
  169. RefUpdate refUpdate = repo.updateRef(Constants.HEAD);
  170. refUpdate.setNewObjectId(newHeadId);
  171. refUpdate.setRefLogMessage(refLogMessage.toString(), false);
  172. refUpdate.setExpectedOldObjectId(oldHeadID);
  173. Result rc = refUpdate.update();
  174. switch (rc) {
  175. case NEW:
  176. case FAST_FORWARD:
  177. return;
  178. case REJECTED:
  179. case LOCK_FAILURE:
  180. throw new ConcurrentRefUpdateException(
  181. JGitText.get().couldNotLockHEAD, refUpdate.getRef(), rc);
  182. default:
  183. throw new JGitInternalException(MessageFormat.format(
  184. JGitText.get().updatingRefFailed, Constants.HEAD,
  185. newHeadId.toString(), rc));
  186. }
  187. }
  188. /**
  189. *
  190. * @param mergeStrategy
  191. * the {@link MergeStrategy} to be used
  192. * @return {@code this}
  193. */
  194. public MergeCommand setStrategy(MergeStrategy mergeStrategy) {
  195. checkCallable();
  196. this.mergeStrategy = mergeStrategy;
  197. return this;
  198. }
  199. /**
  200. * @param commit
  201. * a reference to a commit which is merged with the current
  202. * head
  203. * @return {@code this}
  204. */
  205. public MergeCommand include(Ref commit) {
  206. checkCallable();
  207. commits.add(commit);
  208. return this;
  209. }
  210. /**
  211. * @param commit
  212. * the Id of a commit which is merged with the current head
  213. * @return {@code this}
  214. */
  215. public MergeCommand include(AnyObjectId commit) {
  216. return include(commit.getName(), commit);
  217. }
  218. /**
  219. * @param name a name given to the commit
  220. * @param commit
  221. * the Id of a commit which is merged with the current head
  222. * @return {@code this}
  223. */
  224. public MergeCommand include(String name, AnyObjectId commit) {
  225. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  226. commit.copy()));
  227. }
  228. }