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

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