Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

MergeCommand.java 10KB

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