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

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