Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

MergeCommand.java 18KB

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