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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 restoreIndex = true;
  93. private boolean restoreUntracked = 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 (restoreUntracked && 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 (restoreIndex) {
  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. * @deprecated use {@link #setRestoreIndex} instead
  257. */
  258. @Deprecated
  259. public void setApplyIndex(boolean applyIndex) {
  260. this.restoreIndex = applyIndex;
  261. }
  262. /**
  263. * Whether to restore the index state
  264. *
  265. * @param restoreIndex
  266. * true (default) if the command should restore the index state
  267. * @return {@code this}
  268. * @since 5.3
  269. */
  270. public StashApplyCommand setRestoreIndex(boolean restoreIndex) {
  271. this.restoreIndex = restoreIndex;
  272. return this;
  273. }
  274. /**
  275. * Set the <code>MergeStrategy</code> to use.
  276. *
  277. * @param strategy
  278. * The merge strategy to use in order to merge during this
  279. * command execution.
  280. * @return {@code this}
  281. * @since 3.4
  282. */
  283. public StashApplyCommand setStrategy(MergeStrategy strategy) {
  284. this.strategy = strategy;
  285. return this;
  286. }
  287. /**
  288. * Whether the command should restore untracked files
  289. *
  290. * @param applyUntracked
  291. * true (default) if the command should restore untracked files
  292. * @since 3.4
  293. * @deprecated use {@link #setRestoreUntracked} instead
  294. */
  295. @Deprecated
  296. public void setApplyUntracked(boolean applyUntracked) {
  297. this.restoreUntracked = applyUntracked;
  298. }
  299. /**
  300. * Whether the command should restore untracked files
  301. *
  302. * @param restoreUntracked
  303. * true (default) if the command should restore untracked files
  304. * @return {@code this}
  305. * @since 5.3
  306. */
  307. public StashApplyCommand setRestoreUntracked(boolean restoreUntracked) {
  308. this.restoreUntracked = restoreUntracked;
  309. return this;
  310. }
  311. private void resetIndex(RevTree tree) throws IOException {
  312. DirCache dc = repo.lockDirCache();
  313. try (TreeWalk walk = new TreeWalk(repo)) {
  314. DirCacheBuilder builder = dc.builder();
  315. walk.addTree(tree);
  316. walk.addTree(new DirCacheIterator(dc));
  317. walk.setRecursive(true);
  318. while (walk.next()) {
  319. AbstractTreeIterator cIter = walk.getTree(0,
  320. AbstractTreeIterator.class);
  321. if (cIter == null) {
  322. // Not in commit, don't add to new index
  323. continue;
  324. }
  325. final DirCacheEntry entry = new DirCacheEntry(walk.getRawPath());
  326. entry.setFileMode(cIter.getEntryFileMode());
  327. entry.setObjectIdFromRaw(cIter.idBuffer(), cIter.idOffset());
  328. DirCacheIterator dcIter = walk.getTree(1,
  329. DirCacheIterator.class);
  330. if (dcIter != null && dcIter.idEqual(cIter)) {
  331. DirCacheEntry indexEntry = dcIter.getDirCacheEntry();
  332. entry.setLastModified(indexEntry.getLastModifiedInstant());
  333. entry.setLength(indexEntry.getLength());
  334. }
  335. builder.add(entry);
  336. }
  337. builder.commit();
  338. } finally {
  339. dc.unlock();
  340. }
  341. }
  342. private void resetUntracked(RevTree tree) throws CheckoutConflictException,
  343. IOException {
  344. Set<String> actuallyModifiedPaths = new HashSet<>();
  345. // TODO maybe NameConflictTreeWalk ?
  346. try (TreeWalk walk = new TreeWalk(repo)) {
  347. walk.addTree(tree);
  348. walk.addTree(new FileTreeIterator(repo));
  349. walk.setRecursive(true);
  350. final ObjectReader reader = walk.getObjectReader();
  351. while (walk.next()) {
  352. final AbstractTreeIterator cIter = walk.getTree(0,
  353. AbstractTreeIterator.class);
  354. if (cIter == null)
  355. // Not in commit, don't create untracked
  356. continue;
  357. final EolStreamType eolStreamType = walk
  358. .getEolStreamType(CHECKOUT_OP);
  359. final DirCacheEntry entry = new DirCacheEntry(walk.getRawPath());
  360. entry.setFileMode(cIter.getEntryFileMode());
  361. entry.setObjectIdFromRaw(cIter.idBuffer(), cIter.idOffset());
  362. FileTreeIterator fIter = walk
  363. .getTree(1, FileTreeIterator.class);
  364. if (fIter != null) {
  365. if (fIter.isModified(entry, true, reader)) {
  366. // file exists and is dirty
  367. throw new CheckoutConflictException(
  368. entry.getPathString());
  369. }
  370. }
  371. checkoutPath(entry, reader,
  372. new CheckoutMetadata(eolStreamType, null));
  373. actuallyModifiedPaths.add(entry.getPathString());
  374. }
  375. } finally {
  376. if (!actuallyModifiedPaths.isEmpty()) {
  377. repo.fireEvent(new WorkingTreeModifiedEvent(
  378. actuallyModifiedPaths, null));
  379. }
  380. }
  381. }
  382. private void checkoutPath(DirCacheEntry entry, ObjectReader reader,
  383. CheckoutMetadata checkoutMetadata) {
  384. try {
  385. DirCacheCheckout.checkoutEntry(repo, entry, reader, true,
  386. checkoutMetadata);
  387. } catch (IOException e) {
  388. throw new JGitInternalException(MessageFormat.format(
  389. JGitText.get().checkoutConflictWithFile,
  390. entry.getPathString()), e);
  391. }
  392. }
  393. }