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

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