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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. // we know for now there is only one commit
  125. Ref ref = commits.get(0);
  126. refLogMessage.append(ref.getName());
  127. // handle annotated tags
  128. ObjectId objectId = ref.getPeeledObjectId();
  129. if (objectId == null)
  130. objectId = ref.getObjectId();
  131. RevCommit srcCommit = revWalk.lookupCommit(objectId);
  132. ObjectId headId = head.getObjectId();
  133. if (headId == null) {
  134. revWalk.parseHeaders(srcCommit);
  135. DirCacheCheckout dco = new DirCacheCheckout(repo,
  136. repo.lockDirCache(), srcCommit.getTree());
  137. dco.setFailOnConflict(true);
  138. dco.checkout();
  139. RefUpdate refUpdate = repo
  140. .updateRef(head.getTarget().getName());
  141. refUpdate.setNewObjectId(objectId);
  142. refUpdate.setExpectedOldObjectId(null);
  143. refUpdate.setRefLogMessage("initial pull", false);
  144. if (refUpdate.update() != Result.NEW)
  145. throw new NoHeadException(
  146. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  147. setCallable(false);
  148. return new MergeResult(srcCommit, srcCommit, new ObjectId[] {
  149. null, srcCommit }, MergeStatus.FAST_FORWARD,
  150. mergeStrategy, null, null);
  151. }
  152. RevCommit headCommit = revWalk.lookupCommit(headId);
  153. if (revWalk.isMergedInto(srcCommit, headCommit)) {
  154. setCallable(false);
  155. return new MergeResult(headCommit, srcCommit, new ObjectId[] {
  156. headCommit, srcCommit },
  157. MergeStatus.ALREADY_UP_TO_DATE, mergeStrategy, null, null);
  158. } else if (revWalk.isMergedInto(headCommit, srcCommit)) {
  159. // FAST_FORWARD detected: skip doing a real merge but only
  160. // update HEAD
  161. refLogMessage.append(": " + MergeStatus.FAST_FORWARD);
  162. DirCacheCheckout dco = new DirCacheCheckout(repo,
  163. headCommit.getTree(), repo.lockDirCache(),
  164. srcCommit.getTree());
  165. dco.setFailOnConflict(true);
  166. dco.checkout();
  167. updateHead(refLogMessage, srcCommit, headId);
  168. setCallable(false);
  169. return new MergeResult(srcCommit, srcCommit, new ObjectId[] {
  170. headCommit, srcCommit }, MergeStatus.FAST_FORWARD,
  171. mergeStrategy, null, null);
  172. } else {
  173. repo.writeMergeCommitMsg(new MergeMessageFormatter().format(
  174. commits, head));
  175. repo.writeMergeHeads(Arrays.asList(ref.getObjectId()));
  176. ThreeWayMerger merger = (ThreeWayMerger) mergeStrategy
  177. .newMerger(repo);
  178. boolean noProblems;
  179. Map<String, org.eclipse.jgit.merge.MergeResult<?>> lowLevelResults = null;
  180. Map<String, MergeFailureReason> failingPaths = null;
  181. if (merger instanceof ResolveMerger) {
  182. ResolveMerger resolveMerger = (ResolveMerger) merger;
  183. resolveMerger.setCommitNames(new String[] {
  184. "BASE", "HEAD", ref.getName() });
  185. resolveMerger.setWorkingTreeIterator(new FileTreeIterator(repo));
  186. noProblems = merger.merge(headCommit, srcCommit);
  187. lowLevelResults = resolveMerger
  188. .getMergeResults();
  189. failingPaths = resolveMerger.getFailingPaths();
  190. } else
  191. noProblems = merger.merge(headCommit, srcCommit);
  192. if (noProblems) {
  193. DirCacheCheckout dco = new DirCacheCheckout(repo,
  194. headCommit.getTree(), repo.lockDirCache(),
  195. merger.getResultTreeId());
  196. dco.setFailOnConflict(true);
  197. dco.checkout();
  198. RevCommit newHead = new Git(getRepository()).commit().call();
  199. return new MergeResult(newHead.getId(),
  200. null, new ObjectId[] {
  201. headCommit.getId(), srcCommit.getId() },
  202. MergeStatus.MERGED, mergeStrategy, null, null);
  203. } else {
  204. if (failingPaths != null) {
  205. repo.writeMergeCommitMsg(null);
  206. repo.writeMergeHeads(null);
  207. return new MergeResult(null,
  208. merger.getBaseCommit(0, 1),
  209. new ObjectId[] {
  210. headCommit.getId(), srcCommit.getId() },
  211. MergeStatus.FAILED, mergeStrategy,
  212. lowLevelResults, null);
  213. } else
  214. return new MergeResult(null,
  215. merger.getBaseCommit(0, 1),
  216. new ObjectId[] { headCommit.getId(),
  217. srcCommit.getId() },
  218. MergeStatus.CONFLICTING, mergeStrategy,
  219. lowLevelResults, null);
  220. }
  221. }
  222. } catch (IOException e) {
  223. throw new JGitInternalException(
  224. MessageFormat.format(
  225. JGitText.get().exceptionCaughtDuringExecutionOfMergeCommand,
  226. e), e);
  227. } finally {
  228. if (revWalk != null)
  229. revWalk.release();
  230. }
  231. }
  232. private void updateHead(StringBuilder refLogMessage, ObjectId newHeadId,
  233. ObjectId oldHeadID) throws IOException,
  234. ConcurrentRefUpdateException {
  235. RefUpdate refUpdate = repo.updateRef(Constants.HEAD);
  236. refUpdate.setNewObjectId(newHeadId);
  237. refUpdate.setRefLogMessage(refLogMessage.toString(), false);
  238. refUpdate.setExpectedOldObjectId(oldHeadID);
  239. Result rc = refUpdate.update();
  240. switch (rc) {
  241. case NEW:
  242. case FAST_FORWARD:
  243. return;
  244. case REJECTED:
  245. case LOCK_FAILURE:
  246. throw new ConcurrentRefUpdateException(
  247. JGitText.get().couldNotLockHEAD, refUpdate.getRef(), rc);
  248. default:
  249. throw new JGitInternalException(MessageFormat.format(
  250. JGitText.get().updatingRefFailed, Constants.HEAD,
  251. newHeadId.toString(), rc));
  252. }
  253. }
  254. /**
  255. *
  256. * @param mergeStrategy
  257. * the {@link MergeStrategy} to be used
  258. * @return {@code this}
  259. */
  260. public MergeCommand setStrategy(MergeStrategy mergeStrategy) {
  261. checkCallable();
  262. this.mergeStrategy = mergeStrategy;
  263. return this;
  264. }
  265. /**
  266. * @param commit
  267. * a reference to a commit which is merged with the current head
  268. * @return {@code this}
  269. */
  270. public MergeCommand include(Ref commit) {
  271. checkCallable();
  272. commits.add(commit);
  273. return this;
  274. }
  275. /**
  276. * @param commit
  277. * the Id of a commit which is merged with the current head
  278. * @return {@code this}
  279. */
  280. public MergeCommand include(AnyObjectId commit) {
  281. return include(commit.getName(), commit);
  282. }
  283. /**
  284. * @param name
  285. * a name given to the commit
  286. * @param commit
  287. * the Id of a commit which is merged with the current head
  288. * @return {@code this}
  289. */
  290. public MergeCommand include(String name, AnyObjectId commit) {
  291. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  292. commit.copy()));
  293. }
  294. }