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

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