You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StashApplyCommand.java 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. import java.io.IOException;
  45. import java.text.MessageFormat;
  46. import org.eclipse.jgit.api.errors.GitAPIException;
  47. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  48. import org.eclipse.jgit.api.errors.JGitInternalException;
  49. import org.eclipse.jgit.api.errors.NoHeadException;
  50. import org.eclipse.jgit.api.errors.StashApplyFailureException;
  51. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  52. import org.eclipse.jgit.dircache.DirCache;
  53. import org.eclipse.jgit.dircache.DirCacheBuilder;
  54. import org.eclipse.jgit.dircache.DirCacheCheckout;
  55. import org.eclipse.jgit.dircache.DirCacheEntry;
  56. import org.eclipse.jgit.dircache.DirCacheIterator;
  57. import org.eclipse.jgit.internal.JGitText;
  58. import org.eclipse.jgit.lib.Constants;
  59. import org.eclipse.jgit.lib.ObjectId;
  60. import org.eclipse.jgit.lib.ObjectReader;
  61. import org.eclipse.jgit.lib.Repository;
  62. import org.eclipse.jgit.lib.RepositoryState;
  63. import org.eclipse.jgit.merge.MergeStrategy;
  64. import org.eclipse.jgit.merge.ResolveMerger;
  65. import org.eclipse.jgit.revwalk.RevCommit;
  66. import org.eclipse.jgit.revwalk.RevTree;
  67. import org.eclipse.jgit.revwalk.RevWalk;
  68. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  69. import org.eclipse.jgit.treewalk.FileTreeIterator;
  70. import org.eclipse.jgit.treewalk.TreeWalk;
  71. /**
  72. * Command class to apply a stashed commit.
  73. *
  74. * This class behaves like <em>git stash apply --index</em>, i.e. it tries to
  75. * recover the stashed index state in addition to the working tree state.
  76. *
  77. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-stash.html"
  78. * >Git documentation about Stash</a>
  79. *
  80. * @since 2.0
  81. */
  82. public class StashApplyCommand extends GitCommand<ObjectId> {
  83. private static final String DEFAULT_REF = Constants.STASH + "@{0}"; //$NON-NLS-1$
  84. private String stashRef;
  85. private boolean applyIndex = true;
  86. private boolean ignoreRepositoryState;
  87. /**
  88. * Create command to apply the changes of a stashed commit
  89. *
  90. * @param repo
  91. */
  92. public StashApplyCommand(final Repository repo) {
  93. super(repo);
  94. }
  95. /**
  96. * Set the stash reference to apply
  97. * <p>
  98. * This will default to apply the latest stashed commit (stash@{0}) if
  99. * unspecified
  100. *
  101. * @param stashRef
  102. * @return {@code this}
  103. */
  104. public StashApplyCommand setStashRef(final String stashRef) {
  105. this.stashRef = stashRef;
  106. return this;
  107. }
  108. /**
  109. * @param ignoreRepositoryState
  110. * @return {@code this}
  111. * @since 3.2
  112. */
  113. public StashApplyCommand ignoreRepositoryState(boolean ignoreRepositoryState) {
  114. this.ignoreRepositoryState = ignoreRepositoryState;
  115. return this;
  116. }
  117. private ObjectId getStashId() throws GitAPIException {
  118. final String revision = stashRef != null ? stashRef : DEFAULT_REF;
  119. final ObjectId stashId;
  120. try {
  121. stashId = repo.resolve(revision);
  122. } catch (IOException e) {
  123. throw new InvalidRefNameException(MessageFormat.format(
  124. JGitText.get().stashResolveFailed, revision), e);
  125. }
  126. if (stashId == null)
  127. throw new InvalidRefNameException(MessageFormat.format(
  128. JGitText.get().stashResolveFailed, revision));
  129. return stashId;
  130. }
  131. /**
  132. * Apply the changes in a stashed commit to the working directory and index
  133. *
  134. * @return id of stashed commit that was applied TODO: Does anyone depend on
  135. * this, or could we make it more like Merge/CherryPick/Revert?
  136. * @throws GitAPIException
  137. * @throws WrongRepositoryStateException
  138. * @throws NoHeadException
  139. * @throws StashApplyFailureException
  140. */
  141. public ObjectId call() throws GitAPIException,
  142. WrongRepositoryStateException, NoHeadException,
  143. StashApplyFailureException {
  144. checkCallable();
  145. if (!ignoreRepositoryState
  146. && repo.getRepositoryState() != RepositoryState.SAFE)
  147. throw new WrongRepositoryStateException(MessageFormat.format(
  148. JGitText.get().stashApplyOnUnsafeRepository,
  149. repo.getRepositoryState()));
  150. ObjectReader reader = repo.newObjectReader();
  151. try {
  152. RevWalk revWalk = new RevWalk(reader);
  153. ObjectId headCommit = repo.resolve(Constants.HEAD);
  154. if (headCommit == null)
  155. throw new NoHeadException(JGitText.get().stashApplyWithoutHead);
  156. final ObjectId stashId = getStashId();
  157. RevCommit stashCommit = revWalk.parseCommit(stashId);
  158. if (stashCommit.getParentCount() != 2)
  159. throw new JGitInternalException(MessageFormat.format(
  160. JGitText.get().stashCommitMissingTwoParents,
  161. stashId.name()));
  162. ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  163. ObjectId stashIndexCommit = revWalk.parseCommit(stashCommit
  164. .getParent(1));
  165. ObjectId stashHeadCommit = stashCommit.getParent(0);
  166. ResolveMerger merger = (ResolveMerger) MergeStrategy.RECURSIVE
  167. .newMerger(repo);
  168. merger.setCommitNames(new String[] { "stashed HEAD", "HEAD",
  169. "stash" });
  170. merger.setBase(stashHeadCommit);
  171. merger.setWorkingTreeIterator(new FileTreeIterator(repo));
  172. if (merger.merge(headCommit, stashCommit)) {
  173. DirCache dc = repo.lockDirCache();
  174. DirCacheCheckout dco = new DirCacheCheckout(repo, headTree,
  175. dc, merger.getResultTreeId());
  176. dco.setFailOnConflict(true);
  177. dco.checkout(); // Ignoring failed deletes....
  178. if (applyIndex) {
  179. ResolveMerger ixMerger = (ResolveMerger) MergeStrategy.RECURSIVE
  180. .newMerger(repo, true);
  181. ixMerger.setCommitNames(new String[] { "stashed HEAD",
  182. "HEAD", "stashed index" });
  183. ixMerger.setBase(stashHeadCommit);
  184. boolean ok = ixMerger.merge(headCommit, stashIndexCommit);
  185. if (ok) {
  186. resetIndex(revWalk
  187. .parseTree(ixMerger.getResultTreeId()));
  188. } else {
  189. throw new StashApplyFailureException(
  190. JGitText.get().stashApplyConflict);
  191. }
  192. }
  193. } else {
  194. throw new StashApplyFailureException(
  195. JGitText.get().stashApplyConflict);
  196. }
  197. return stashId;
  198. } catch (JGitInternalException e) {
  199. throw e;
  200. } catch (IOException e) {
  201. throw new JGitInternalException(JGitText.get().stashApplyFailed, e);
  202. } finally {
  203. reader.release();
  204. }
  205. }
  206. /**
  207. * @param applyIndex
  208. * true (default) if the command should restore the index state
  209. */
  210. public void setApplyIndex(boolean applyIndex) {
  211. this.applyIndex = applyIndex;
  212. }
  213. private void resetIndex(RevTree tree) throws IOException {
  214. DirCache dc = repo.lockDirCache();
  215. TreeWalk walk = null;
  216. try {
  217. DirCacheBuilder builder = dc.builder();
  218. walk = new TreeWalk(repo);
  219. walk.addTree(tree);
  220. walk.addTree(new DirCacheIterator(dc));
  221. walk.setRecursive(true);
  222. while (walk.next()) {
  223. AbstractTreeIterator cIter = walk.getTree(0,
  224. AbstractTreeIterator.class);
  225. if (cIter == null) {
  226. // Not in commit, don't add to new index
  227. continue;
  228. }
  229. final DirCacheEntry entry = new DirCacheEntry(walk.getRawPath());
  230. entry.setFileMode(cIter.getEntryFileMode());
  231. entry.setObjectIdFromRaw(cIter.idBuffer(), cIter.idOffset());
  232. DirCacheIterator dcIter = walk.getTree(1,
  233. DirCacheIterator.class);
  234. if (dcIter != null && dcIter.idEqual(cIter)) {
  235. DirCacheEntry indexEntry = dcIter.getDirCacheEntry();
  236. entry.setLastModified(indexEntry.getLastModified());
  237. entry.setLength(indexEntry.getLength());
  238. }
  239. builder.add(entry);
  240. }
  241. builder.commit();
  242. } finally {
  243. dc.unlock();
  244. if (walk != null)
  245. walk.release();
  246. }
  247. }
  248. }