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.

ResetCommand.java 11KB

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