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  import java.util.Map;
50  
51  import org.eclipse.jgit.api.MergeResult.MergeStatus;
52  import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
53  import org.eclipse.jgit.api.errors.GitAPIException;
54  import org.eclipse.jgit.api.errors.JGitInternalException;
55  import org.eclipse.jgit.api.errors.MultipleParentsNotAllowedException;
56  import org.eclipse.jgit.api.errors.NoHeadException;
57  import org.eclipse.jgit.api.errors.NoMessageException;
58  import org.eclipse.jgit.api.errors.UnmergedPathsException;
59  import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
60  import org.eclipse.jgit.dircache.DirCacheCheckout;
61  import org.eclipse.jgit.internal.JGitText;
62  import org.eclipse.jgit.lib.AnyObjectId;
63  import org.eclipse.jgit.lib.Constants;
64  import org.eclipse.jgit.lib.NullProgressMonitor;
65  import org.eclipse.jgit.lib.ObjectId;
66  import org.eclipse.jgit.lib.ObjectIdRef;
67  import org.eclipse.jgit.lib.ProgressMonitor;
68  import org.eclipse.jgit.lib.Ref;
69  import org.eclipse.jgit.lib.Ref.Storage;
70  import org.eclipse.jgit.lib.Repository;
71  import org.eclipse.jgit.merge.MergeMessageFormatter;
72  import org.eclipse.jgit.merge.MergeStrategy;
73  import org.eclipse.jgit.merge.ResolveMerger;
74  import org.eclipse.jgit.merge.ResolveMerger.MergeFailureReason;
75  import org.eclipse.jgit.revwalk.RevCommit;
76  import org.eclipse.jgit.revwalk.RevWalk;
77  import org.eclipse.jgit.treewalk.FileTreeIterator;
78  
79  /**
80   * A class used to execute a {@code revert} command. It has setters for all
81   * supported options and arguments of this command and a {@link #call()} method
82   * to finally execute the command. Each instance of this class should only be
83   * used for one invocation of the command (means: one call to {@link #call()})
84   *
85   * @see <a
86   *      href="http://www.kernel.org/pub/software/scm/git/docs/git-revert.html"
87   *      >Git documentation about revert</a>
88   */
89  public class RevertCommand extends GitCommand<RevCommit> {
90  	private List<Ref> commits = new LinkedList<>();
91  
92  	private String ourCommitName = null;
93  
94  	private List<Ref> revertedRefs = new LinkedList<>();
95  
96  	private MergeResult failingResult;
97  
98  	private List<String> unmergedPaths;
99  
100 	private MergeStrategy strategy = MergeStrategy.RECURSIVE;
101 
102 	private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
103 
104 	/**
105 	 * <p>
106 	 * Constructor for RevertCommand.
107 	 * </p>
108 	 *
109 	 * @param repo
110 	 *            the {@link org.eclipse.jgit.lib.Repository}
111 	 */
112 	protected RevertCommand(Repository repo) {
113 		super(repo);
114 	}
115 
116 	/**
117 	 * {@inheritDoc}
118 	 * <p>
119 	 * Executes the {@code revert} command with all the options and parameters
120 	 * collected by the setter methods (e.g. {@link #include(Ref)} of this
121 	 * class. Each instance of this class should only be used for one invocation
122 	 * of the command. Don't call this method twice on an instance.
123 	 */
124 	@Override
125 	public RevCommit call() throws NoMessageException, UnmergedPathsException,
126 			ConcurrentRefUpdateException, WrongRepositoryStateException,
127 			GitAPIException {
128 		RevCommit newHead = null;
129 		checkCallable();
130 
131 		try (RevWalk revWalk = new RevWalk(repo)) {
132 
133 			// get the head commit
134 			Ref headRef = repo.exactRef(Constants.HEAD);
135 			if (headRef == null)
136 				throw new NoHeadException(
137 						JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
138 			RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId());
139 
140 			newHead = headCommit;
141 
142 			// loop through all refs to be reverted
143 			for (Ref src : commits) {
144 				// get the commit to be reverted
145 				// handle annotated tags
146 				ObjectId srcObjectId = src.getPeeledObjectId();
147 				if (srcObjectId == null)
148 					srcObjectId = src.getObjectId();
149 				RevCommit srcCommit = revWalk.parseCommit(srcObjectId);
150 
151 				// get the parent of the commit to revert
152 				if (srcCommit.getParentCount() != 1)
153 					throw new MultipleParentsNotAllowedException(
154 							MessageFormat.format(
155 									JGitText.get().canOnlyRevertCommitsWithOneParent,
156 									srcCommit.name(),
157 									Integer.valueOf(srcCommit.getParentCount())));
158 
159 				RevCommit srcParent = srcCommit.getParent(0);
160 				revWalk.parseHeaders(srcParent);
161 
162 				String ourName = calculateOurName(headRef);
163 				String revertName = srcCommit.getId().abbreviate(7).name()
164 						+ " " + srcCommit.getShortMessage(); //$NON-NLS-1$
165 
166 				ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
167 				merger.setWorkingTreeIterator(new FileTreeIterator(repo));
168 				merger.setBase(srcCommit.getTree());
169 				merger.setCommitNames(new String[] {
170 						"BASE", ourName, revertName }); //$NON-NLS-1$
171 
172 				String shortMessage = "Revert \"" + srcCommit.getShortMessage() //$NON-NLS-1$
173 						+ "\""; //$NON-NLS-1$
174 				String newMessage = shortMessage + "\n\n" //$NON-NLS-1$
175 						+ "This reverts commit " + srcCommit.getId().getName() //$NON-NLS-1$
176 						+ ".\n"; //$NON-NLS-1$
177 				if (merger.merge(headCommit, srcParent)) {
178 					if (AnyObjectId.equals(headCommit.getTree().getId(), merger
179 							.getResultTreeId()))
180 						continue;
181 					DirCacheCheckout dco = new DirCacheCheckout(repo,
182 							headCommit.getTree(), repo.lockDirCache(),
183 							merger.getResultTreeId());
184 					dco.setFailOnConflict(true);
185 					dco.setProgressMonitor(monitor);
186 					dco.checkout();
187 					try (Git git = new Git(getRepository())) {
188 						newHead = git.commit().setMessage(newMessage)
189 								.setReflogComment("revert: " + shortMessage) //$NON-NLS-1$
190 								.call();
191 					}
192 					revertedRefs.add(src);
193 					headCommit = newHead;
194 				} else {
195 					unmergedPaths = merger.getUnmergedPaths();
196 					Map<String, MergeFailureReason> failingPaths = merger
197 							.getFailingPaths();
198 					if (failingPaths != null)
199 						failingResult = new MergeResult(null,
200 								merger.getBaseCommitId(),
201 								new ObjectId[] { headCommit.getId(),
202 										srcParent.getId() },
203 								MergeStatus.FAILED, strategy,
204 								merger.getMergeResults(), failingPaths, null);
205 					else
206 						failingResult = new MergeResult(null,
207 								merger.getBaseCommitId(),
208 								new ObjectId[] { headCommit.getId(),
209 										srcParent.getId() },
210 								MergeStatus.CONFLICTING, strategy,
211 								merger.getMergeResults(), failingPaths, null);
212 					if (!merger.failed() && !unmergedPaths.isEmpty()) {
213 						String message = new MergeMessageFormatter()
214 						.formatWithConflicts(newMessage,
215 								merger.getUnmergedPaths());
216 						repo.writeRevertHead(srcCommit.getId());
217 						repo.writeMergeCommitMsg(message);
218 					}
219 					return null;
220 				}
221 			}
222 		} catch (IOException e) {
223 			throw new JGitInternalException(
224 					MessageFormat.format(
225 									JGitText.get().exceptionCaughtDuringExecutionOfRevertCommand,
226 							e), e);
227 		}
228 		return newHead;
229 	}
230 
231 	/**
232 	 * Include a {@code Ref} to a commit to be reverted
233 	 *
234 	 * @param commit
235 	 *            a reference to a commit to be reverted into the current head
236 	 * @return {@code this}
237 	 */
238 	public RevertCommand include(Ref commit) {
239 		checkCallable();
240 		commits.add(commit);
241 		return this;
242 	}
243 
244 	/**
245 	 * Include a commit to be reverted
246 	 *
247 	 * @param commit
248 	 *            the Id of a commit to be reverted into the current head
249 	 * @return {@code this}
250 	 */
251 	public RevertCommand include(AnyObjectId commit) {
252 		return include(commit.getName(), commit);
253 	}
254 
255 	/**
256 	 * Include a commit to be reverted
257 	 *
258 	 * @param name
259 	 *            name of a {@code Ref} referring to the commit
260 	 * @param commit
261 	 *            the Id of a commit which is reverted into the current head
262 	 * @return {@code this}
263 	 */
264 	public RevertCommand include(String name, AnyObjectId commit) {
265 		return include(new ObjectIdRef.Unpeeled(Storage.LOOSE, name,
266 				commit.copy()));
267 	}
268 
269 	/**
270 	 * Set the name to be used in the "OURS" place for conflict markers
271 	 *
272 	 * @param ourCommitName
273 	 *            the name that should be used in the "OURS" place for conflict
274 	 *            markers
275 	 * @return {@code this}
276 	 */
277 	public RevertCommand setOurCommitName(String ourCommitName) {
278 		this.ourCommitName = ourCommitName;
279 		return this;
280 	}
281 
282 	private String calculateOurName(Ref headRef) {
283 		if (ourCommitName != null)
284 			return ourCommitName;
285 
286 		String targetRefName = headRef.getTarget().getName();
287 		String headName = Repository.shortenRefName(targetRefName);
288 		return headName;
289 	}
290 
291 	/**
292 	 * Get the list of successfully reverted {@link org.eclipse.jgit.lib.Ref}'s.
293 	 *
294 	 * @return the list of successfully reverted
295 	 *         {@link org.eclipse.jgit.lib.Ref}'s. Never <code>null</code> but
296 	 *         maybe an empty list if no commit was successfully cherry-picked
297 	 */
298 	public List<Ref> getRevertedRefs() {
299 		return revertedRefs;
300 	}
301 
302 	/**
303 	 * Get the result of a merge failure
304 	 *
305 	 * @return the result of a merge failure, <code>null</code> if no merge
306 	 *         failure occurred during the revert
307 	 */
308 	public MergeResult getFailingResult() {
309 		return failingResult;
310 	}
311 
312 	/**
313 	 * Get unmerged paths
314 	 *
315 	 * @return the unmerged paths, will be null if no merge conflicts
316 	 */
317 	public List<String> getUnmergedPaths() {
318 		return unmergedPaths;
319 	}
320 
321 	/**
322 	 * Set the merge strategy to use for this revert command
323 	 *
324 	 * @param strategy
325 	 *            The merge strategy to use for this revert command.
326 	 * @return {@code this}
327 	 * @since 3.4
328 	 */
329 	public RevertCommand setStrategy(MergeStrategy strategy) {
330 		this.strategy = strategy;
331 		return this;
332 	}
333 
334 	/**
335 	 * The progress monitor associated with the revert operation. By default,
336 	 * this is set to <code>NullProgressMonitor</code>
337 	 *
338 	 * @see NullProgressMonitor
339 	 * @param monitor
340 	 *            a {@link org.eclipse.jgit.lib.ProgressMonitor}
341 	 * @return {@code this}
342 	 * @since 4.11
343 	 */
344 	public RevertCommand setProgressMonitor(ProgressMonitor monitor) {
345 		if (monitor == null) {
346 			monitor = NullProgressMonitor.INSTANCE;
347 		}
348 		this.monitor = monitor;
349 		return this;
350 	}
351 }