View Javadoc
1   /*
2    * Copyright (C) 2012, 2017 GitHub Inc.
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.HashSet;
48  import java.util.List;
49  import java.util.Set;
50  
51  import org.eclipse.jgit.api.errors.GitAPIException;
52  import org.eclipse.jgit.api.errors.InvalidRefNameException;
53  import org.eclipse.jgit.api.errors.JGitInternalException;
54  import org.eclipse.jgit.api.errors.NoHeadException;
55  import org.eclipse.jgit.api.errors.StashApplyFailureException;
56  import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
57  import org.eclipse.jgit.dircache.DirCache;
58  import org.eclipse.jgit.dircache.DirCacheBuilder;
59  import org.eclipse.jgit.dircache.DirCacheCheckout;
60  import org.eclipse.jgit.dircache.DirCacheCheckout.CheckoutMetadata;
61  import org.eclipse.jgit.dircache.DirCacheEntry;
62  import org.eclipse.jgit.dircache.DirCacheIterator;
63  import org.eclipse.jgit.errors.CheckoutConflictException;
64  import org.eclipse.jgit.events.WorkingTreeModifiedEvent;
65  import org.eclipse.jgit.internal.JGitText;
66  import org.eclipse.jgit.lib.Constants;
67  import org.eclipse.jgit.lib.CoreConfig.EolStreamType;
68  import org.eclipse.jgit.lib.ObjectId;
69  import org.eclipse.jgit.lib.ObjectReader;
70  import org.eclipse.jgit.lib.Repository;
71  import org.eclipse.jgit.lib.RepositoryState;
72  import org.eclipse.jgit.merge.MergeStrategy;
73  import org.eclipse.jgit.merge.ResolveMerger;
74  import org.eclipse.jgit.revwalk.RevCommit;
75  import org.eclipse.jgit.revwalk.RevTree;
76  import org.eclipse.jgit.revwalk.RevWalk;
77  import org.eclipse.jgit.treewalk.AbstractTreeIterator;
78  import org.eclipse.jgit.treewalk.FileTreeIterator;
79  import org.eclipse.jgit.treewalk.TreeWalk;
80  
81  /**
82   * Command class to apply a stashed commit.
83   *
84   * This class behaves like <em>git stash apply --index</em>, i.e. it tries to
85   * recover the stashed index state in addition to the working tree state.
86   *
87   * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-stash.html"
88   *      >Git documentation about Stash</a>
89   *
90   * @since 2.0
91   */
92  public class StashApplyCommand extends GitCommand<ObjectId> {
93  
94  	private static final String DEFAULT_REF = Constants.STASH + "@{0}"; //$NON-NLS-1$
95  
96  	private String stashRef;
97  
98  	private boolean applyIndex = true;
99  
100 	private boolean applyUntracked = true;
101 
102 	private boolean ignoreRepositoryState;
103 
104 	private MergeStrategy strategy = MergeStrategy.RECURSIVE;
105 
106 	/**
107 	 * Create command to apply the changes of a stashed commit
108 	 *
109 	 * @param repo
110 	 */
111 	public StashApplyCommand(final Repository repo) {
112 		super(repo);
113 	}
114 
115 	/**
116 	 * Set the stash reference to apply
117 	 * <p>
118 	 * This will default to apply the latest stashed commit (stash@{0}) if
119 	 * unspecified
120 	 *
121 	 * @param stashRef
122 	 * @return {@code this}
123 	 */
124 	public StashApplyCommand setStashRef(final String stashRef) {
125 		this.stashRef = stashRef;
126 		return this;
127 	}
128 
129 	/**
130 	 * @param willIgnoreRepositoryState
131 	 * @return {@code this}
132 	 * @since 3.2
133 	 */
134 	public StashApplyCommand ignoreRepositoryState(boolean willIgnoreRepositoryState) {
135 		this.ignoreRepositoryState = willIgnoreRepositoryState;
136 		return this;
137 	}
138 
139 	private ObjectId getStashId() throws GitAPIException {
140 		final String revision = stashRef != null ? stashRef : DEFAULT_REF;
141 		final ObjectId stashId;
142 		try {
143 			stashId = repo.resolve(revision);
144 		} catch (IOException e) {
145 			throw new InvalidRefNameException(MessageFormat.format(
146 					JGitText.get().stashResolveFailed, revision), e);
147 		}
148 		if (stashId == null)
149 			throw new InvalidRefNameException(MessageFormat.format(
150 					JGitText.get().stashResolveFailed, revision));
151 		return stashId;
152 	}
153 
154 	/**
155 	 * Apply the changes in a stashed commit to the working directory and index
156 	 *
157 	 * @return id of stashed commit that was applied TODO: Does anyone depend on
158 	 *         this, or could we make it more like Merge/CherryPick/Revert?
159 	 * @throws GitAPIException
160 	 * @throws WrongRepositoryStateException
161 	 * @throws NoHeadException
162 	 * @throws StashApplyFailureException
163 	 */
164 	@Override
165 	public ObjectId call() throws GitAPIException,
166 			WrongRepositoryStateException, NoHeadException,
167 			StashApplyFailureException {
168 		checkCallable();
169 
170 		if (!ignoreRepositoryState
171 				&& repo.getRepositoryState() != RepositoryState.SAFE)
172 			throw new WrongRepositoryStateException(MessageFormat.format(
173 					JGitText.get().stashApplyOnUnsafeRepository,
174 					repo.getRepositoryState()));
175 
176 		try (ObjectReader reader = repo.newObjectReader();
177 				RevWalk revWalk = new RevWalk(reader)) {
178 
179 			ObjectId headCommit = repo.resolve(Constants.HEAD);
180 			if (headCommit == null)
181 				throw new NoHeadException(JGitText.get().stashApplyWithoutHead);
182 
183 			final ObjectId stashId = getStashId();
184 			RevCommit stashCommit = revWalk.parseCommit(stashId);
185 			if (stashCommit.getParentCount() < 2
186 					|| stashCommit.getParentCount() > 3)
187 				throw new JGitInternalException(MessageFormat.format(
188 						JGitText.get().stashCommitIncorrectNumberOfParents,
189 						stashId.name(),
190 						Integer.valueOf(stashCommit.getParentCount())));
191 
192 			ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
193 			ObjectId stashIndexCommit = revWalk.parseCommit(stashCommit
194 					.getParent(1));
195 			ObjectId stashHeadCommit = stashCommit.getParent(0);
196 			ObjectId untrackedCommit = null;
197 			if (applyUntracked && stashCommit.getParentCount() == 3)
198 				untrackedCommit = revWalk.parseCommit(stashCommit.getParent(2));
199 
200 			ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
201 			merger.setCommitNames(new String[] { "stashed HEAD", "HEAD", //$NON-NLS-1$ //$NON-NLS-2$
202 					"stash" }); //$NON-NLS-1$
203 			merger.setBase(stashHeadCommit);
204 			merger.setWorkingTreeIterator(new FileTreeIterator(repo));
205 			boolean mergeSucceeded = merger.merge(headCommit, stashCommit);
206 			List<String> modifiedByMerge = merger.getModifiedFiles();
207 			if (!modifiedByMerge.isEmpty()) {
208 				repo.fireEvent(
209 						new WorkingTreeModifiedEvent(modifiedByMerge, null));
210 			}
211 			if (mergeSucceeded) {
212 				DirCache dc = repo.lockDirCache();
213 				DirCacheCheckout dco = new DirCacheCheckout(repo, headTree,
214 						dc, merger.getResultTreeId());
215 				dco.setFailOnConflict(true);
216 				dco.checkout(); // Ignoring failed deletes....
217 				if (applyIndex) {
218 					ResolveMerger ixMerger = (ResolveMerger) strategy
219 							.newMerger(repo, true);
220 					ixMerger.setCommitNames(new String[] { "stashed HEAD", //$NON-NLS-1$
221 							"HEAD", "stashed index" }); //$NON-NLS-1$//$NON-NLS-2$
222 					ixMerger.setBase(stashHeadCommit);
223 					boolean ok = ixMerger.merge(headCommit, stashIndexCommit);
224 					if (ok) {
225 						resetIndex(revWalk
226 								.parseTree(ixMerger.getResultTreeId()));
227 					} else {
228 						throw new StashApplyFailureException(
229 								JGitText.get().stashApplyConflict);
230 					}
231 				}
232 
233 				if (untrackedCommit != null) {
234 					ResolveMerger untrackedMerger = (ResolveMerger) strategy
235 							.newMerger(repo, true);
236 					untrackedMerger.setCommitNames(new String[] {
237 							"null", "HEAD", "untracked files" }); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
238 					// There is no common base for HEAD & untracked files
239 					// because the commit for untracked files has no parent. If
240 					// we use stashHeadCommit as common base (as in the other
241 					// merges) we potentially report conflicts for files
242 					// which are not even member of untracked files commit
243 					untrackedMerger.setBase(null);
244 					boolean ok = untrackedMerger.merge(headCommit,
245 							untrackedCommit);
246 					if (ok) {
247 						try {
248 							RevTree untrackedTree = revWalk
249 									.parseTree(untrackedCommit);
250 							resetUntracked(untrackedTree);
251 						} catch (CheckoutConflictException e) {
252 							throw new StashApplyFailureException(
253 									JGitText.get().stashApplyConflict, e);
254 						}
255 					} else {
256 						throw new StashApplyFailureException(
257 								JGitText.get().stashApplyConflict);
258 					}
259 				}
260 			} else {
261 				throw new StashApplyFailureException(
262 						JGitText.get().stashApplyConflict);
263 			}
264 			return stashId;
265 
266 		} catch (JGitInternalException e) {
267 			throw e;
268 		} catch (IOException e) {
269 			throw new JGitInternalException(JGitText.get().stashApplyFailed, e);
270 		}
271 	}
272 
273 	/**
274 	 * @param applyIndex
275 	 *            true (default) if the command should restore the index state
276 	 */
277 	public void setApplyIndex(boolean applyIndex) {
278 		this.applyIndex = applyIndex;
279 	}
280 
281 	/**
282 	 * @param strategy
283 	 *            The merge strategy to use in order to merge during this
284 	 *            command execution.
285 	 * @return {@code this}
286 	 * @since 3.4
287 	 */
288 	public StashApplyCommand setStrategy(MergeStrategy strategy) {
289 		this.strategy = strategy;
290 		return this;
291 	}
292 
293 	/**
294 	 * @param applyUntracked
295 	 *            true (default) if the command should restore untracked files
296 	 * @since 3.4
297 	 */
298 	public void setApplyUntracked(boolean applyUntracked) {
299 		this.applyUntracked = applyUntracked;
300 	}
301 
302 	private void resetIndex(RevTree tree) throws IOException {
303 		DirCache dc = repo.lockDirCache();
304 		try (TreeWalk walk = new TreeWalk(repo)) {
305 			DirCacheBuilder builder = dc.builder();
306 
307 			walk.addTree(tree);
308 			walk.addTree(new DirCacheIterator(dc));
309 			walk.setRecursive(true);
310 
311 			while (walk.next()) {
312 				AbstractTreeIterator cIter = walk.getTree(0,
313 						AbstractTreeIterator.class);
314 				if (cIter == null) {
315 					// Not in commit, don't add to new index
316 					continue;
317 				}
318 
319 				final DirCacheEntry entry = new DirCacheEntry(walk.getRawPath());
320 				entry.setFileMode(cIter.getEntryFileMode());
321 				entry.setObjectIdFromRaw(cIter.idBuffer(), cIter.idOffset());
322 
323 				DirCacheIterator dcIter = walk.getTree(1,
324 						DirCacheIterator.class);
325 				if (dcIter != null && dcIter.idEqual(cIter)) {
326 					DirCacheEntry indexEntry = dcIter.getDirCacheEntry();
327 					entry.setLastModified(indexEntry.getLastModified());
328 					entry.setLength(indexEntry.getLength());
329 				}
330 
331 				builder.add(entry);
332 			}
333 
334 			builder.commit();
335 		} finally {
336 			dc.unlock();
337 		}
338 	}
339 
340 	private void resetUntracked(RevTree tree) throws CheckoutConflictException,
341 			IOException {
342 		Set<String> actuallyModifiedPaths = new HashSet<>();
343 		// TODO maybe NameConflictTreeWalk ?
344 		try (TreeWalk walk = new TreeWalk(repo)) {
345 			walk.addTree(tree);
346 			walk.addTree(new FileTreeIterator(repo));
347 			walk.setRecursive(true);
348 
349 			final ObjectReader reader = walk.getObjectReader();
350 
351 			while (walk.next()) {
352 				final AbstractTreeIterator cIter = walk.getTree(0,
353 						AbstractTreeIterator.class);
354 				if (cIter == null)
355 					// Not in commit, don't create untracked
356 					continue;
357 
358 				final EolStreamType eolStreamType = walk.getEolStreamType();
359 				final DirCacheEntry entry = new DirCacheEntry(walk.getRawPath());
360 				entry.setFileMode(cIter.getEntryFileMode());
361 				entry.setObjectIdFromRaw(cIter.idBuffer(), cIter.idOffset());
362 
363 				FileTreeIterator fIter = walk
364 						.getTree(1, FileTreeIterator.class);
365 				if (fIter != null) {
366 					if (fIter.isModified(entry, true, reader)) {
367 						// file exists and is dirty
368 						throw new CheckoutConflictException(
369 								entry.getPathString());
370 					}
371 				}
372 
373 				checkoutPath(entry, reader,
374 						new CheckoutMetadata(eolStreamType, null));
375 				actuallyModifiedPaths.add(entry.getPathString());
376 			}
377 		} finally {
378 			if (!actuallyModifiedPaths.isEmpty()) {
379 				repo.fireEvent(new WorkingTreeModifiedEvent(
380 						actuallyModifiedPaths, null));
381 			}
382 		}
383 	}
384 
385 	private void checkoutPath(DirCacheEntry entry, ObjectReader reader,
386 			CheckoutMetadata checkoutMetadata) {
387 		try {
388 			DirCacheCheckout.checkoutEntry(repo, entry, reader, true,
389 					checkoutMetadata);
390 		} catch (IOException e) {
391 			throw new JGitInternalException(MessageFormat.format(
392 					JGitText.get().checkoutConflictWithFile,
393 					entry.getPathString()), e);
394 		}
395 	}
396 }