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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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}"; //$NON-NLS-1$
  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"; //$NON-NLS-1$
  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 GitAPIException {
  174. final ObjectId headTree;
  175. try {
  176. headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  177. } catch (IOException e) {
  178. throw new JGitInternalException(JGitText.get().cannotReadTree, e);
  179. }
  180. if (headTree == null)
  181. throw new NoHeadException(JGitText.get().cannotReadTree);
  182. return headTree;
  183. }
  184. private ObjectId getStashId() throws GitAPIException {
  185. final String revision = stashRef != null ? stashRef : DEFAULT_REF;
  186. final ObjectId stashId;
  187. try {
  188. stashId = repo.resolve(revision);
  189. } catch (IOException e) {
  190. throw new InvalidRefNameException(MessageFormat.format(
  191. JGitText.get().stashResolveFailed, revision), e);
  192. }
  193. if (stashId == null)
  194. throw new InvalidRefNameException(MessageFormat.format(
  195. JGitText.get().stashResolveFailed, revision));
  196. return stashId;
  197. }
  198. private void scanForConflicts(TreeWalk treeWalk) throws IOException {
  199. File workingTree = repo.getWorkTree();
  200. while (treeWalk.next()) {
  201. // State of the stashed index and working directory
  202. AbstractTreeIterator stashIndexIter = treeWalk.getTree(1,
  203. AbstractTreeIterator.class);
  204. AbstractTreeIterator stashWorkingIter = treeWalk.getTree(2,
  205. AbstractTreeIterator.class);
  206. // State of the current HEAD, index, and working directory
  207. AbstractTreeIterator headIter = treeWalk.getTree(3,
  208. AbstractTreeIterator.class);
  209. AbstractTreeIterator indexIter = treeWalk.getTree(4,
  210. AbstractTreeIterator.class);
  211. AbstractTreeIterator workingIter = treeWalk.getTree(5,
  212. AbstractTreeIterator.class);
  213. if (isConflict(stashIndexIter, stashWorkingIter, headIter,
  214. indexIter, workingIter)) {
  215. String path = treeWalk.getPathString();
  216. File file = new File(workingTree, path);
  217. throw new CheckoutConflictException(file.getAbsolutePath());
  218. }
  219. }
  220. }
  221. private void applyChanges(TreeWalk treeWalk, DirCache cache,
  222. DirCacheEditor editor) throws IOException {
  223. File workingTree = repo.getWorkTree();
  224. while (treeWalk.next()) {
  225. String path = treeWalk.getPathString();
  226. File file = new File(workingTree, path);
  227. // State of the stashed HEAD, index, and working directory
  228. AbstractTreeIterator stashHeadIter = treeWalk.getTree(0,
  229. AbstractTreeIterator.class);
  230. AbstractTreeIterator stashIndexIter = treeWalk.getTree(1,
  231. AbstractTreeIterator.class);
  232. AbstractTreeIterator stashWorkingIter = treeWalk.getTree(2,
  233. AbstractTreeIterator.class);
  234. if (stashWorkingIter != null && stashIndexIter != null) {
  235. // Checkout index change
  236. DirCacheEntry entry = cache.getEntry(path);
  237. if (entry == null)
  238. entry = new DirCacheEntry(treeWalk.getRawPath());
  239. entry.setFileMode(stashIndexIter.getEntryFileMode());
  240. entry.setObjectId(stashIndexIter.getEntryObjectId());
  241. DirCacheCheckout.checkoutEntry(repo, file, entry,
  242. treeWalk.getObjectReader());
  243. final DirCacheEntry updatedEntry = entry;
  244. editor.add(new PathEdit(path) {
  245. public void apply(DirCacheEntry ent) {
  246. ent.copyMetaData(updatedEntry);
  247. }
  248. });
  249. // Checkout working directory change
  250. if (!stashWorkingIter.idEqual(stashIndexIter)) {
  251. entry = new DirCacheEntry(treeWalk.getRawPath());
  252. entry.setObjectId(stashWorkingIter.getEntryObjectId());
  253. DirCacheCheckout.checkoutEntry(repo, file, entry,
  254. treeWalk.getObjectReader());
  255. }
  256. } else {
  257. if (stashIndexIter == null
  258. || (stashHeadIter != null && !stashIndexIter
  259. .idEqual(stashHeadIter)))
  260. editor.add(new DeletePath(path));
  261. FileUtils
  262. .delete(file, FileUtils.RETRY | FileUtils.SKIP_MISSING);
  263. }
  264. }
  265. }
  266. /**
  267. * Apply the changes in a stashed commit to the working directory and index
  268. *
  269. * @return id of stashed commit that was applied
  270. * @throws GitAPIException
  271. * @throws WrongRepositoryStateException
  272. */
  273. public ObjectId call() throws GitAPIException,
  274. WrongRepositoryStateException {
  275. checkCallable();
  276. if (repo.getRepositoryState() != RepositoryState.SAFE)
  277. throw new WrongRepositoryStateException(MessageFormat.format(
  278. JGitText.get().stashApplyOnUnsafeRepository,
  279. repo.getRepositoryState()));
  280. final ObjectId headTree = getHeadTree();
  281. final ObjectId stashId = getStashId();
  282. ObjectReader reader = repo.newObjectReader();
  283. try {
  284. RevWalk revWalk = new RevWalk(reader);
  285. RevCommit stashCommit = revWalk.parseCommit(stashId);
  286. if (stashCommit.getParentCount() != 2)
  287. throw new JGitInternalException(MessageFormat.format(
  288. JGitText.get().stashCommitMissingTwoParents,
  289. stashId.name()));
  290. RevTree stashWorkingTree = stashCommit.getTree();
  291. RevTree stashIndexTree = revWalk.parseCommit(
  292. stashCommit.getParent(1)).getTree();
  293. RevTree stashHeadTree = revWalk.parseCommit(
  294. stashCommit.getParent(0)).getTree();
  295. CanonicalTreeParser stashWorkingIter = new CanonicalTreeParser();
  296. stashWorkingIter.reset(reader, stashWorkingTree);
  297. CanonicalTreeParser stashIndexIter = new CanonicalTreeParser();
  298. stashIndexIter.reset(reader, stashIndexTree);
  299. CanonicalTreeParser stashHeadIter = new CanonicalTreeParser();
  300. stashHeadIter.reset(reader, stashHeadTree);
  301. CanonicalTreeParser headIter = new CanonicalTreeParser();
  302. headIter.reset(reader, headTree);
  303. DirCache cache = repo.lockDirCache();
  304. DirCacheEditor editor = cache.editor();
  305. try {
  306. DirCacheIterator indexIter = new DirCacheIterator(cache);
  307. FileTreeIterator workingIter = new FileTreeIterator(repo);
  308. TreeWalk treeWalk = new TreeWalk(reader);
  309. treeWalk.setRecursive(true);
  310. treeWalk.setFilter(new StashDiffFilter());
  311. treeWalk.addTree(stashHeadIter);
  312. treeWalk.addTree(stashIndexIter);
  313. treeWalk.addTree(stashWorkingIter);
  314. treeWalk.addTree(headIter);
  315. treeWalk.addTree(indexIter);
  316. treeWalk.addTree(workingIter);
  317. scanForConflicts(treeWalk);
  318. // Reset trees and walk
  319. treeWalk.reset();
  320. stashWorkingIter.reset(reader, stashWorkingTree);
  321. stashIndexIter.reset(reader, stashIndexTree);
  322. stashHeadIter.reset(reader, stashHeadTree);
  323. treeWalk.addTree(stashHeadIter);
  324. treeWalk.addTree(stashIndexIter);
  325. treeWalk.addTree(stashWorkingIter);
  326. applyChanges(treeWalk, cache, editor);
  327. } finally {
  328. editor.commit();
  329. cache.unlock();
  330. }
  331. } catch (JGitInternalException e) {
  332. throw e;
  333. } catch (IOException e) {
  334. throw new JGitInternalException(JGitText.get().stashApplyFailed, e);
  335. } finally {
  336. reader.release();
  337. }
  338. return stashId;
  339. }
  340. }