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

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