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

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