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

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