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

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