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.NullProgressMonitor;
64  import org.eclipse.jgit.lib.ObjectId;
65  import org.eclipse.jgit.lib.ObjectIdRef;
66  import org.eclipse.jgit.lib.ProgressMonitor;
67  import org.eclipse.jgit.lib.Ref;
68  import org.eclipse.jgit.lib.Ref.Storage;
69  import org.eclipse.jgit.lib.Repository;
70  import org.eclipse.jgit.merge.MergeMessageFormatter;
71  import org.eclipse.jgit.merge.MergeStrategy;
72  import org.eclipse.jgit.merge.ResolveMerger;
73  import org.eclipse.jgit.revwalk.RevCommit;
74  import org.eclipse.jgit.revwalk.RevWalk;
75  import org.eclipse.jgit.treewalk.FileTreeIterator;
76  
77  /**
78   * A class used to execute a {@code cherry-pick} command. It has setters for all
79   * supported options and arguments of this command and a {@link #call()} method
80   * to finally execute the command. Each instance of this class should only be
81   * used for one invocation of the command (means: one call to {@link #call()})
82   *
83   * @see <a
84   *      href="http://www.kernel.org/pub/software/scm/git/docs/git-cherry-pick.html"
85   *      >Git documentation about cherry-pick</a>
86   */
87  public class CherryPickCommand extends GitCommand<CherryPickResult> {
88  	private String reflogPrefix = "cherry-pick:"; //$NON-NLS-1$
89  
90  	private List<Ref> commits = new LinkedList<>();
91  
92  	private String ourCommitName = null;
93  
94  	private MergeStrategy strategy = MergeStrategy.RECURSIVE;
95  
96  	private Integer mainlineParentNumber;
97  
98  	private boolean noCommit = false;
99  
100 	private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
101 
102 	/**
103 	 * Constructor for CherryPickCommand
104 	 *
105 	 * @param repo
106 	 *            the {@link org.eclipse.jgit.lib.Repository}
107 	 */
108 	protected CherryPickCommand(Repository repo) {
109 		super(repo);
110 	}
111 
112 	/**
113 	 * {@inheritDoc}
114 	 * <p>
115 	 * Executes the {@code Cherry-Pick} command with all the options and
116 	 * parameters collected by the setter methods (e.g. {@link #include(Ref)} of
117 	 * this class. Each instance of this class should only be used for one
118 	 * invocation of the command. Don't call this method twice on an instance.
119 	 */
120 	@Override
121 	public CherryPickResult call() throws GitAPIException, NoMessageException,
122 			UnmergedPathsException, ConcurrentRefUpdateException,
123 			WrongRepositoryStateException, NoHeadException {
124 		RevCommit newHead = null;
125 		List<Ref> cherryPickedRefs = new LinkedList<>();
126 		checkCallable();
127 
128 		try (RevWalklk.html#RevWalk">RevWalk revWalk = new RevWalk(repo)) {
129 
130 			// get the head commit
131 			Ref headRef = repo.exactRef(Constants.HEAD);
132 			if (headRef == null)
133 				throw new NoHeadException(
134 						JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
135 
136 			newHead = revWalk.parseCommit(headRef.getObjectId());
137 
138 			// loop through all refs to be cherry-picked
139 			for (Ref src : commits) {
140 				// get the commit to be cherry-picked
141 				// handle annotated tags
142 				ObjectId srcObjectId = src.getPeeledObjectId();
143 				if (srcObjectId == null)
144 					srcObjectId = src.getObjectId();
145 				RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
146 
147 				// get the parent of the commit to cherry-pick
148 				final RevCommit srcParent = getParentCommit(srcCommit, revWalk);
149 
150 				String ourName = calculateOurName(headRef);
151 				String cherryPickName = srcCommit.getId().abbreviate(7).name()
152 						+ " " + srcCommit.getShortMessage(); //$NON-NLS-1$
153 
154 				ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
155 				merger.setWorkingTreeIterator(new FileTreeIterator(repo));
156 				merger.setBase(srcParent.getTree());
157 				merger.setCommitNames(new String[] { "BASE", ourName, //$NON-NLS-1$
158 						cherryPickName });
159 				if (merger.merge(newHead, srcCommit)) {
160 					if (AnyObjectId.isEqual(newHead.getTree().getId(),
161 							merger.getResultTreeId()))
162 						continue;
163 					DirCacheCheckout dco = new DirCacheCheckout(repo,
164 							newHead.getTree(), repo.lockDirCache(),
165 							merger.getResultTreeId());
166 					dco.setFailOnConflict(true);
167 					dco.setProgressMonitor(monitor);
168 					dco.checkout();
169 					if (!noCommit)
170 						newHead = new Git(getRepository()).commit()
171 								.setMessage(srcCommit.getFullMessage())
172 								.setReflogComment(reflogPrefix + " " //$NON-NLS-1$
173 										+ srcCommit.getShortMessage())
174 								.setAuthor(srcCommit.getAuthorIdent())
175 								.setNoVerify(true).call();
176 					cherryPickedRefs.add(src);
177 				} else {
178 					if (merger.failed())
179 						return new CherryPickResult(merger.getFailingPaths());
180 
181 					// there are merge conflicts
182 
183 					String message = new MergeMessageFormatter()
184 							.formatWithConflicts(srcCommit.getFullMessage(),
185 									merger.getUnmergedPaths());
186 
187 					if (!noCommit)
188 						repo.writeCherryPickHead(srcCommit.getId());
189 					repo.writeMergeCommitMsg(message);
190 
191 					return CherryPickResult.CONFLICT;
192 				}
193 			}
194 		} catch (IOException e) {
195 			throw new JGitInternalException(
196 					MessageFormat.format(
197 							JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand,
198 							e), e);
199 		}
200 		return new CherryPickResult(newHead, cherryPickedRefs);
201 	}
202 
203 	private RevCommit../org/eclipse/jgit/revwalk/RevCommit.html#RevCommit">RevCommit getParentCommit(RevCommit srcCommit, RevWalk revWalk)
204 			throws MultipleParentsNotAllowedException, MissingObjectException,
205 			IOException {
206 		final RevCommit srcParent;
207 		if (mainlineParentNumber == null) {
208 			if (srcCommit.getParentCount() != 1)
209 				throw new MultipleParentsNotAllowedException(
210 						MessageFormat.format(
211 								JGitText.get().canOnlyCherryPickCommitsWithOneParent,
212 								srcCommit.name(),
213 								Integer.valueOf(srcCommit.getParentCount())));
214 			srcParent = srcCommit.getParent(0);
215 		} else {
216 			if (mainlineParentNumber.intValue() > srcCommit.getParentCount())
217 				throw new JGitInternalException(MessageFormat.format(
218 						JGitText.get().commitDoesNotHaveGivenParent, srcCommit,
219 						mainlineParentNumber));
220 			srcParent = srcCommit
221 					.getParent(mainlineParentNumber.intValue() - 1);
222 		}
223 
224 		revWalk.parseHeaders(srcParent);
225 		return srcParent;
226 	}
227 
228 	/**
229 	 * Include a reference to a commit
230 	 *
231 	 * @param commit
232 	 *            a reference to a commit which is cherry-picked to the current
233 	 *            head
234 	 * @return {@code this}
235 	 */
236 	public CherryPickCommand include(Ref commit) {
237 		checkCallable();
238 		commits.add(commit);
239 		return this;
240 	}
241 
242 	/**
243 	 * Include a commit
244 	 *
245 	 * @param commit
246 	 *            the Id of a commit which is cherry-picked to the current head
247 	 * @return {@code this}
248 	 */
249 	public CherryPickCommand include(AnyObjectId commit) {
250 		return include(commit.getName(), commit);
251 	}
252 
253 	/**
254 	 * Include a commit
255 	 *
256 	 * @param name
257 	 *            a name given to the commit
258 	 * @param commit
259 	 *            the Id of a commit which is cherry-picked to the current head
260 	 * @return {@code this}
261 	 */
262 	public CherryPickCommand include(String name, AnyObjectId commit) {
263 		return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
264 				commit.copy()));
265 	}
266 
267 	/**
268 	 * Set the name that should be used in the "OURS" place for conflict markers
269 	 *
270 	 * @param ourCommitName
271 	 *            the name that should be used in the "OURS" place for conflict
272 	 *            markers
273 	 * @return {@code this}
274 	 */
275 	public CherryPickCommand setOurCommitName(String ourCommitName) {
276 		this.ourCommitName = ourCommitName;
277 		return this;
278 	}
279 
280 	/**
281 	 * Set the prefix to use in the reflog.
282 	 * <p>
283 	 * This is primarily needed for implementing rebase in terms of
284 	 * cherry-picking
285 	 *
286 	 * @param prefix
287 	 *            including ":"
288 	 * @return {@code this}
289 	 * @since 3.1
290 	 */
291 	public CherryPickCommand setReflogPrefix(String prefix) {
292 		this.reflogPrefix = prefix;
293 		return this;
294 	}
295 
296 	/**
297 	 * Set the {@code MergeStrategy}
298 	 *
299 	 * @param strategy
300 	 *            The merge strategy to use during this Cherry-pick.
301 	 * @return {@code this}
302 	 * @since 3.4
303 	 */
304 	public CherryPickCommand setStrategy(MergeStrategy strategy) {
305 		this.strategy = strategy;
306 		return this;
307 	}
308 
309 	/**
310 	 * Set the (1-based) parent number to diff against
311 	 *
312 	 * @param mainlineParentNumber
313 	 *            the (1-based) parent number to diff against. This allows
314 	 *            cherry-picking of merges.
315 	 * @return {@code this}
316 	 * @since 3.4
317 	 */
318 	public CherryPickCommand setMainlineParentNumber(int mainlineParentNumber) {
319 		this.mainlineParentNumber = Integer.valueOf(mainlineParentNumber);
320 		return this;
321 	}
322 
323 	/**
324 	 * Allows cherry-picking changes without committing them.
325 	 * <p>
326 	 * NOTE: The behavior of cherry-pick is undefined if you pick multiple
327 	 * commits or if HEAD does not match the index state before cherry-picking.
328 	 *
329 	 * @param noCommit
330 	 *            true to cherry-pick without committing, false to commit after
331 	 *            each pick (default)
332 	 * @return {@code this}
333 	 * @since 3.5
334 	 */
335 	public CherryPickCommand setNoCommit(boolean noCommit) {
336 		this.noCommit = noCommit;
337 		return this;
338 	}
339 
340 	/**
341 	 * The progress monitor associated with the cherry-pick operation. By
342 	 * default, this is set to <code>NullProgressMonitor</code>
343 	 *
344 	 * @see NullProgressMonitor
345 	 * @param monitor
346 	 *            a {@link org.eclipse.jgit.lib.ProgressMonitor}
347 	 * @return {@code this}
348 	 * @since 4.11
349 	 */
350 	public CherryPickCommand setProgressMonitor(ProgressMonitor monitor) {
351 		if (monitor == null) {
352 			monitor = NullProgressMonitor.INSTANCE;
353 		}
354 		this.monitor = monitor;
355 		return this;
356 	}
357 
358 	private String calculateOurName(Ref headRef) {
359 		if (ourCommitName != null)
360 			return ourCommitName;
361 
362 		String targetRefName = headRef.getTarget().getName();
363 		String headName = Repository.shortenRefName(targetRefName);
364 		return headName;
365 	}
366 
367 	/** {@inheritDoc} */
368 	@SuppressWarnings("nls")
369 	@Override
370 	public String toString() {
371 		return "CherryPickCommand [repo=" + repo + ",\ncommits=" + commits
372 				+ ",\nmainlineParentNumber=" + mainlineParentNumber
373 				+ ", noCommit=" + noCommit + ", ourCommitName=" + ourCommitName
374 				+ ", reflogPrefix=" + reflogPrefix + ", strategy=" + strategy
375 				+ "]";
376 	}
377 
378 }