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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /*
  2. * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
  3. * Copyright (C) 2010-2012, 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.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.GitAPIException;
  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.internal.JGitText;
  63. import org.eclipse.jgit.lib.AnyObjectId;
  64. import org.eclipse.jgit.lib.Constants;
  65. import org.eclipse.jgit.lib.ObjectId;
  66. import org.eclipse.jgit.lib.ObjectIdRef;
  67. import org.eclipse.jgit.lib.Ref;
  68. import org.eclipse.jgit.lib.Ref.Storage;
  69. import org.eclipse.jgit.lib.RefUpdate;
  70. import org.eclipse.jgit.lib.RefUpdate.Result;
  71. import org.eclipse.jgit.lib.Repository;
  72. import org.eclipse.jgit.merge.MergeMessageFormatter;
  73. import org.eclipse.jgit.merge.MergeStrategy;
  74. import org.eclipse.jgit.merge.Merger;
  75. import org.eclipse.jgit.merge.ResolveMerger;
  76. import org.eclipse.jgit.merge.ResolveMerger.MergeFailureReason;
  77. import org.eclipse.jgit.merge.SquashMessageFormatter;
  78. import org.eclipse.jgit.revwalk.RevCommit;
  79. import org.eclipse.jgit.revwalk.RevWalk;
  80. import org.eclipse.jgit.revwalk.RevWalkUtils;
  81. import org.eclipse.jgit.treewalk.FileTreeIterator;
  82. /**
  83. * A class used to execute a {@code Merge} command. It has setters for all
  84. * supported options and arguments of this command and a {@link #call()} method
  85. * to finally execute the command. Each instance of this class should only be
  86. * used for one invocation of the command (means: one call to {@link #call()})
  87. *
  88. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-merge.html"
  89. * >Git documentation about Merge</a>
  90. */
  91. public class MergeCommand extends GitCommand<MergeResult> {
  92. private MergeStrategy mergeStrategy = MergeStrategy.RESOLVE;
  93. private List<Ref> commits = new LinkedList<Ref>();
  94. private boolean squash;
  95. private FastForwardMode fastForwardMode = FastForwardMode.FF;
  96. /**
  97. * The modes available for fast forward merges (corresponding to the --ff,
  98. * --no-ff and --ff-only options).
  99. */
  100. public enum FastForwardMode {
  101. /**
  102. * Corresponds to the default --ff option (for a fast forward update the
  103. * branch pointer only).
  104. */
  105. FF,
  106. /**
  107. * Corresponds to the --no-ff option (create a merge commit even for a
  108. * fast forward).
  109. */
  110. NO_FF,
  111. /**
  112. * Corresponds to the --ff-only option (abort unless the merge is a fast
  113. * forward).
  114. */
  115. FF_ONLY;
  116. /**
  117. * The modes available for fast forward merges corresponding to the
  118. * options under branch.<name>.branch config option.
  119. */
  120. public enum MergeOptions {
  121. /**
  122. * {@link FastForwardMode#FF}.
  123. */
  124. __FF,
  125. /**
  126. * {@link FastForwardMode#NO_FF}.
  127. */
  128. __NO_FF,
  129. /**
  130. * {@link FastForwardMode#FF_ONLY}.
  131. */
  132. __FF_ONLY;
  133. /**
  134. * Map from <code>FastForwardMode</code> to
  135. * <code>FastForwardMode.MergeOptions</code>.
  136. *
  137. * @param ffMode
  138. * the <code>FastForwardMode</code> value to be mapped
  139. * @return the mapped code>FastForwardMode.MergeOptions</code> value
  140. */
  141. public static MergeOptions valueOf(FastForwardMode ffMode) {
  142. switch (ffMode) {
  143. case NO_FF:
  144. return __NO_FF;
  145. case FF_ONLY:
  146. return __FF_ONLY;
  147. default:
  148. return __FF;
  149. }
  150. }
  151. }
  152. /**
  153. * The modes available for fast forward merges corresponding to the
  154. * options under merge.ff config option.
  155. */
  156. public enum Merge {
  157. /**
  158. * {@link FastForwardMode#FF}.
  159. */
  160. TRUE,
  161. /**
  162. * {@link FastForwardMode#NO_FF}.
  163. */
  164. FALSE,
  165. /**
  166. * {@link FastForwardMode#FF_ONLY}.
  167. */
  168. ONLY;
  169. /**
  170. * Map from <code>FastForwardMode</code> to
  171. * <code>FastForwardMode.Merge</code>.
  172. *
  173. * @param ffMode
  174. * the <code>FastForwardMode</code> value to be mapped
  175. * @return the mapped code>FastForwardMode.Merge</code> value
  176. */
  177. public static Merge valueOf(FastForwardMode ffMode) {
  178. switch (ffMode) {
  179. case NO_FF:
  180. return FALSE;
  181. case FF_ONLY:
  182. return ONLY;
  183. default:
  184. return TRUE;
  185. }
  186. }
  187. }
  188. /**
  189. * Map from <code>FastForwardMode.Merge</code> to
  190. * <code>FastForwardMode</code>.
  191. *
  192. * @param ffMode
  193. * the <code>FastForwardMode.Merge</code> value to be mapped
  194. * @return the mapped code>FastForwardMode</code> value
  195. */
  196. public static FastForwardMode valueOf(FastForwardMode.Merge ffMode) {
  197. switch (ffMode) {
  198. case FALSE:
  199. return NO_FF;
  200. case ONLY:
  201. return FF_ONLY;
  202. default:
  203. return FF;
  204. }
  205. }
  206. /**
  207. * Map from <code>FastForwardMode.MergeOptions</code> to
  208. * <code>FastForwardMode</code>.
  209. *
  210. * @param ffMode
  211. * the <code>FastForwardMode.MergeOptions</code> value to be
  212. * mapped
  213. * @return the mapped code>FastForwardMode</code> value
  214. */
  215. public static FastForwardMode valueOf(
  216. FastForwardMode.MergeOptions ffMode) {
  217. switch (ffMode) {
  218. case __NO_FF:
  219. return NO_FF;
  220. case __FF_ONLY:
  221. return FF_ONLY;
  222. default:
  223. return FF;
  224. }
  225. }
  226. }
  227. /**
  228. * @param repo
  229. */
  230. protected MergeCommand(Repository repo) {
  231. super(repo);
  232. }
  233. /**
  234. * Executes the {@code Merge} command with all the options and parameters
  235. * collected by the setter methods (e.g. {@link #include(Ref)}) of this
  236. * class. Each instance of this class should only be used for one invocation
  237. * of the command. Don't call this method twice on an instance.
  238. *
  239. * @return the result of the merge
  240. */
  241. public MergeResult call() throws GitAPIException, NoHeadException,
  242. ConcurrentRefUpdateException, CheckoutConflictException,
  243. InvalidMergeHeadsException, WrongRepositoryStateException, NoMessageException {
  244. checkCallable();
  245. checkParameters();
  246. RevWalk revWalk = null;
  247. DirCacheCheckout dco = null;
  248. try {
  249. Ref head = repo.getRef(Constants.HEAD);
  250. if (head == null)
  251. throw new NoHeadException(
  252. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  253. StringBuilder refLogMessage = new StringBuilder("merge "); //$NON-NLS-1$
  254. // Check for FAST_FORWARD, ALREADY_UP_TO_DATE
  255. revWalk = new RevWalk(repo);
  256. // we know for now there is only one commit
  257. Ref ref = commits.get(0);
  258. refLogMessage.append(ref.getName());
  259. // handle annotated tags
  260. ObjectId objectId = ref.getPeeledObjectId();
  261. if (objectId == null)
  262. objectId = ref.getObjectId();
  263. RevCommit srcCommit = revWalk.lookupCommit(objectId);
  264. ObjectId headId = head.getObjectId();
  265. if (headId == null) {
  266. revWalk.parseHeaders(srcCommit);
  267. dco = new DirCacheCheckout(repo,
  268. repo.lockDirCache(), srcCommit.getTree());
  269. dco.setFailOnConflict(true);
  270. dco.checkout();
  271. RefUpdate refUpdate = repo
  272. .updateRef(head.getTarget().getName());
  273. refUpdate.setNewObjectId(objectId);
  274. refUpdate.setExpectedOldObjectId(null);
  275. refUpdate.setRefLogMessage("initial pull", false); //$NON-NLS-1$
  276. if (refUpdate.update() != Result.NEW)
  277. throw new NoHeadException(
  278. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  279. setCallable(false);
  280. return new MergeResult(srcCommit, srcCommit, new ObjectId[] {
  281. null, srcCommit }, MergeStatus.FAST_FORWARD,
  282. mergeStrategy, null, null);
  283. }
  284. RevCommit headCommit = revWalk.lookupCommit(headId);
  285. if (revWalk.isMergedInto(srcCommit, headCommit)) {
  286. setCallable(false);
  287. return new MergeResult(headCommit, srcCommit, new ObjectId[] {
  288. headCommit, srcCommit },
  289. MergeStatus.ALREADY_UP_TO_DATE, mergeStrategy, null, null);
  290. } else if (revWalk.isMergedInto(headCommit, srcCommit)
  291. && fastForwardMode == FastForwardMode.FF) {
  292. // FAST_FORWARD detected: skip doing a real merge but only
  293. // update HEAD
  294. refLogMessage.append(": " + MergeStatus.FAST_FORWARD); //$NON-NLS-1$
  295. dco = new DirCacheCheckout(repo,
  296. headCommit.getTree(), repo.lockDirCache(),
  297. srcCommit.getTree());
  298. dco.setFailOnConflict(true);
  299. dco.checkout();
  300. String msg = null;
  301. ObjectId newHead, base = null;
  302. MergeStatus mergeStatus = null;
  303. if (!squash) {
  304. updateHead(refLogMessage, srcCommit, headId);
  305. newHead = base = srcCommit;
  306. mergeStatus = MergeStatus.FAST_FORWARD;
  307. } else {
  308. msg = JGitText.get().squashCommitNotUpdatingHEAD;
  309. newHead = base = headId;
  310. mergeStatus = MergeStatus.FAST_FORWARD_SQUASHED;
  311. List<RevCommit> squashedCommits = RevWalkUtils.find(
  312. revWalk, srcCommit, headCommit);
  313. String squashMessage = new SquashMessageFormatter().format(
  314. squashedCommits, head);
  315. repo.writeSquashCommitMsg(squashMessage);
  316. }
  317. setCallable(false);
  318. return new MergeResult(newHead, base, new ObjectId[] {
  319. headCommit, srcCommit }, mergeStatus, mergeStrategy,
  320. null, msg);
  321. } else {
  322. if (fastForwardMode == FastForwardMode.FF_ONLY) {
  323. return new MergeResult(headCommit, srcCommit,
  324. new ObjectId[] { headCommit, srcCommit },
  325. MergeStatus.ABORTED, mergeStrategy, null, null);
  326. }
  327. String mergeMessage = ""; //$NON-NLS-1$
  328. if (!squash) {
  329. mergeMessage = new MergeMessageFormatter().format(
  330. commits, head);
  331. repo.writeMergeCommitMsg(mergeMessage);
  332. repo.writeMergeHeads(Arrays.asList(ref.getObjectId()));
  333. } else {
  334. List<RevCommit> squashedCommits = RevWalkUtils.find(
  335. revWalk, srcCommit, headCommit);
  336. String squashMessage = new SquashMessageFormatter().format(
  337. squashedCommits, head);
  338. repo.writeSquashCommitMsg(squashMessage);
  339. }
  340. Merger merger = mergeStrategy.newMerger(repo);
  341. boolean noProblems;
  342. Map<String, org.eclipse.jgit.merge.MergeResult<?>> lowLevelResults = null;
  343. Map<String, MergeFailureReason> failingPaths = null;
  344. List<String> unmergedPaths = null;
  345. if (merger instanceof ResolveMerger) {
  346. ResolveMerger resolveMerger = (ResolveMerger) merger;
  347. resolveMerger.setCommitNames(new String[] {
  348. "BASE", "HEAD", ref.getName() }); //$NON-NLS-1$
  349. resolveMerger.setWorkingTreeIterator(new FileTreeIterator(repo));
  350. noProblems = merger.merge(headCommit, srcCommit);
  351. lowLevelResults = resolveMerger
  352. .getMergeResults();
  353. failingPaths = resolveMerger.getFailingPaths();
  354. unmergedPaths = resolveMerger.getUnmergedPaths();
  355. } else
  356. noProblems = merger.merge(headCommit, srcCommit);
  357. refLogMessage.append(": Merge made by "); //$NON-NLS-1$
  358. if (!revWalk.isMergedInto(headCommit, srcCommit))
  359. refLogMessage.append(mergeStrategy.getName());
  360. else
  361. refLogMessage.append("recursive"); //$NON-NLS-1$
  362. refLogMessage.append('.');
  363. if (noProblems) {
  364. dco = new DirCacheCheckout(repo,
  365. headCommit.getTree(), repo.lockDirCache(),
  366. merger.getResultTreeId());
  367. dco.setFailOnConflict(true);
  368. dco.checkout();
  369. String msg = null;
  370. RevCommit newHead = null;
  371. MergeStatus mergeStatus = null;
  372. if (!squash) {
  373. newHead = new Git(getRepository()).commit()
  374. .setReflogComment(refLogMessage.toString()).call();
  375. mergeStatus = MergeStatus.MERGED;
  376. } else {
  377. msg = JGitText.get().squashCommitNotUpdatingHEAD;
  378. newHead = headCommit;
  379. mergeStatus = MergeStatus.MERGED_SQUASHED;
  380. }
  381. return new MergeResult(newHead.getId(), null,
  382. new ObjectId[] { headCommit.getId(),
  383. srcCommit.getId() }, mergeStatus,
  384. mergeStrategy, null, msg);
  385. } else {
  386. if (failingPaths != null) {
  387. repo.writeMergeCommitMsg(null);
  388. repo.writeMergeHeads(null);
  389. return new MergeResult(null,
  390. merger.getBaseCommit(0, 1),
  391. new ObjectId[] {
  392. headCommit.getId(), srcCommit.getId() },
  393. MergeStatus.FAILED, mergeStrategy,
  394. lowLevelResults, failingPaths, null);
  395. } else {
  396. String mergeMessageWithConflicts = new MergeMessageFormatter()
  397. .formatWithConflicts(mergeMessage,
  398. unmergedPaths);
  399. repo.writeMergeCommitMsg(mergeMessageWithConflicts);
  400. return new MergeResult(null,
  401. merger.getBaseCommit(0, 1),
  402. new ObjectId[] { headCommit.getId(),
  403. srcCommit.getId() },
  404. MergeStatus.CONFLICTING, mergeStrategy,
  405. lowLevelResults, null);
  406. }
  407. }
  408. }
  409. } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
  410. List<String> conflicts = (dco == null) ? Collections
  411. .<String> emptyList() : dco.getConflicts();
  412. throw new CheckoutConflictException(conflicts, e);
  413. } catch (IOException e) {
  414. throw new JGitInternalException(
  415. MessageFormat.format(
  416. JGitText.get().exceptionCaughtDuringExecutionOfMergeCommand,
  417. e), e);
  418. } finally {
  419. if (revWalk != null)
  420. revWalk.release();
  421. }
  422. }
  423. private void checkParameters() throws InvalidMergeHeadsException {
  424. if (squash && fastForwardMode == FastForwardMode.NO_FF) {
  425. throw new JGitInternalException(
  426. JGitText.get().cannotCombineSquashWithNoff);
  427. }
  428. if (commits.size() != 1)
  429. throw new InvalidMergeHeadsException(
  430. commits.isEmpty() ? JGitText.get().noMergeHeadSpecified
  431. : MessageFormat.format(
  432. JGitText.get().mergeStrategyDoesNotSupportHeads,
  433. mergeStrategy.getName(),
  434. Integer.valueOf(commits.size())));
  435. }
  436. private void updateHead(StringBuilder refLogMessage, ObjectId newHeadId,
  437. ObjectId oldHeadID) throws IOException,
  438. ConcurrentRefUpdateException {
  439. RefUpdate refUpdate = repo.updateRef(Constants.HEAD);
  440. refUpdate.setNewObjectId(newHeadId);
  441. refUpdate.setRefLogMessage(refLogMessage.toString(), false);
  442. refUpdate.setExpectedOldObjectId(oldHeadID);
  443. Result rc = refUpdate.update();
  444. switch (rc) {
  445. case NEW:
  446. case FAST_FORWARD:
  447. return;
  448. case REJECTED:
  449. case LOCK_FAILURE:
  450. throw new ConcurrentRefUpdateException(
  451. JGitText.get().couldNotLockHEAD, refUpdate.getRef(), rc);
  452. default:
  453. throw new JGitInternalException(MessageFormat.format(
  454. JGitText.get().updatingRefFailed, Constants.HEAD,
  455. newHeadId.toString(), rc));
  456. }
  457. }
  458. /**
  459. *
  460. * @param mergeStrategy
  461. * the {@link MergeStrategy} to be used
  462. * @return {@code this}
  463. */
  464. public MergeCommand setStrategy(MergeStrategy mergeStrategy) {
  465. checkCallable();
  466. this.mergeStrategy = mergeStrategy;
  467. return this;
  468. }
  469. /**
  470. * @param commit
  471. * a reference to a commit which is merged with the current head
  472. * @return {@code this}
  473. */
  474. public MergeCommand include(Ref commit) {
  475. checkCallable();
  476. commits.add(commit);
  477. return this;
  478. }
  479. /**
  480. * @param commit
  481. * the Id of a commit which is merged with the current head
  482. * @return {@code this}
  483. */
  484. public MergeCommand include(AnyObjectId commit) {
  485. return include(commit.getName(), commit);
  486. }
  487. /**
  488. * @param name
  489. * a name given to the commit
  490. * @param commit
  491. * the Id of a commit which is merged with the current head
  492. * @return {@code this}
  493. */
  494. public MergeCommand include(String name, AnyObjectId commit) {
  495. return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
  496. commit.copy()));
  497. }
  498. /**
  499. * If <code>true</code>, will prepare the next commit in working tree and
  500. * index as if a real merge happened, but do not make the commit or move the
  501. * HEAD. Otherwise, perform the merge and commit the result.
  502. * <p>
  503. * In case the merge was successful but this flag was set to
  504. * <code>true</code> a {@link MergeResult} with status
  505. * {@link MergeStatus#MERGED_SQUASHED} or
  506. * {@link MergeStatus#FAST_FORWARD_SQUASHED} is returned.
  507. *
  508. * @param squash
  509. * whether to squash commits or not
  510. * @return {@code this}
  511. * @since 2.0
  512. */
  513. public MergeCommand setSquash(boolean squash) {
  514. checkCallable();
  515. this.squash = squash;
  516. return this;
  517. }
  518. /**
  519. * Sets the fast forward mode.
  520. *
  521. * @param fastForwardMode
  522. * corresponds to the --ff/--no-ff/--ff-only options. --ff is the
  523. * default option.
  524. * @return {@code this}
  525. * @since 2.2
  526. */
  527. public MergeCommand setFastForward(FastForwardMode fastForwardMode) {
  528. checkCallable();
  529. this.fastForwardMode = fastForwardMode;
  530. return this;
  531. }
  532. }