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 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. /**
  87. * Create command to apply the changes of a stashed commit
  88. *
  89. * @param repo
  90. */
  91. public StashApplyCommand(final Repository repo) {
  92. super(repo);
  93. }
  94. /**
  95. * Set the stash reference to apply
  96. * <p>
  97. * This will default to apply the latest stashed commit (stash@{0}) if
  98. * unspecified
  99. *
  100. * @param stashRef
  101. * @return {@code this}
  102. */
  103. public StashApplyCommand setStashRef(final String stashRef) {
  104. this.stashRef = stashRef;
  105. return this;
  106. }
  107. private ObjectId getStashId() throws GitAPIException {
  108. final String revision = stashRef != null ? stashRef : DEFAULT_REF;
  109. final ObjectId stashId;
  110. try {
  111. stashId = repo.resolve(revision);
  112. } catch (IOException e) {
  113. throw new InvalidRefNameException(MessageFormat.format(
  114. JGitText.get().stashResolveFailed, revision), e);
  115. }
  116. if (stashId == null)
  117. throw new InvalidRefNameException(MessageFormat.format(
  118. JGitText.get().stashResolveFailed, revision));
  119. return stashId;
  120. }
  121. /**
  122. * Apply the changes in a stashed commit to the working directory and index
  123. *
  124. * @return id of stashed commit that was applied TODO: Does anyone depend on
  125. * this, or could we make it more like Merge/CherryPick/Revert?
  126. * @throws GitAPIException
  127. * @throws WrongRepositoryStateException
  128. * @throws NoHeadException
  129. * @throws StashApplyFailureException
  130. */
  131. public ObjectId call() throws GitAPIException,
  132. WrongRepositoryStateException, NoHeadException,
  133. StashApplyFailureException {
  134. checkCallable();
  135. if (repo.getRepositoryState() != RepositoryState.SAFE)
  136. throw new WrongRepositoryStateException(MessageFormat.format(
  137. JGitText.get().stashApplyOnUnsafeRepository,
  138. repo.getRepositoryState()));
  139. ObjectReader reader = repo.newObjectReader();
  140. try {
  141. RevWalk revWalk = new RevWalk(reader);
  142. ObjectId headCommit = repo.resolve(Constants.HEAD);
  143. if (headCommit == null)
  144. throw new NoHeadException(JGitText.get().stashApplyWithoutHead);
  145. final ObjectId stashId = getStashId();
  146. RevCommit stashCommit = revWalk.parseCommit(stashId);
  147. if (stashCommit.getParentCount() != 2)
  148. throw new JGitInternalException(MessageFormat.format(
  149. JGitText.get().stashCommitMissingTwoParents,
  150. stashId.name()));
  151. ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}");
  152. ObjectId stashIndexCommit = revWalk.parseCommit(stashCommit
  153. .getParent(1));
  154. ObjectId stashHeadCommit = stashCommit.getParent(0);
  155. ResolveMerger merger = (ResolveMerger) MergeStrategy.RECURSIVE
  156. .newMerger(repo);
  157. merger.setCommitNames(new String[] { "stashed HEAD", "HEAD",
  158. "stash" });
  159. merger.setBase(stashHeadCommit);
  160. merger.setWorkingTreeIterator(new FileTreeIterator(repo));
  161. if (merger.merge(headCommit, stashCommit)) {
  162. DirCache dc = repo.lockDirCache();
  163. DirCacheCheckout dco = new DirCacheCheckout(repo, headTree,
  164. dc, merger.getResultTreeId());
  165. dco.setFailOnConflict(true);
  166. dco.checkout(); // Ignoring failed deletes....
  167. if (applyIndex) {
  168. ResolveMerger ixMerger = (ResolveMerger) MergeStrategy.RECURSIVE
  169. .newMerger(repo, true);
  170. ixMerger.setCommitNames(new String[] { "stashed HEAD",
  171. "HEAD", "stashed index" });
  172. boolean ok = ixMerger.merge(headCommit, stashIndexCommit);
  173. if (ok) {
  174. resetIndex(revWalk
  175. .parseTree(ixMerger.getResultTreeId()));
  176. } else {
  177. throw new StashApplyFailureException(
  178. JGitText.get().stashApplyConflict);
  179. }
  180. }
  181. } else {
  182. throw new StashApplyFailureException(
  183. JGitText.get().stashApplyConflict);
  184. }
  185. return stashId;
  186. } catch (JGitInternalException e) {
  187. throw e;
  188. } catch (IOException e) {
  189. throw new JGitInternalException(JGitText.get().stashApplyFailed, e);
  190. } finally {
  191. reader.release();
  192. }
  193. }
  194. /**
  195. * @param applyIndex
  196. * true (default) if the command should restore the index state
  197. */
  198. public void setApplyIndex(boolean applyIndex) {
  199. this.applyIndex = applyIndex;
  200. }
  201. private void resetIndex(RevTree tree) throws IOException {
  202. DirCache dc = repo.lockDirCache();
  203. TreeWalk walk = null;
  204. try {
  205. DirCacheBuilder builder = dc.builder();
  206. walk = new TreeWalk(repo);
  207. walk.addTree(tree);
  208. walk.addTree(new DirCacheIterator(dc));
  209. walk.setRecursive(true);
  210. while (walk.next()) {
  211. AbstractTreeIterator cIter = walk.getTree(0,
  212. AbstractTreeIterator.class);
  213. if (cIter == null) {
  214. // Not in commit, don't add to new index
  215. continue;
  216. }
  217. final DirCacheEntry entry = new DirCacheEntry(walk.getRawPath());
  218. entry.setFileMode(cIter.getEntryFileMode());
  219. entry.setObjectIdFromRaw(cIter.idBuffer(), cIter.idOffset());
  220. DirCacheIterator dcIter = walk.getTree(1,
  221. DirCacheIterator.class);
  222. if (dcIter != null && dcIter.idEqual(cIter)) {
  223. DirCacheEntry indexEntry = dcIter.getDirCacheEntry();
  224. entry.setLastModified(indexEntry.getLastModified());
  225. entry.setLength(indexEntry.getLength());
  226. }
  227. builder.add(entry);
  228. }
  229. builder.commit();
  230. } finally {
  231. dc.unlock();
  232. if (walk != null)
  233. walk.release();
  234. }
  235. }
  236. }