PageRenderTime 27ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 1ms

/org.eclipse.jgit/src/org/eclipse/jgit/api/ResetCommand.java

https://bitbucket.org/albfan/jgit
Java | 357 lines | 212 code | 36 blank | 109 comment | 26 complexity | d72bd18e1fa72f4b91ad347002cbc706 MD5 | raw file
  1. /*
  2. * Copyright (C) 2011, Chris Aniszczyk <caniszczyk@gmail.com>
  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.text.MessageFormat;
  46. import java.util.Collection;
  47. import java.util.LinkedList;
  48. import org.eclipse.jgit.JGitText;
  49. import org.eclipse.jgit.api.errors.JGitInternalException;
  50. import org.eclipse.jgit.dircache.DirCache;
  51. import org.eclipse.jgit.dircache.DirCacheBuilder;
  52. import org.eclipse.jgit.dircache.DirCacheCheckout;
  53. import org.eclipse.jgit.dircache.DirCacheEditor;
  54. import org.eclipse.jgit.dircache.DirCacheEntry;
  55. import org.eclipse.jgit.dircache.DirCacheIterator;
  56. import org.eclipse.jgit.lib.Constants;
  57. import org.eclipse.jgit.lib.FileMode;
  58. import org.eclipse.jgit.lib.ObjectId;
  59. import org.eclipse.jgit.lib.Ref;
  60. import org.eclipse.jgit.lib.RefUpdate;
  61. import org.eclipse.jgit.lib.Repository;
  62. import org.eclipse.jgit.lib.RepositoryState;
  63. import org.eclipse.jgit.revwalk.RevCommit;
  64. import org.eclipse.jgit.revwalk.RevWalk;
  65. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  66. import org.eclipse.jgit.treewalk.TreeWalk;
  67. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  68. /**
  69. * A class used to execute a {@code Reset} command. It has setters for all
  70. * supported options and arguments of this command and a {@link #call()} method
  71. * to finally execute the command. Each instance of this class should only be
  72. * used for one invocation of the command (means: one call to {@link #call()})
  73. *
  74. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-reset.html"
  75. * >Git documentation about Reset</a>
  76. */
  77. public class ResetCommand extends GitCommand<Ref> {
  78. /**
  79. * Kind of reset
  80. */
  81. public enum ResetType {
  82. /**
  83. * Just change the ref, the index and workdir are not changed.
  84. */
  85. SOFT,
  86. /**
  87. * Change the ref and the index, the workdir is not changed.
  88. */
  89. MIXED,
  90. /**
  91. * Change the ref, the index and the workdir
  92. */
  93. HARD,
  94. /**
  95. * Resets the index and updates the files in the working tree that are
  96. * different between respective commit and HEAD, but keeps those which
  97. * are different between the index and working tree
  98. */
  99. MERGE, // TODO not implemented yet
  100. /**
  101. * Change the ref, the index and the workdir that are different between
  102. * respective commit and HEAD
  103. */
  104. KEEP // TODO not implemented yet
  105. }
  106. private String ref = Constants.HEAD;
  107. private ResetType mode;
  108. private Collection<String> filepaths = new LinkedList<String>();
  109. /**
  110. *
  111. * @param repo
  112. */
  113. public ResetCommand(Repository repo) {
  114. super(repo);
  115. }
  116. /**
  117. * Executes the {@code Reset} command. Each instance of this class should
  118. * only be used for one invocation of the command. Don't call this method
  119. * twice on an instance.
  120. *
  121. * @return the Ref after reset
  122. */
  123. public Ref call() throws IOException {
  124. checkCallable();
  125. Ref r;
  126. RevCommit commit;
  127. try {
  128. RepositoryState state = repo.getRepositoryState();
  129. final boolean merging = state.equals(RepositoryState.MERGING)
  130. || state.equals(RepositoryState.MERGING_RESOLVED);
  131. final boolean cherryPicking = state
  132. .equals(RepositoryState.CHERRY_PICKING)
  133. || state.equals(RepositoryState.CHERRY_PICKING_RESOLVED);
  134. // resolve the ref to a commit
  135. final ObjectId commitId;
  136. try {
  137. commitId = repo.resolve(ref);
  138. if (commitId == null) {
  139. // @TODO throw an InvalidRefNameException. We can't do that
  140. // now because this would break the API
  141. throw new JGitInternalException("Invalid ref " + ref
  142. + " specified");
  143. }
  144. } catch (IOException e) {
  145. throw new JGitInternalException(
  146. MessageFormat.format(JGitText.get().cannotRead, ref),
  147. e);
  148. }
  149. RevWalk rw = new RevWalk(repo);
  150. try {
  151. commit = rw.parseCommit(commitId);
  152. } catch (IOException e) {
  153. throw new JGitInternalException(
  154. MessageFormat.format(
  155. JGitText.get().cannotReadCommit, commitId.toString()),
  156. e);
  157. } finally {
  158. rw.release();
  159. }
  160. if (!filepaths.isEmpty()) {
  161. // reset [commit] -- paths
  162. resetIndexForPaths(commit);
  163. setCallable(false);
  164. return repo.getRef(Constants.HEAD);
  165. }
  166. // write the ref
  167. final RefUpdate ru = repo.updateRef(Constants.HEAD);
  168. ru.setNewObjectId(commitId);
  169. String refName = Repository.shortenRefName(ref);
  170. String message = refName + ": updating " + Constants.HEAD; //$NON-NLS-1$
  171. ru.setRefLogMessage(message, false);
  172. if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE)
  173. throw new JGitInternalException(MessageFormat.format(
  174. JGitText.get().cannotLock, ru.getName()));
  175. switch (mode) {
  176. case HARD:
  177. checkoutIndex(commit);
  178. break;
  179. case MIXED:
  180. resetIndex(commit);
  181. break;
  182. case SOFT: // do nothing, only the ref was changed
  183. break;
  184. case KEEP: // TODO
  185. case MERGE: // TODO
  186. throw new UnsupportedOperationException();
  187. }
  188. if (mode != ResetType.SOFT) {
  189. if (merging)
  190. resetMerge();
  191. else if (cherryPicking)
  192. resetCherryPick();
  193. }
  194. setCallable(false);
  195. r = ru.getRef();
  196. } catch (IOException e) {
  197. throw new JGitInternalException(
  198. JGitText.get().exceptionCaughtDuringExecutionOfResetCommand,
  199. e);
  200. }
  201. return r;
  202. }
  203. /**
  204. * @param ref
  205. * the ref to reset to
  206. * @return this instance
  207. */
  208. public ResetCommand setRef(String ref) {
  209. this.ref = ref;
  210. return this;
  211. }
  212. /**
  213. * @param mode
  214. * the mode of the reset command
  215. * @return this instance
  216. */
  217. public ResetCommand setMode(ResetType mode) {
  218. if (!filepaths.isEmpty())
  219. throw new JGitInternalException(MessageFormat.format(
  220. JGitText.get().illegalCombinationOfArguments,
  221. "[--mixed | --soft | --hard]", "<paths>..."));
  222. this.mode = mode;
  223. return this;
  224. }
  225. /**
  226. * @param file
  227. * the file to add
  228. * @return this instance
  229. */
  230. public ResetCommand addPath(String file) {
  231. if (mode != null)
  232. throw new JGitInternalException(MessageFormat.format(
  233. JGitText.get().illegalCombinationOfArguments, "<paths>...",
  234. "[--mixed | --soft | --hard]"));
  235. filepaths.add(file);
  236. return this;
  237. }
  238. private void resetIndexForPaths(RevCommit commit) {
  239. DirCache dc = null;
  240. final DirCacheEditor edit;
  241. try {
  242. dc = repo.lockDirCache();
  243. edit = dc.editor();
  244. final TreeWalk tw = new TreeWalk(repo);
  245. tw.addTree(new DirCacheIterator(dc));
  246. tw.addTree(commit.getTree());
  247. tw.setFilter(PathFilterGroup.createFromStrings(filepaths));
  248. tw.setRecursive(true);
  249. while (tw.next()) {
  250. final String path = tw.getPathString();
  251. // DirCacheIterator dci = tw.getTree(0, DirCacheIterator.class);
  252. final CanonicalTreeParser tree = tw.getTree(1,
  253. CanonicalTreeParser.class);
  254. if (tree == null)
  255. // file is not in the commit, remove from index
  256. edit.add(new DirCacheEditor.DeletePath(path));
  257. else { // revert index to commit
  258. // it seams that there is concurrent access to tree
  259. // variable, therefore we need to keep references to
  260. // entryFileMode and entryObjectId in local
  261. // variables
  262. final FileMode entryFileMode = tree.getEntryFileMode();
  263. final ObjectId entryObjectId = tree.getEntryObjectId();
  264. edit.add(new DirCacheEditor.PathEdit(path) {
  265. @Override
  266. public void apply(DirCacheEntry ent) {
  267. ent.setFileMode(entryFileMode);
  268. ent.setObjectId(entryObjectId);
  269. ent.setLastModified(0);
  270. }
  271. });
  272. }
  273. }
  274. edit.commit();
  275. } catch (IOException e) {
  276. throw new RuntimeException(e);
  277. } finally {
  278. if (dc != null)
  279. dc.unlock();
  280. }
  281. }
  282. private void resetIndex(RevCommit commit) throws IOException {
  283. DirCache dc = null;
  284. try {
  285. dc = repo.lockDirCache();
  286. dc.clear();
  287. DirCacheBuilder dcb = dc.builder();
  288. dcb.addTree(new byte[0], 0, repo.newObjectReader(),
  289. commit.getTree());
  290. dcb.commit();
  291. } catch (IOException e) {
  292. throw e;
  293. } finally {
  294. if (dc != null)
  295. dc.unlock();
  296. }
  297. }
  298. private void checkoutIndex(RevCommit commit) throws IOException {
  299. DirCache dc = null;
  300. try {
  301. dc = repo.lockDirCache();
  302. DirCacheCheckout checkout = new DirCacheCheckout(repo, dc,
  303. commit.getTree());
  304. checkout.setFailOnConflict(false);
  305. checkout.checkout();
  306. } catch (IOException e) {
  307. throw e;
  308. } finally {
  309. if (dc != null)
  310. dc.unlock();
  311. }
  312. }
  313. private void resetMerge() throws IOException {
  314. repo.writeMergeHeads(null);
  315. repo.writeMergeCommitMsg(null);
  316. }
  317. private void resetCherryPick() throws IOException {
  318. repo.writeCherryPickHead(null);
  319. repo.writeMergeCommitMsg(null);
  320. }
  321. }