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