View Javadoc
1   /*
2    * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.api;
44  
45  import java.io.IOException;
46  import java.text.MessageFormat;
47  import java.util.LinkedList;
48  import java.util.List;
49  
50  import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
51  import org.eclipse.jgit.api.errors.GitAPIException;
52  import org.eclipse.jgit.api.errors.JGitInternalException;
53  import org.eclipse.jgit.api.errors.MultipleParentsNotAllowedException;
54  import org.eclipse.jgit.api.errors.NoHeadException;
55  import org.eclipse.jgit.api.errors.NoMessageException;
56  import org.eclipse.jgit.api.errors.UnmergedPathsException;
57  import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
58  import org.eclipse.jgit.dircache.DirCacheCheckout;
59  import org.eclipse.jgit.errors.MissingObjectException;
60  import org.eclipse.jgit.internal.JGitText;
61  import org.eclipse.jgit.lib.AnyObjectId;
62  import org.eclipse.jgit.lib.Constants;
63  import org.eclipse.jgit.lib.ObjectId;
64  import org.eclipse.jgit.lib.ObjectIdRef;
65  import org.eclipse.jgit.lib.Ref;
66  import org.eclipse.jgit.lib.Ref.Storage;
67  import org.eclipse.jgit.lib.Repository;
68  import org.eclipse.jgit.merge.MergeMessageFormatter;
69  import org.eclipse.jgit.merge.MergeStrategy;
70  import org.eclipse.jgit.merge.ResolveMerger;
71  import org.eclipse.jgit.revwalk.RevCommit;
72  import org.eclipse.jgit.revwalk.RevWalk;
73  import org.eclipse.jgit.treewalk.FileTreeIterator;
74  
75  /**
76   * A class used to execute a {@code cherry-pick} command. It has setters for all
77   * supported options and arguments of this command and a {@link #call()} method
78   * to finally execute the command. Each instance of this class should only be
79   * used for one invocation of the command (means: one call to {@link #call()})
80   *
81   * @see <a
82   *      href="http://www.kernel.org/pub/software/scm/git/docs/git-cherry-pick.html"
83   *      >Git documentation about cherry-pick</a>
84   */
85  public class CherryPickCommand extends GitCommand<CherryPickResult> {
86  	private String reflogPrefix = "cherry-pick:"; //$NON-NLS-1$
87  
88  	private List<Ref> commits = new LinkedList<Ref>();
89  
90  	private String ourCommitName = null;
91  
92  	private MergeStrategy strategy = MergeStrategy.RECURSIVE;
93  
94  	private Integer mainlineParentNumber;
95  
96  	private boolean noCommit = false;
97  
98  	/**
99  	 * @param repo
100 	 */
101 	protected CherryPickCommand(Repository repo) {
102 		super(repo);
103 	}
104 
105 	/**
106 	 * Executes the {@code Cherry-Pick} command with all the options and
107 	 * parameters collected by the setter methods (e.g. {@link #include(Ref)} of
108 	 * this class. Each instance of this class should only be used for one
109 	 * invocation of the command. Don't call this method twice on an instance.
110 	 *
111 	 * @return the result of the cherry-pick
112 	 * @throws GitAPIException
113 	 * @throws WrongRepositoryStateException
114 	 * @throws ConcurrentRefUpdateException
115 	 * @throws UnmergedPathsException
116 	 * @throws NoMessageException
117 	 * @throws NoHeadException
118 	 */
119 	public CherryPickResult call() throws GitAPIException, NoMessageException,
120 			UnmergedPathsException, ConcurrentRefUpdateException,
121 			WrongRepositoryStateException, NoHeadException {
122 		RevCommit newHead = null;
123 		List<Ref> cherryPickedRefs = new LinkedList<Ref>();
124 		checkCallable();
125 
126 		try (RevWalk revWalk = new RevWalk(repo)) {
127 
128 			// get the head commit
129 			Ref headRef = repo.getRef(Constants.HEAD);
130 			if (headRef == null)
131 				throw new NoHeadException(
132 						JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
133 
134 			newHead = revWalk.parseCommit(headRef.getObjectId());
135 
136 			// loop through all refs to be cherry-picked
137 			for (Ref src : commits) {
138 				// get the commit to be cherry-picked
139 				// handle annotated tags
140 				ObjectId srcObjectId = src.getPeeledObjectId();
141 				if (srcObjectId == null)
142 					srcObjectId = src.getObjectId();
143 				RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
144 
145 				// get the parent of the commit to cherry-pick
146 				final RevCommit srcParent = getParentCommit(srcCommit, revWalk);
147 
148 				String ourName = calculateOurName(headRef);
149 				String cherryPickName = srcCommit.getId().abbreviate(7).name()
150 						+ " " + srcCommit.getShortMessage(); //$NON-NLS-1$
151 
152 				ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
153 				merger.setWorkingTreeIterator(new FileTreeIterator(repo));
154 				merger.setBase(srcParent.getTree());
155 				merger.setCommitNames(new String[] { "BASE", ourName, //$NON-NLS-1$
156 						cherryPickName });
157 				if (merger.merge(newHead, srcCommit)) {
158 					if (AnyObjectId.equals(newHead.getTree().getId(), merger
159 							.getResultTreeId()))
160 						continue;
161 					DirCacheCheckout dco = new DirCacheCheckout(repo,
162 							newHead.getTree(), repo.lockDirCache(),
163 							merger.getResultTreeId());
164 					dco.setFailOnConflict(true);
165 					dco.checkout();
166 					if (!noCommit)
167 						newHead = new Git(getRepository()).commit()
168 								.setMessage(srcCommit.getFullMessage())
169 								.setReflogComment(reflogPrefix + " " //$NON-NLS-1$
170 										+ srcCommit.getShortMessage())
171 								.setAuthor(srcCommit.getAuthorIdent())
172 								.setNoVerify(true).call();
173 					cherryPickedRefs.add(src);
174 				} else {
175 					if (merger.failed())
176 						return new CherryPickResult(merger.getFailingPaths());
177 
178 					// there are merge conflicts
179 
180 					String message = new MergeMessageFormatter()
181 							.formatWithConflicts(srcCommit.getFullMessage(),
182 									merger.getUnmergedPaths());
183 
184 					if (!noCommit)
185 						repo.writeCherryPickHead(srcCommit.getId());
186 					repo.writeMergeCommitMsg(message);
187 
188 					return CherryPickResult.CONFLICT;
189 				}
190 			}
191 		} catch (IOException e) {
192 			throw new JGitInternalException(
193 					MessageFormat.format(
194 							JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand,
195 							e), e);
196 		}
197 		return new CherryPickResult(newHead, cherryPickedRefs);
198 	}
199 
200 	private RevCommit getParentCommit(RevCommit srcCommit, RevWalk revWalk)
201 			throws MultipleParentsNotAllowedException, MissingObjectException,
202 			IOException {
203 		final RevCommit srcParent;
204 		if (mainlineParentNumber == null) {
205 			if (srcCommit.getParentCount() != 1)
206 				throw new MultipleParentsNotAllowedException(
207 						MessageFormat.format(
208 								JGitText.get().canOnlyCherryPickCommitsWithOneParent,
209 								srcCommit.name(),
210 								Integer.valueOf(srcCommit.getParentCount())));
211 			srcParent = srcCommit.getParent(0);
212 		} else {
213 			if (mainlineParentNumber.intValue() > srcCommit.getParentCount())
214 				throw new JGitInternalException(MessageFormat.format(
215 						JGitText.get().commitDoesNotHaveGivenParent, srcCommit,
216 						mainlineParentNumber));
217 			srcParent = srcCommit
218 					.getParent(mainlineParentNumber.intValue() - 1);
219 		}
220 
221 		revWalk.parseHeaders(srcParent);
222 		return srcParent;
223 	}
224 
225 	/**
226 	 * @param commit
227 	 *            a reference to a commit which is cherry-picked to the current
228 	 *            head
229 	 * @return {@code this}
230 	 */
231 	public CherryPickCommand include(Ref commit) {
232 		checkCallable();
233 		commits.add(commit);
234 		return this;
235 	}
236 
237 	/**
238 	 * @param commit
239 	 *            the Id of a commit which is cherry-picked to the current head
240 	 * @return {@code this}
241 	 */
242 	public CherryPickCommand include(AnyObjectId commit) {
243 		return include(commit.getName(), commit);
244 	}
245 
246 	/**
247 	 * @param name
248 	 *            a name given to the commit
249 	 * @param commit
250 	 *            the Id of a commit which is cherry-picked to the current head
251 	 * @return {@code this}
252 	 */
253 	public CherryPickCommand include(String name, AnyObjectId commit) {
254 		return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
255 				commit.copy()));
256 	}
257 
258 	/**
259 	 * @param ourCommitName
260 	 *            the name that should be used in the "OURS" place for conflict
261 	 *            markers
262 	 * @return {@code this}
263 	 */
264 	public CherryPickCommand setOurCommitName(String ourCommitName) {
265 		this.ourCommitName = ourCommitName;
266 		return this;
267 	}
268 
269 	/**
270 	 * Set the prefix to use in the reflog.
271 	 * <p>
272 	 * This is primarily needed for implementing rebase in terms of
273 	 * cherry-picking
274 	 *
275 	 * @param prefix
276 	 *            including ":"
277 	 * @return {@code this}
278 	 * @since 3.1
279 	 */
280 	public CherryPickCommand setReflogPrefix(final String prefix) {
281 		this.reflogPrefix = prefix;
282 		return this;
283 	}
284 
285 	/**
286 	 * @param strategy
287 	 *            The merge strategy to use during this Cherry-pick.
288 	 * @return {@code this}
289 	 * @since 3.4
290 	 */
291 	public CherryPickCommand setStrategy(MergeStrategy strategy) {
292 		this.strategy = strategy;
293 		return this;
294 	}
295 
296 	/**
297 	 * @param mainlineParentNumber
298 	 *            the (1-based) parent number to diff against. This allows
299 	 *            cherry-picking of merges.
300 	 * @return {@code this}
301 	 * @since 3.4
302 	 */
303 	public CherryPickCommand setMainlineParentNumber(int mainlineParentNumber) {
304 		this.mainlineParentNumber = Integer.valueOf(mainlineParentNumber);
305 		return this;
306 	}
307 
308 	/**
309 	 * Allows cherry-picking changes without committing them.
310 	 * <p>
311 	 * NOTE: The behavior of cherry-pick is undefined if you pick multiple
312 	 * commits or if HEAD does not match the index state before cherry-picking.
313 	 *
314 	 * @param noCommit
315 	 *            true to cherry-pick without committing, false to commit after
316 	 *            each pick (default)
317 	 * @return {@code this}
318 	 * @since 3.5
319 	 */
320 	public CherryPickCommand setNoCommit(boolean noCommit) {
321 		this.noCommit = noCommit;
322 		return this;
323 	}
324 
325 	private String calculateOurName(Ref headRef) {
326 		if (ourCommitName != null)
327 			return ourCommitName;
328 
329 		String targetRefName = headRef.getTarget().getName();
330 		String headName = Repository.shortenRefName(targetRefName);
331 		return headName;
332 	}
333 }