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.

RecursiveMerger.java 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. * Copyright (C) 2012, Research In Motion Limited
  3. * Copyright (C) 2012, Christian Halstrick <christian.halstrick@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. /*
  45. * Contributors:
  46. * George Young - initial API and implementation
  47. * Christian Halstrick - initial API and implementation
  48. */
  49. package org.eclipse.jgit.merge;
  50. import java.io.IOException;
  51. import java.text.MessageFormat;
  52. import java.util.ArrayList;
  53. import java.util.Date;
  54. import java.util.List;
  55. import java.util.TimeZone;
  56. import org.eclipse.jgit.dircache.DirCache;
  57. import org.eclipse.jgit.dircache.DirCacheBuilder;
  58. import org.eclipse.jgit.dircache.DirCacheEntry;
  59. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  60. import org.eclipse.jgit.errors.NoMergeBaseException;
  61. import org.eclipse.jgit.internal.JGitText;
  62. import org.eclipse.jgit.lib.CommitBuilder;
  63. import org.eclipse.jgit.lib.ObjectId;
  64. import org.eclipse.jgit.lib.PersonIdent;
  65. import org.eclipse.jgit.lib.Repository;
  66. import org.eclipse.jgit.revwalk.RevCommit;
  67. import org.eclipse.jgit.revwalk.filter.RevFilter;
  68. import org.eclipse.jgit.treewalk.TreeWalk;
  69. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  70. /**
  71. * A three-way merger performing a content-merge if necessary across multiple
  72. * bases using recursion
  73. *
  74. * This merger extends the resolve merger and does several things differently:
  75. *
  76. * - allow more than one merge base, up to a maximum
  77. *
  78. * - uses "Lists" instead of Arrays for chained types
  79. *
  80. * - recursively merges the merge bases together to compute a usable base
  81. * @since 3.0
  82. */
  83. public class RecursiveMerger extends ResolveMerger {
  84. /**
  85. * The maximum number of merge bases. This merge will stop when the number
  86. * of merge bases exceeds this value
  87. */
  88. public final int MAX_BASES = 200;
  89. /**
  90. * Normal recursive merge when you want a choice of DirCache placement
  91. * inCore
  92. *
  93. * @param local
  94. * @param inCore
  95. */
  96. protected RecursiveMerger(Repository local, boolean inCore) {
  97. super(local, inCore);
  98. }
  99. /**
  100. * Normal recursive merge, implies not inCore
  101. *
  102. * @param local
  103. */
  104. protected RecursiveMerger(Repository local) {
  105. this(local, false);
  106. }
  107. /**
  108. * Get a single base commit for two given commits. If the two source commits
  109. * have more than one base commit recursively merge the base commits
  110. * together until you end up with a single base commit.
  111. *
  112. * @throws IOException
  113. * @throws IncorrectObjectTypeException
  114. */
  115. @Override
  116. protected RevCommit getBaseCommit(RevCommit a, RevCommit b)
  117. throws IncorrectObjectTypeException, IOException {
  118. return getBaseCommit(a, b, 0);
  119. }
  120. /**
  121. * Get a single base commit for two given commits. If the two source commits
  122. * have more than one base commit recursively merge the base commits
  123. * together until a virtual common base commit has been found.
  124. *
  125. * @param a
  126. * the first commit to be merged
  127. * @param b
  128. * the second commit to be merged
  129. * @param callDepth
  130. * the callDepth when this method is called recursively
  131. * @return the merge base of two commits. If a criss-cross merge required a
  132. * synthetic merge base this commit is visible only the merger's
  133. * RevWalk and will not be in the repository.
  134. * @throws IOException
  135. * @throws IncorrectObjectTypeException
  136. * one of the input objects is not a commit.
  137. * @throws NoMergeBaseException
  138. * too many merge bases are found or the computation of a common
  139. * merge base failed (e.g. because of a conflict).
  140. */
  141. protected RevCommit getBaseCommit(RevCommit a, RevCommit b, int callDepth)
  142. throws IOException {
  143. ArrayList<RevCommit> baseCommits = new ArrayList<RevCommit>();
  144. walk.reset();
  145. walk.setRevFilter(RevFilter.MERGE_BASE);
  146. walk.markStart(a);
  147. walk.markStart(b);
  148. RevCommit c;
  149. while ((c = walk.next()) != null)
  150. baseCommits.add(c);
  151. if (baseCommits.isEmpty())
  152. return null;
  153. if (baseCommits.size() == 1)
  154. return baseCommits.get(0);
  155. if (baseCommits.size() >= MAX_BASES)
  156. throw new NoMergeBaseException(NoMergeBaseException.MergeBaseFailureReason.TOO_MANY_MERGE_BASES, MessageFormat.format(
  157. JGitText.get().mergeRecursiveTooManyMergeBasesFor,
  158. Integer.valueOf(MAX_BASES), a.name(), b.name(),
  159. Integer.valueOf(baseCommits.size())));
  160. // We know we have more than one base commit. We have to do merges now
  161. // to determine a single base commit. We don't want to spoil the current
  162. // dircache and working tree with the results of this intermediate
  163. // merges. Therefore set the dircache to a new in-memory dircache and
  164. // disable that we update the working-tree. We set this back to the
  165. // original values once a single base commit is created.
  166. RevCommit currentBase = baseCommits.get(0);
  167. DirCache oldDircache = dircache;
  168. boolean oldIncore = inCore;
  169. WorkingTreeIterator oldWTreeIt = workingTreeIterator;
  170. workingTreeIterator = null;
  171. try {
  172. dircache = dircacheFromTree(currentBase.getTree());
  173. inCore = true;
  174. List<RevCommit> parents = new ArrayList<RevCommit>();
  175. parents.add(currentBase);
  176. for (int commitIdx = 1; commitIdx < baseCommits.size(); commitIdx++) {
  177. RevCommit nextBase = baseCommits.get(commitIdx);
  178. if (commitIdx >= MAX_BASES)
  179. throw new NoMergeBaseException(
  180. NoMergeBaseException.MergeBaseFailureReason.TOO_MANY_MERGE_BASES,
  181. MessageFormat.format(
  182. JGitText.get().mergeRecursiveTooManyMergeBasesFor,
  183. Integer.valueOf(MAX_BASES), a.name(), b.name(),
  184. Integer.valueOf(baseCommits.size())));
  185. parents.add(nextBase);
  186. if (mergeTrees(
  187. openTree(getBaseCommit(currentBase, nextBase,
  188. callDepth + 1).getTree()),
  189. currentBase.getTree(), nextBase.getTree(), true))
  190. currentBase = createCommitForTree(resultTree, parents);
  191. else
  192. throw new NoMergeBaseException(
  193. NoMergeBaseException.MergeBaseFailureReason.CONFLICTS_DURING_MERGE_BASE_CALCULATION,
  194. MessageFormat.format(
  195. JGitText.get().mergeRecursiveConflictsWhenMergingCommonAncestors,
  196. currentBase.getName(), nextBase.getName()));
  197. }
  198. } finally {
  199. inCore = oldIncore;
  200. dircache = oldDircache;
  201. workingTreeIterator = oldWTreeIt;
  202. toBeCheckedOut.clear();
  203. toBeDeleted.clear();
  204. modifiedFiles.clear();
  205. unmergedPaths.clear();
  206. mergeResults.clear();
  207. failingPaths.clear();
  208. }
  209. return currentBase;
  210. }
  211. /**
  212. * Create a new commit by explicitly specifying the content tree and the
  213. * parents. The commit message is not set and author/committer are set to
  214. * the current user.
  215. *
  216. * @param tree
  217. * the tree this commit should capture
  218. * @param parents
  219. * the list of parent commits
  220. * @return a new commit visible only within this merger's RevWalk.
  221. * @throws IOException
  222. */
  223. private RevCommit createCommitForTree(ObjectId tree, List<RevCommit> parents)
  224. throws IOException {
  225. CommitBuilder c = new CommitBuilder();
  226. c.setTreeId(tree);
  227. c.setParentIds(parents);
  228. c.setAuthor(mockAuthor(parents));
  229. c.setCommitter(c.getAuthor());
  230. return RevCommit.parse(walk, c.build());
  231. }
  232. private static PersonIdent mockAuthor(List<RevCommit> parents) {
  233. String name = RecursiveMerger.class.getSimpleName();
  234. int time = 0;
  235. for (RevCommit p : parents)
  236. time = Math.max(time, p.getCommitTime());
  237. return new PersonIdent(
  238. name, name + "@JGit", //$NON-NLS-1$
  239. new Date((time + 1) * 1000L),
  240. TimeZone.getTimeZone("GMT+0000")); //$NON-NLS-1$
  241. }
  242. /**
  243. * Create a new in memory dircache which has the same content as a given
  244. * tree.
  245. *
  246. * @param treeId
  247. * the tree which should be used to fill the dircache
  248. * @return a new in memory dircache
  249. * @throws IOException
  250. */
  251. private DirCache dircacheFromTree(ObjectId treeId) throws IOException {
  252. DirCache ret = DirCache.newInCore();
  253. DirCacheBuilder aBuilder = ret.builder();
  254. TreeWalk atw = new TreeWalk(reader);
  255. atw.addTree(treeId);
  256. atw.setRecursive(true);
  257. while (atw.next()) {
  258. DirCacheEntry e = new DirCacheEntry(atw.getRawPath());
  259. e.setFileMode(atw.getFileMode(0));
  260. e.setObjectId(atw.getObjectId(0));
  261. aBuilder.add(e);
  262. }
  263. aBuilder.finish();
  264. return ret;
  265. }
  266. }