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<>();
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 	@Override
120 	public CherryPickResult call() throws GitAPIException, NoMessageException,
121 			UnmergedPathsException, ConcurrentRefUpdateException,
122 			WrongRepositoryStateException, NoHeadException {
123 		RevCommit newHead = null;
124 		List<Ref> cherryPickedRefs = new LinkedList<>();
125 		checkCallable();
126 
127 		try (RevWalk revWalk = new RevWalk(repo)) {
128 
129 			// get the head commit
130 			Ref headRef = repo.exactRef(Constants.HEAD);
131 			if (headRef == null)
132 				throw new NoHeadException(
133 						JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
134 
135 			newHead = revWalk.parseCommit(headRef.getObjectId());
136 
137 			// loop through all refs to be cherry-picked
138 			for (Ref src : commits) {
139 				// get the commit to be cherry-picked
140 				// handle annotated tags
141 				ObjectId srcObjectId = src.getPeeledObjectId();
142 				if (srcObjectId == null)
143 					srcObjectId = src.getObjectId();
144 				RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
145 
146 				// get the parent of the commit to cherry-pick
147 				final RevCommit srcParent = getParentCommit(srcCommit, revWalk);
148 
149 				String ourName = calculateOurName(headRef);
150 				String cherryPickName = srcCommit.getId().abbreviate(7).name()
151 						+ " " + srcCommit.getShortMessage(); //$NON-NLS-1$
152 
153 				ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
154 				merger.setWorkingTreeIterator(new FileTreeIterator(repo));
155 				merger.setBase(srcParent.getTree());
156 				merger.setCommitNames(new String[] { "BASE", ourName, //$NON-NLS-1$
157 						cherryPickName });
158 				if (merger.merge(newHead, srcCommit)) {
159 					if (AnyObjectId.equals(newHead.getTree().getId(), merger
160 							.getResultTreeId()))
161 						continue;
162 					DirCacheCheckout dco = new DirCacheCheckout(repo,
163 							newHead.getTree(), repo.lockDirCache(),
164 							merger.getResultTreeId());
165 					dco.setFailOnConflict(true);
166 					dco.checkout();
167 					if (!noCommit)
168 						newHead = new Git(getRepository()).commit()
169 								.setMessage(srcCommit.getFullMessage())
170 								.setReflogComment(reflogPrefix + " " //$NON-NLS-1$
171 										+ srcCommit.getShortMessage())
172 								.setAuthor(srcCommit.getAuthorIdent())
173 								.setNoVerify(true).call();
174 					cherryPickedRefs.add(src);
175 				} else {
176 					if (merger.failed())
177 						return new CherryPickResult(merger.getFailingPaths());
178 
179 					// there are merge conflicts
180 
181 					String message = new MergeMessageFormatter()
182 							.formatWithConflicts(srcCommit.getFullMessage(),
183 									merger.getUnmergedPaths());
184 
185 					if (!noCommit)
186 						repo.writeCherryPickHead(srcCommit.getId());
187 					repo.writeMergeCommitMsg(message);
188 
189 					return CherryPickResult.CONFLICT;
190 				}
191 			}
192 		} catch (IOException e) {
193 			throw new JGitInternalException(
194 					MessageFormat.format(
195 							JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand,
196 							e), e);
197 		}
198 		return new CherryPickResult(newHead, cherryPickedRefs);
199 	}
200 
201 	private RevCommit getParentCommit(RevCommit srcCommit, RevWalk revWalk)
202 			throws MultipleParentsNotAllowedException, MissingObjectException,
203 			IOException {
204 		final RevCommit srcParent;
205 		if (mainlineParentNumber == null) {
206 			if (srcCommit.getParentCount() != 1)
207 				throw new MultipleParentsNotAllowedException(
208 						MessageFormat.format(
209 								JGitText.get().canOnlyCherryPickCommitsWithOneParent,
210 								srcCommit.name(),
211 								Integer.valueOf(srcCommit.getParentCount())));
212 			srcParent = srcCommit.getParent(0);
213 		} else {
214 			if (mainlineParentNumber.intValue() > srcCommit.getParentCount())
215 				throw new JGitInternalException(MessageFormat.format(
216 						JGitText.get().commitDoesNotHaveGivenParent, srcCommit,
217 						mainlineParentNumber));
218 			srcParent = srcCommit
219 					.getParent(mainlineParentNumber.intValue() - 1);
220 		}
221 
222 		revWalk.parseHeaders(srcParent);
223 		return srcParent;
224 	}
225 
226 	/**
227 	 * @param commit
228 	 *            a reference to a commit which is cherry-picked to the current
229 	 *            head
230 	 * @return {@code this}
231 	 */
232 	public CherryPickCommand include(Ref commit) {
233 		checkCallable();
234 		commits.add(commit);
235 		return this;
236 	}
237 
238 	/**
239 	 * @param commit
240 	 *            the Id of a commit which is cherry-picked to the current head
241 	 * @return {@code this}
242 	 */
243 	public CherryPickCommand include(AnyObjectId commit) {
244 		return include(commit.getName(), commit);
245 	}
246 
247 	/**
248 	 * @param name
249 	 *            a name given to the commit
250 	 * @param commit
251 	 *            the Id of a commit which is cherry-picked to the current head
252 	 * @return {@code this}
253 	 */
254 	public CherryPickCommand include(String name, AnyObjectId commit) {
255 		return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
256 				commit.copy()));
257 	}
258 
259 	/**
260 	 * @param ourCommitName
261 	 *            the name that should be used in the "OURS" place for conflict
262 	 *            markers
263 	 * @return {@code this}
264 	 */
265 	public CherryPickCommand setOurCommitName(String ourCommitName) {
266 		this.ourCommitName = ourCommitName;
267 		return this;
268 	}
269 
270 	/**
271 	 * Set the prefix to use in the reflog.
272 	 * <p>
273 	 * This is primarily needed for implementing rebase in terms of
274 	 * cherry-picking
275 	 *
276 	 * @param prefix
277 	 *            including ":"
278 	 * @return {@code this}
279 	 * @since 3.1
280 	 */
281 	public CherryPickCommand setReflogPrefix(final String prefix) {
282 		this.reflogPrefix = prefix;
283 		return this;
284 	}
285 
286 	/**
287 	 * @param strategy
288 	 *            The merge strategy to use during this Cherry-pick.
289 	 * @return {@code this}
290 	 * @since 3.4
291 	 */
292 	public CherryPickCommand setStrategy(MergeStrategy strategy) {
293 		this.strategy = strategy;
294 		return this;
295 	}
296 
297 	/**
298 	 * @param mainlineParentNumber
299 	 *            the (1-based) parent number to diff against. This allows
300 	 *            cherry-picking of merges.
301 	 * @return {@code this}
302 	 * @since 3.4
303 	 */
304 	public CherryPickCommand setMainlineParentNumber(int mainlineParentNumber) {
305 		this.mainlineParentNumber = Integer.valueOf(mainlineParentNumber);
306 		return this;
307 	}
308 
309 	/**
310 	 * Allows cherry-picking changes without committing them.
311 	 * <p>
312 	 * NOTE: The behavior of cherry-pick is undefined if you pick multiple
313 	 * commits or if HEAD does not match the index state before cherry-picking.
314 	 *
315 	 * @param noCommit
316 	 *            true to cherry-pick without committing, false to commit after
317 	 *            each pick (default)
318 	 * @return {@code this}
319 	 * @since 3.5
320 	 */
321 	public CherryPickCommand setNoCommit(boolean noCommit) {
322 		this.noCommit = noCommit;
323 		return this;
324 	}
325 
326 	private String calculateOurName(Ref headRef) {
327 		if (ourCommitName != null)
328 			return ourCommitName;
329 
330 		String targetRefName = headRef.getTarget().getName();
331 		String headName = Repository.shortenRefName(targetRefName);
332 		return headName;
333 	}
334 
335 	@SuppressWarnings("nls")
336 	@Override
337 	public String toString() {
338 		return "CherryPickCommand [repo=" + repo + ",\ncommits=" + commits
339 				+ ",\nmainlineParentNumber=" + mainlineParentNumber
340 				+ ", noCommit=" + noCommit + ", ourCommitName=" + ourCommitName
341 				+ ", reflogPrefix=" + reflogPrefix + ", strategy=" + strategy
342 				+ "]";
343 	}
344 
345 }