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