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

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