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.

StashCreateCommand.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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.File;
  45. import java.io.IOException;
  46. import java.io.InputStream;
  47. import java.text.MessageFormat;
  48. import java.util.ArrayList;
  49. import java.util.List;
  50. import org.eclipse.jgit.api.ResetCommand.ResetType;
  51. import org.eclipse.jgit.api.errors.GitAPIException;
  52. import org.eclipse.jgit.api.errors.JGitInternalException;
  53. import org.eclipse.jgit.api.errors.NoHeadException;
  54. import org.eclipse.jgit.api.errors.UnmergedPathsException;
  55. import org.eclipse.jgit.dircache.DirCache;
  56. import org.eclipse.jgit.dircache.DirCacheBuilder;
  57. import org.eclipse.jgit.dircache.DirCacheEditor;
  58. import org.eclipse.jgit.dircache.DirCacheEditor.DeletePath;
  59. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  60. import org.eclipse.jgit.dircache.DirCacheEntry;
  61. import org.eclipse.jgit.dircache.DirCacheIterator;
  62. import org.eclipse.jgit.errors.UnmergedPathException;
  63. import org.eclipse.jgit.internal.JGitText;
  64. import org.eclipse.jgit.lib.CommitBuilder;
  65. import org.eclipse.jgit.lib.Constants;
  66. import org.eclipse.jgit.lib.MutableObjectId;
  67. import org.eclipse.jgit.lib.ObjectId;
  68. import org.eclipse.jgit.lib.ObjectInserter;
  69. import org.eclipse.jgit.lib.ObjectReader;
  70. import org.eclipse.jgit.lib.PersonIdent;
  71. import org.eclipse.jgit.lib.Ref;
  72. import org.eclipse.jgit.lib.RefUpdate;
  73. import org.eclipse.jgit.lib.Repository;
  74. import org.eclipse.jgit.revwalk.RevCommit;
  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. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  80. import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
  81. import org.eclipse.jgit.treewalk.filter.IndexDiffFilter;
  82. import org.eclipse.jgit.treewalk.filter.SkipWorkTreeFilter;
  83. import org.eclipse.jgit.util.FileUtils;
  84. /**
  85. * Command class to stash changes in the working directory and index in a
  86. * commit.
  87. *
  88. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-stash.html"
  89. * >Git documentation about Stash</a>
  90. * @since 2.0
  91. */
  92. public class StashCreateCommand extends GitCommand<RevCommit> {
  93. private static final String MSG_INDEX = "index on {0}: {1} {2}"; //$NON-NLS-1$
  94. private static final String MSG_UNTRACKED = "untracked files on {0}: {1} {2}"; //$NON-NLS-1$
  95. private static final String MSG_WORKING_DIR = "WIP on {0}: {1} {2}"; //$NON-NLS-1$
  96. private String indexMessage = MSG_INDEX;
  97. private String workingDirectoryMessage = MSG_WORKING_DIR;
  98. private String ref = Constants.R_STASH;
  99. private PersonIdent person;
  100. private boolean includeUntracked;
  101. /**
  102. * Create a command to stash changes in the working directory and index
  103. *
  104. * @param repo
  105. */
  106. public StashCreateCommand(Repository repo) {
  107. super(repo);
  108. person = new PersonIdent(repo);
  109. }
  110. /**
  111. * Set the message used when committing index changes
  112. * <p>
  113. * The message will be formatted with the current branch, abbreviated commit
  114. * id, and short commit message when used.
  115. *
  116. * @param message
  117. * @return {@code this}
  118. */
  119. public StashCreateCommand setIndexMessage(String message) {
  120. indexMessage = message;
  121. return this;
  122. }
  123. /**
  124. * Set the message used when committing working directory changes
  125. * <p>
  126. * The message will be formatted with the current branch, abbreviated commit
  127. * id, and short commit message when used.
  128. *
  129. * @param message
  130. * @return {@code this}
  131. */
  132. public StashCreateCommand setWorkingDirectoryMessage(String message) {
  133. workingDirectoryMessage = message;
  134. return this;
  135. }
  136. /**
  137. * Set the person to use as the author and committer in the commits made
  138. *
  139. * @param person
  140. * @return {@code this}
  141. */
  142. public StashCreateCommand setPerson(PersonIdent person) {
  143. this.person = person;
  144. return this;
  145. }
  146. /**
  147. * Set the reference to update with the stashed commit id
  148. * If null, no reference is updated
  149. * <p>
  150. * This value defaults to {@link Constants#R_STASH}
  151. *
  152. * @param ref
  153. * @return {@code this}
  154. */
  155. public StashCreateCommand setRef(String ref) {
  156. this.ref = ref;
  157. return this;
  158. }
  159. /**
  160. * Whether to include untracked files in the stash.
  161. *
  162. * @param includeUntracked
  163. * @return {@code this}
  164. * @since 3.4
  165. */
  166. public StashCreateCommand setIncludeUntracked(boolean includeUntracked) {
  167. this.includeUntracked = includeUntracked;
  168. return this;
  169. }
  170. private RevCommit parseCommit(final ObjectReader reader,
  171. final ObjectId headId) throws IOException {
  172. try (final RevWalk walk = new RevWalk(reader)) {
  173. return walk.parseCommit(headId);
  174. }
  175. }
  176. private CommitBuilder createBuilder() {
  177. CommitBuilder builder = new CommitBuilder();
  178. PersonIdent author = person;
  179. if (author == null)
  180. author = new PersonIdent(repo);
  181. builder.setAuthor(author);
  182. builder.setCommitter(author);
  183. return builder;
  184. }
  185. private void updateStashRef(ObjectId commitId, PersonIdent refLogIdent,
  186. String refLogMessage) throws IOException {
  187. if (ref == null)
  188. return;
  189. Ref currentRef = repo.findRef(ref);
  190. RefUpdate refUpdate = repo.updateRef(ref);
  191. refUpdate.setNewObjectId(commitId);
  192. refUpdate.setRefLogIdent(refLogIdent);
  193. refUpdate.setRefLogMessage(refLogMessage, false);
  194. if (currentRef != null)
  195. refUpdate.setExpectedOldObjectId(currentRef.getObjectId());
  196. else
  197. refUpdate.setExpectedOldObjectId(ObjectId.zeroId());
  198. refUpdate.forceUpdate();
  199. }
  200. private Ref getHead() throws GitAPIException {
  201. try {
  202. Ref head = repo.exactRef(Constants.HEAD);
  203. if (head == null || head.getObjectId() == null)
  204. throw new NoHeadException(JGitText.get().headRequiredToStash);
  205. return head;
  206. } catch (IOException e) {
  207. throw new JGitInternalException(JGitText.get().stashFailed, e);
  208. }
  209. }
  210. /**
  211. * Stash the contents on the working directory and index in separate commits
  212. * and reset to the current HEAD commit.
  213. *
  214. * @return stashed commit or null if no changes to stash
  215. * @throws GitAPIException
  216. */
  217. public RevCommit call() throws GitAPIException {
  218. checkCallable();
  219. Ref head = getHead();
  220. try (ObjectReader reader = repo.newObjectReader()) {
  221. RevCommit headCommit = parseCommit(reader, head.getObjectId());
  222. DirCache cache = repo.lockDirCache();
  223. ObjectId commitId;
  224. try (ObjectInserter inserter = repo.newObjectInserter();
  225. TreeWalk treeWalk = new TreeWalk(repo, reader)) {
  226. treeWalk.setRecursive(true);
  227. treeWalk.addTree(headCommit.getTree());
  228. treeWalk.addTree(new DirCacheIterator(cache));
  229. treeWalk.addTree(new FileTreeIterator(repo));
  230. treeWalk.getTree(2, FileTreeIterator.class)
  231. .setDirCacheIterator(treeWalk, 1);
  232. treeWalk.setFilter(AndTreeFilter.create(new SkipWorkTreeFilter(
  233. 1), new IndexDiffFilter(1, 2)));
  234. // Return null if no local changes to stash
  235. if (!treeWalk.next())
  236. return null;
  237. MutableObjectId id = new MutableObjectId();
  238. List<PathEdit> wtEdits = new ArrayList<PathEdit>();
  239. List<String> wtDeletes = new ArrayList<String>();
  240. List<DirCacheEntry> untracked = new ArrayList<DirCacheEntry>();
  241. boolean hasChanges = false;
  242. do {
  243. AbstractTreeIterator headIter = treeWalk.getTree(0,
  244. AbstractTreeIterator.class);
  245. DirCacheIterator indexIter = treeWalk.getTree(1,
  246. DirCacheIterator.class);
  247. WorkingTreeIterator wtIter = treeWalk.getTree(2,
  248. WorkingTreeIterator.class);
  249. if (indexIter != null
  250. && !indexIter.getDirCacheEntry().isMerged())
  251. throw new UnmergedPathsException(
  252. new UnmergedPathException(
  253. indexIter.getDirCacheEntry()));
  254. if (wtIter != null) {
  255. if (indexIter == null && headIter == null
  256. && !includeUntracked)
  257. continue;
  258. hasChanges = true;
  259. if (indexIter != null && wtIter.idEqual(indexIter))
  260. continue;
  261. if (headIter != null && wtIter.idEqual(headIter))
  262. continue;
  263. treeWalk.getObjectId(id, 0);
  264. final DirCacheEntry entry = new DirCacheEntry(
  265. treeWalk.getRawPath());
  266. entry.setLength(wtIter.getEntryLength());
  267. entry.setLastModified(wtIter.getEntryLastModified());
  268. entry.setFileMode(wtIter.getEntryFileMode());
  269. long contentLength = wtIter.getEntryContentLength();
  270. InputStream in = wtIter.openEntryStream();
  271. try {
  272. entry.setObjectId(inserter.insert(
  273. Constants.OBJ_BLOB, contentLength, in));
  274. } finally {
  275. in.close();
  276. }
  277. if (indexIter == null && headIter == null)
  278. untracked.add(entry);
  279. else
  280. wtEdits.add(new PathEdit(entry) {
  281. public void apply(DirCacheEntry ent) {
  282. ent.copyMetaData(entry);
  283. }
  284. });
  285. }
  286. hasChanges = true;
  287. if (wtIter == null && headIter != null)
  288. wtDeletes.add(treeWalk.getPathString());
  289. } while (treeWalk.next());
  290. if (!hasChanges)
  291. return null;
  292. String branch = Repository.shortenRefName(head.getTarget()
  293. .getName());
  294. // Commit index changes
  295. CommitBuilder builder = createBuilder();
  296. builder.setParentId(headCommit);
  297. builder.setTreeId(cache.writeTree(inserter));
  298. builder.setMessage(MessageFormat.format(indexMessage, branch,
  299. headCommit.abbreviate(7).name(),
  300. headCommit.getShortMessage()));
  301. ObjectId indexCommit = inserter.insert(builder);
  302. // Commit untracked changes
  303. ObjectId untrackedCommit = null;
  304. if (!untracked.isEmpty()) {
  305. DirCache untrackedDirCache = DirCache.newInCore();
  306. DirCacheBuilder untrackedBuilder = untrackedDirCache
  307. .builder();
  308. for (DirCacheEntry entry : untracked)
  309. untrackedBuilder.add(entry);
  310. untrackedBuilder.finish();
  311. builder.setParentIds(new ObjectId[0]);
  312. builder.setTreeId(untrackedDirCache.writeTree(inserter));
  313. builder.setMessage(MessageFormat.format(MSG_UNTRACKED,
  314. branch, headCommit.abbreviate(7).name(),
  315. headCommit.getShortMessage()));
  316. untrackedCommit = inserter.insert(builder);
  317. }
  318. // Commit working tree changes
  319. if (!wtEdits.isEmpty() || !wtDeletes.isEmpty()) {
  320. DirCacheEditor editor = cache.editor();
  321. for (PathEdit edit : wtEdits)
  322. editor.add(edit);
  323. for (String path : wtDeletes)
  324. editor.add(new DeletePath(path));
  325. editor.finish();
  326. }
  327. builder.setParentId(headCommit);
  328. builder.addParentId(indexCommit);
  329. if (untrackedCommit != null)
  330. builder.addParentId(untrackedCommit);
  331. builder.setMessage(MessageFormat.format(
  332. workingDirectoryMessage, branch,
  333. headCommit.abbreviate(7).name(),
  334. headCommit.getShortMessage()));
  335. builder.setTreeId(cache.writeTree(inserter));
  336. commitId = inserter.insert(builder);
  337. inserter.flush();
  338. updateStashRef(commitId, builder.getAuthor(),
  339. builder.getMessage());
  340. // Remove untracked files
  341. if (includeUntracked) {
  342. for (DirCacheEntry entry : untracked) {
  343. File file = new File(repo.getWorkTree(),
  344. entry.getPathString());
  345. FileUtils.delete(file);
  346. }
  347. }
  348. } finally {
  349. cache.unlock();
  350. }
  351. // Hard reset to HEAD
  352. new ResetCommand(repo).setMode(ResetType.HARD).call();
  353. // Return stashed commit
  354. return parseCommit(reader, commitId);
  355. } catch (IOException e) {
  356. throw new JGitInternalException(JGitText.get().stashFailed, e);
  357. }
  358. }
  359. }