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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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.File;
  45. import java.io.IOException;
  46. import java.text.MessageFormat;
  47. import org.eclipse.jgit.api.errors.GitAPIException;
  48. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  49. import org.eclipse.jgit.api.errors.JGitInternalException;
  50. import org.eclipse.jgit.api.errors.NoHeadException;
  51. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  52. import org.eclipse.jgit.dircache.DirCache;
  53. import org.eclipse.jgit.dircache.DirCacheCheckout;
  54. import org.eclipse.jgit.dircache.DirCacheEditor;
  55. import org.eclipse.jgit.dircache.DirCacheEditor.DeletePath;
  56. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  57. import org.eclipse.jgit.dircache.DirCacheEntry;
  58. import org.eclipse.jgit.dircache.DirCacheIterator;
  59. import org.eclipse.jgit.errors.CheckoutConflictException;
  60. import org.eclipse.jgit.internal.JGitText;
  61. import org.eclipse.jgit.lib.Constants;
  62. import org.eclipse.jgit.lib.ObjectId;
  63. import org.eclipse.jgit.lib.ObjectReader;
  64. import org.eclipse.jgit.lib.Repository;
  65. import org.eclipse.jgit.lib.RepositoryState;
  66. import org.eclipse.jgit.revwalk.RevCommit;
  67. import org.eclipse.jgit.revwalk.RevTree;
  68. import org.eclipse.jgit.revwalk.RevWalk;
  69. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  70. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  71. import org.eclipse.jgit.treewalk.FileTreeIterator;
  72. import org.eclipse.jgit.treewalk.TreeWalk;
  73. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  74. import org.eclipse.jgit.util.FileUtils;
  75. /**
  76. * Command class to apply a stashed commit.
  77. *
  78. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-stash.html"
  79. * >Git documentation about Stash</a>
  80. * @since 2.0
  81. */
  82. public class StashApplyCommand extends GitCommand<ObjectId> {
  83. private static final String DEFAULT_REF = Constants.STASH + "@{0}";
  84. /**
  85. * Stash diff filter that looks for differences in the first three trees
  86. * which must be the stash head tree, stash index tree, and stash working
  87. * directory tree in any order.
  88. */
  89. private static class StashDiffFilter extends TreeFilter {
  90. @Override
  91. public boolean include(final TreeWalk walker) {
  92. final int m = walker.getRawMode(0);
  93. if (walker.getRawMode(1) != m || !walker.idEqual(1, 0))
  94. return true;
  95. if (walker.getRawMode(2) != m || !walker.idEqual(2, 0))
  96. return true;
  97. return false;
  98. }
  99. @Override
  100. public boolean shouldBeRecursive() {
  101. return false;
  102. }
  103. @Override
  104. public TreeFilter clone() {
  105. return this;
  106. }
  107. @Override
  108. public String toString() {
  109. return "STASH_DIFF";
  110. }
  111. }
  112. private String stashRef;
  113. /**
  114. * Create command to apply the changes of a stashed commit
  115. *
  116. * @param repo
  117. */
  118. public StashApplyCommand(final Repository repo) {
  119. super(repo);
  120. }
  121. /**
  122. * Set the stash reference to apply
  123. * <p>
  124. * This will default to apply the latest stashed commit (stash@{0}) if
  125. * unspecified
  126. *
  127. * @param stashRef
  128. * @return {@code this}
  129. */
  130. public StashApplyCommand setStashRef(final String stashRef) {
  131. this.stashRef = stashRef;
  132. return this;
  133. }
  134. private boolean isEqualEntry(AbstractTreeIterator iter1,
  135. AbstractTreeIterator iter2) {
  136. if (!iter1.getEntryFileMode().equals(iter2.getEntryFileMode()))
  137. return false;
  138. ObjectId id1 = iter1.getEntryObjectId();
  139. ObjectId id2 = iter2.getEntryObjectId();
  140. return id1 != null ? id1.equals(id2) : id2 == null;
  141. }
  142. /**
  143. * Would unstashing overwrite local changes?
  144. *
  145. * @param stashIndexIter
  146. * @param stashWorkingTreeIter
  147. * @param headIter
  148. * @param indexIter
  149. * @param workingTreeIter
  150. * @return true if unstash conflict, false otherwise
  151. */
  152. private boolean isConflict(AbstractTreeIterator stashIndexIter,
  153. AbstractTreeIterator stashWorkingTreeIter,
  154. AbstractTreeIterator headIter, AbstractTreeIterator indexIter,
  155. AbstractTreeIterator workingTreeIter) {
  156. // Is the current index dirty?
  157. boolean indexDirty = indexIter != null
  158. && (headIter == null || !isEqualEntry(indexIter, headIter));
  159. // Is the current working tree dirty?
  160. boolean workingTreeDirty = workingTreeIter != null
  161. && (headIter == null || !isEqualEntry(workingTreeIter, headIter));
  162. // Would unstashing overwrite existing index changes?
  163. if (indexDirty && stashIndexIter != null && indexIter != null
  164. && !isEqualEntry(stashIndexIter, indexIter))
  165. return true;
  166. // Would unstashing overwrite existing working tree changes?
  167. if (workingTreeDirty && stashWorkingTreeIter != null
  168. && workingTreeIter != null
  169. && !isEqualEntry(stashWorkingTreeIter, workingTreeIter))
  170. return true;
  171. return false;
  172. }
  173. private ObjectId getHeadTree() throws JGitInternalException,
  174. GitAPIException {
  175. final ObjectId headTree;
  176. try {
  177. headTree = repo.resolve(Constants.HEAD + "^{tree}");
  178. } catch (IOException e) {
  179. throw new JGitInternalException(JGitText.get().cannotReadTree, e);
  180. }
  181. if (headTree == null)
  182. throw new NoHeadException(JGitText.get().cannotReadTree);
  183. return headTree;
  184. }
  185. private ObjectId getStashId() throws JGitInternalException, GitAPIException {
  186. final String revision = stashRef != null ? stashRef : DEFAULT_REF;
  187. final ObjectId stashId;
  188. try {
  189. stashId = repo.resolve(revision);
  190. } catch (IOException e) {
  191. throw new InvalidRefNameException(MessageFormat.format(
  192. JGitText.get().stashResolveFailed, revision), e);
  193. }
  194. if (stashId == null)
  195. throw new InvalidRefNameException(MessageFormat.format(
  196. JGitText.get().stashResolveFailed, revision));
  197. return stashId;
  198. }
  199. private void scanForConflicts(TreeWalk treeWalk) throws IOException {
  200. File workingTree = repo.getWorkTree();
  201. while (treeWalk.next()) {
  202. // State of the stashed index and working directory
  203. AbstractTreeIterator stashIndexIter = treeWalk.getTree(1,
  204. AbstractTreeIterator.class);
  205. AbstractTreeIterator stashWorkingIter = treeWalk.getTree(2,
  206. AbstractTreeIterator.class);
  207. // State of the current HEAD, index, and working directory
  208. AbstractTreeIterator headIter = treeWalk.getTree(3,
  209. AbstractTreeIterator.class);
  210. AbstractTreeIterator indexIter = treeWalk.getTree(4,
  211. AbstractTreeIterator.class);
  212. AbstractTreeIterator workingIter = treeWalk.getTree(5,
  213. AbstractTreeIterator.class);
  214. if (isConflict(stashIndexIter, stashWorkingIter, headIter,
  215. indexIter, workingIter)) {
  216. String path = treeWalk.getPathString();
  217. File file = new File(workingTree, path);
  218. throw new CheckoutConflictException(file.getAbsolutePath());
  219. }
  220. }
  221. }
  222. private void applyChanges(TreeWalk treeWalk, DirCache cache,
  223. DirCacheEditor editor) throws IOException {
  224. File workingTree = repo.getWorkTree();
  225. while (treeWalk.next()) {
  226. String path = treeWalk.getPathString();
  227. File file = new File(workingTree, path);
  228. // State of the stashed HEAD, index, and working directory
  229. AbstractTreeIterator stashHeadIter = treeWalk.getTree(0,
  230. AbstractTreeIterator.class);
  231. AbstractTreeIterator stashIndexIter = treeWalk.getTree(1,
  232. AbstractTreeIterator.class);
  233. AbstractTreeIterator stashWorkingIter = treeWalk.getTree(2,
  234. AbstractTreeIterator.class);
  235. if (stashWorkingIter != null && stashIndexIter != null) {
  236. // Checkout index change
  237. DirCacheEntry entry = cache.getEntry(path);
  238. if (entry == null)
  239. entry = new DirCacheEntry(treeWalk.getRawPath());
  240. entry.setFileMode(stashIndexIter.getEntryFileMode());
  241. entry.setObjectId(stashIndexIter.getEntryObjectId());
  242. DirCacheCheckout.checkoutEntry(repo, file, entry,
  243. treeWalk.getObjectReader());
  244. final DirCacheEntry updatedEntry = entry;
  245. editor.add(new PathEdit(path) {
  246. public void apply(DirCacheEntry ent) {
  247. ent.copyMetaData(updatedEntry);
  248. }
  249. });
  250. // Checkout working directory change
  251. if (!stashWorkingIter.idEqual(stashIndexIter)) {
  252. entry = new DirCacheEntry(treeWalk.getRawPath());
  253. entry.setObjectId(stashWorkingIter.getEntryObjectId());
  254. DirCacheCheckout.checkoutEntry(repo, file, entry,
  255. treeWalk.getObjectReader());
  256. }
  257. } else {
  258. if (stashIndexIter == null
  259. || (stashHeadIter != null && !stashIndexIter
  260. .idEqual(stashHeadIter)))
  261. editor.add(new DeletePath(path));
  262. FileUtils
  263. .delete(file, FileUtils.RETRY | FileUtils.SKIP_MISSING);
  264. }
  265. }
  266. }
  267. /**
  268. * Apply the changes in a stashed commit to the working directory and index
  269. *
  270. * @return id of stashed commit that was applied
  271. */
  272. public ObjectId call() throws GitAPIException, JGitInternalException {
  273. checkCallable();
  274. if (repo.getRepositoryState() != RepositoryState.SAFE)
  275. throw new WrongRepositoryStateException(MessageFormat.format(
  276. JGitText.get().stashApplyOnUnsafeRepository,
  277. repo.getRepositoryState()));
  278. final ObjectId headTree = getHeadTree();
  279. final ObjectId stashId = getStashId();
  280. ObjectReader reader = repo.newObjectReader();
  281. try {
  282. RevWalk revWalk = new RevWalk(reader);
  283. RevCommit stashCommit = revWalk.parseCommit(stashId);
  284. if (stashCommit.getParentCount() != 2)
  285. throw new JGitInternalException(MessageFormat.format(
  286. JGitText.get().stashCommitMissingTwoParents,
  287. stashId.name()));
  288. RevTree stashWorkingTree = stashCommit.getTree();
  289. RevTree stashIndexTree = revWalk.parseCommit(
  290. stashCommit.getParent(1)).getTree();
  291. RevTree stashHeadTree = revWalk.parseCommit(
  292. stashCommit.getParent(0)).getTree();
  293. CanonicalTreeParser stashWorkingIter = new CanonicalTreeParser();
  294. stashWorkingIter.reset(reader, stashWorkingTree);
  295. CanonicalTreeParser stashIndexIter = new CanonicalTreeParser();
  296. stashIndexIter.reset(reader, stashIndexTree);
  297. CanonicalTreeParser stashHeadIter = new CanonicalTreeParser();
  298. stashHeadIter.reset(reader, stashHeadTree);
  299. CanonicalTreeParser headIter = new CanonicalTreeParser();
  300. headIter.reset(reader, headTree);
  301. DirCache cache = repo.lockDirCache();
  302. DirCacheEditor editor = cache.editor();
  303. try {
  304. DirCacheIterator indexIter = new DirCacheIterator(cache);
  305. FileTreeIterator workingIter = new FileTreeIterator(repo);
  306. TreeWalk treeWalk = new TreeWalk(reader);
  307. treeWalk.setRecursive(true);
  308. treeWalk.setFilter(new StashDiffFilter());
  309. treeWalk.addTree(stashHeadIter);
  310. treeWalk.addTree(stashIndexIter);
  311. treeWalk.addTree(stashWorkingIter);
  312. treeWalk.addTree(headIter);
  313. treeWalk.addTree(indexIter);
  314. treeWalk.addTree(workingIter);
  315. scanForConflicts(treeWalk);
  316. // Reset trees and walk
  317. treeWalk.reset();
  318. stashWorkingIter.reset(reader, stashWorkingTree);
  319. stashIndexIter.reset(reader, stashIndexTree);
  320. stashHeadIter.reset(reader, stashHeadTree);
  321. treeWalk.addTree(stashHeadIter);
  322. treeWalk.addTree(stashIndexIter);
  323. treeWalk.addTree(stashWorkingIter);
  324. applyChanges(treeWalk, cache, editor);
  325. } finally {
  326. editor.commit();
  327. cache.unlock();
  328. }
  329. } catch (JGitInternalException e) {
  330. throw e;
  331. } catch (IOException e) {
  332. throw new JGitInternalException(JGitText.get().stashApplyFailed, e);
  333. } finally {
  334. reader.release();
  335. }
  336. return stashId;
  337. }
  338. }