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

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