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

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