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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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.IOException;
  46. import java.text.MessageFormat;
  47. import java.util.Arrays;
  48. import java.util.LinkedList;
  49. import java.util.List;
  50. import java.util.Map;
  51. import org.eclipse.jgit.JGitText;
  52. import org.eclipse.jgit.api.MergeResult.MergeStatus;
  53. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  54. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  55. import org.eclipse.jgit.api.errors.InvalidMergeHeadsException;
  56. import org.eclipse.jgit.api.errors.JGitInternalException;
  57. import org.eclipse.jgit.api.errors.NoHeadException;
  58. import org.eclipse.jgit.api.errors.NoMessageException;
  59. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  60. import org.eclipse.jgit.dircache.DirCacheCheckout;
  61. import org.eclipse.jgit.lib.AnyObjectId;
  62. import org.eclipse.jgit.lib.Constants;
  63. import org.eclipse.jgit.lib.ObjectId;
  64. import org.eclipse.jgit.lib.ObjectIdRef;
  65. import org.eclipse.jgit.lib.Ref;
  66. import org.eclipse.jgit.lib.Ref.Storage;
  67. import org.eclipse.jgit.lib.RefUpdate;
  68. import org.eclipse.jgit.lib.RefUpdate.Result;
  69. import org.eclipse.jgit.lib.Repository;
  70. import org.eclipse.jgit.merge.MergeMessageFormatter;
  71. import org.eclipse.jgit.merge.MergeStrategy;
  72. import org.eclipse.jgit.merge.ResolveMerger;
  73. import org.eclipse.jgit.merge.ResolveMerger.MergeFailureReason;
  74. import org.eclipse.jgit.merge.ThreeWayMerger;
  75. import org.eclipse.jgit.revwalk.RevCommit;
  76. import org.eclipse.jgit.revwalk.RevWalk;
  77. import org.eclipse.jgit.treewalk.FileTreeIterator;
  78. /**
  79. * A class used to execute a {@code Merge} command. It has setters for all
  80. * supported options and arguments of this command and a {@link #call()} method
  81. * to finally execute the command. Each instance of this class should only be
  82. * used for one invocation of the command (means: one call to {@link #call()})
  83. *
  84. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-merge.html"
  85. * >Git documentation about Merge</a>
  86. */
  87. public class MergeCommand extends GitCommand<MergeResult> {
  88. private MergeStrategy mergeStrategy = MergeStrategy.RESOLVE;
  89. private List<Ref> commits = new LinkedList<Ref>();
  90. /**
  91. * @param repo
  92. */
  93. protected MergeCommand(Repository repo) {
  94. super(repo);
  95. }
  96. /**
  97. * Executes the {@code Merge} command with all the options and parameters
  98. * collected by the setter methods (e.g. {@link #include(Ref)}) of this
  99. * class. Each instance of this class should only be used for one invocation
  100. * of the command. Don't call this method twice on an instance.
  101. *
  102. * @return the result of the merge
  103. */
  104. public MergeResult call() throws NoHeadException,
  105. ConcurrentRefUpdateException, CheckoutConflictException,
  106. InvalidMergeHeadsException, WrongRepositoryStateException, NoMessageException {
  107. checkCallable();
  108. if (commits.size() != 1)
  109. throw new InvalidMergeHeadsException(
  110. commits.isEmpty() ? JGitText.get().noMergeHeadSpecified
  111. : MessageFormat.format(
  112. JGitText.get().mergeStrategyDoesNotSupportHeads,
  113. mergeStrategy.getName(),
  114. Integer.valueOf(commits.size())));
  115. RevWalk revWalk = null;
  116. try {
  117. Ref head = repo.getRef(Constants.HEAD);
  118. if (head == null)
  119. throw new NoHeadException(
  120. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  121. StringBuilder refLogMessage = new StringBuilder("merge ");
  122. // Check for FAST_FORWARD, ALREADY_UP_TO_DATE
  123. revWalk = new RevWalk(repo);
  124. RevCommit headCommit = revWalk.lookupCommit(head.getObjectId());
  125. // we know for now there is only one commit
  126. Ref ref = commits.get(0);
  127. refLogMessage.append(ref.getName());
  128. // handle annotated tags
  129. ObjectId objectId = ref.getPeeledObjectId();
  130. if (objectId == null)
  131. objectId = ref.getObjectId();
  132. RevCommit srcCommit = revWalk.lookupCommit(objectId);
  133. if (revWalk.isMergedInto(srcCommit, headCommit)) {
  134. setCallable(false);
  135. return new MergeResult(headCommit, srcCommit, new ObjectId[] {
  136. headCommit, srcCommit },
  137. MergeStatus.ALREADY_UP_TO_DATE, mergeStrategy, null, null);
  138. } else if (revWalk.isMergedInto(headCommit, srcCommit)) {
  139. // FAST_FORWARD detected: skip doing a real merge but only
  140. // update HEAD
  141. refLogMessage.append(": " + MergeStatus.FAST_FORWARD);
  142. DirCacheCheckout dco = new DirCacheCheckout(repo,
  143. headCommit.getTree(), repo.lockDirCache(),
  144. srcCommit.getTree());
  145. dco.setFailOnConflict(true);
  146. dco.checkout();
  147. updateHead(refLogMessage, srcCommit, head.getObjectId());
  148. setCallable(false);
  149. return new MergeResult(srcCommit, srcCommit, new ObjectId[] {
  150. headCommit, srcCommit }, MergeStatus.FAST_FORWARD,
  151. mergeStrategy, null, null);
  152. } else {
  153. repo.writeMergeCommitMsg(new MergeMessageFormatter().format(
  154. commits, head));
  155. repo.writeMergeHeads(Arrays.asList(ref.getObjectId()));
  156. ThreeWayMerger merger = (ThreeWayMerger) mergeStrategy
  157. .newMerger(repo);
  158. boolean noProblems;
  159. Map<String, org.eclipse.jgit.merge.MergeResult<?>> lowLevelResults = null;
  160. Map<String, MergeFailureReason> failingPaths = null;
  161. if (merger instanceof ResolveMerger) {
  162. ResolveMerger resolveMerger = (ResolveMerger) merger;
  163. resolveMerger.setCommitNames(new String[] {
  164. "BASE", "HEAD", ref.getName() });
  165. resolveMerger.setWorkingTreeIterator(new FileTreeIterator(repo));
  166. noProblems = merger.merge(headCommit, srcCommit);
  167. lowLevelResults = resolveMerger
  168. .getMergeResults();
  169. failingPaths = resolveMerger.getFailingPathes();
  170. } else
  171. noProblems = merger.merge(headCommit, srcCommit);
  172. if (noProblems) {
  173. DirCacheCheckout dco = new DirCacheCheckout(repo,
  174. headCommit.getTree(), repo.lockDirCache(),
  175. merger.getResultTreeId());
  176. dco.setFailOnConflict(true);
  177. dco.checkout();
  178. RevCommit newHead = new Git(getRepository()).commit().call();
  179. return new MergeResult(newHead.getId(),
  180. null, new ObjectId[] {
  181. headCommit.getId(), srcCommit.getId() },
  182. MergeStatus.MERGED, mergeStrategy, null, null);
  183. } else {
  184. if (failingPaths != null) {
  185. repo.writeMergeCommitMsg(null);
  186. repo.writeMergeHeads(null);
  187. return new MergeResult(null,
  188. merger.getBaseCommit(0, 1),
  189. new ObjectId[] {
  190. headCommit.getId(), srcCommit.getId() },
  191. MergeStatus.FAILED, mergeStrategy,
  192. lowLevelResults, null);
  193. } else
  194. return new MergeResult(null,
  195. merger.getBaseCommit(0, 1),
  196. new ObjectId[] { headCommit.getId(),
  197. srcCommit.getId() },
  198. MergeStatus.CONFLICTING, mergeStrategy,
  199. lowLevelResults, null);
  200. }
  201. }
  202. } catch (IOException e) {
  203. throw new JGitInternalException(
  204. MessageFormat.format(
  205. JGitText.get().exceptionCaughtDuringExecutionOfMergeCommand,
  206. e), e);
  207. } finally {
  208. if (revWalk != null)
  209. revWalk.release();
  210. }
  211. }
  212. private void updateHead(StringBuilder refLogMessage, ObjectId newHeadId,
  213. ObjectId oldHeadID) throws IOException,
  214. ConcurrentRefUpdateException {
  215. RefUpdate refUpdate = repo.updateRef(Constants.HEAD);
  216. refUpdate.setNewObjectId(newHeadId);
  217. refUpdate.setRefLogMessage(refLogMessage.toString(), false);
  218. refUpdate.setExpectedOldObjectId(oldHeadID);
  219. Result rc = refUpdate.update();
  220. switch (rc) {
  221. case NEW:
  222. case FAST_FORWARD:
  223. return;
  224. case REJECTED:
  225. case LOCK_FAILURE:
  226. throw new ConcurrentRefUpdateException(
  227. JGitText.get().couldNotLockHEAD, refUpdate.getRef(), rc);
  228. default:
  229. throw new JGitInternalException(MessageFormat.format(
  230. JGitText.get().updatingRefFailed, Constants.HEAD,
  231. newHeadId.toString(), rc));
  232. }
  233. }
  234. /**
  235. *
  236. * @param mergeStrategy
  237. * the {@link MergeStrategy} to be used
  238. * @return {@code this}
  239. */
  240. public MergeCommand setStrategy(MergeStrategy mergeStrategy) {
  241. checkCallable();
  242. this.mergeStrategy = mergeStrategy;
  243. return this;
  244. }
  245. /**
  246. * @param commit
  247. * a reference to a commit which is merged with the current head
  248. * @return {@code this}
  249. */
  250. public MergeCommand include(Ref commit) {
  251. checkCallable();
  252. commits.add(commit);
  253. return this;
  254. }
  255. /**
  256. * @param commit
  257. * the Id of a commit which is merged with the current head
  258. * @return {@code this}
  259. */
  260. public MergeCommand include(AnyObjectId commit) {
  261. return include(commit.getName(), commit);
  262. }
  263. /**
  264. * @param name
  265. * a name given to the commit
  266. * @param commit
  267. * the Id of a commit which is merged with the current head
  268. * @return {@code this}
  269. */
  270. public MergeCommand include(String name, AnyObjectId commit) {
  271. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  272. commit.copy()));
  273. }
  274. }