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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /*
  2. * Copyright (C) 2011-2013, 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.DirCacheBuildIterator;
  53. import org.eclipse.jgit.dircache.DirCacheBuilder;
  54. import org.eclipse.jgit.dircache.DirCacheCheckout;
  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.ObjectId;
  60. import org.eclipse.jgit.lib.Ref;
  61. import org.eclipse.jgit.lib.RefUpdate;
  62. import org.eclipse.jgit.lib.Repository;
  63. import org.eclipse.jgit.lib.RepositoryState;
  64. import org.eclipse.jgit.revwalk.RevCommit;
  65. import org.eclipse.jgit.revwalk.RevWalk;
  66. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  67. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  68. import org.eclipse.jgit.treewalk.EmptyTreeIterator;
  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. // We need to be able to distinguish whether the caller set the ref
  110. // explicitly or not, so we apply the default (HEAD) only later.
  111. private String ref = null;
  112. private ResetType mode;
  113. private Collection<String> filepaths = new LinkedList<String>();
  114. /**
  115. *
  116. * @param repo
  117. */
  118. public ResetCommand(Repository repo) {
  119. super(repo);
  120. }
  121. /**
  122. * Executes the {@code Reset} command. Each instance of this class should
  123. * only be used for one invocation of the command. Don't call this method
  124. * twice on an instance.
  125. *
  126. * @return the Ref after reset
  127. * @throws GitAPIException
  128. */
  129. public Ref call() throws GitAPIException, CheckoutConflictException {
  130. checkCallable();
  131. try {
  132. RepositoryState state = repo.getRepositoryState();
  133. final boolean merging = state.equals(RepositoryState.MERGING)
  134. || state.equals(RepositoryState.MERGING_RESOLVED);
  135. final boolean cherryPicking = state
  136. .equals(RepositoryState.CHERRY_PICKING)
  137. || state.equals(RepositoryState.CHERRY_PICKING_RESOLVED);
  138. final boolean reverting = state.equals(RepositoryState.REVERTING)
  139. || state.equals(RepositoryState.REVERTING_RESOLVED);
  140. final ObjectId commitId = resolveRefToCommitId();
  141. // When ref is explicitly specified, it has to resolve
  142. if (ref != null && commitId == null) {
  143. // @TODO throw an InvalidRefNameException. We can't do that
  144. // now because this would break the API
  145. throw new JGitInternalException("Invalid ref " + ref
  146. + " specified");
  147. }
  148. final ObjectId commitTree;
  149. if (commitId != null)
  150. commitTree = parseCommit(commitId).getTree();
  151. else
  152. commitTree = null;
  153. if (!filepaths.isEmpty()) {
  154. // reset [commit] -- paths
  155. resetIndexForPaths(commitTree);
  156. setCallable(false);
  157. return repo.getRef(Constants.HEAD);
  158. }
  159. final Ref result;
  160. if (commitId != null) {
  161. // write the ref
  162. final RefUpdate ru = repo.updateRef(Constants.HEAD);
  163. ru.setNewObjectId(commitId);
  164. String refName = Repository.shortenRefName(getRefOrHEAD());
  165. String message = refName + ": updating " + Constants.HEAD; //$NON-NLS-1$
  166. ru.setRefLogMessage(message, false);
  167. if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE)
  168. throw new JGitInternalException(MessageFormat.format(
  169. JGitText.get().cannotLock, ru.getName()));
  170. ObjectId origHead = ru.getOldObjectId();
  171. if (origHead != null)
  172. repo.writeOrigHead(origHead);
  173. result = ru.getRef();
  174. } else {
  175. result = repo.getRef(Constants.HEAD);
  176. }
  177. switch (mode) {
  178. case HARD:
  179. checkoutIndex(commitTree);
  180. break;
  181. case MIXED:
  182. resetIndex(commitTree);
  183. break;
  184. case SOFT: // do nothing, only the ref was changed
  185. break;
  186. case KEEP: // TODO
  187. case MERGE: // TODO
  188. throw new UnsupportedOperationException();
  189. }
  190. if (mode != ResetType.SOFT) {
  191. if (merging)
  192. resetMerge();
  193. else if (cherryPicking)
  194. resetCherryPick();
  195. else if (reverting)
  196. resetRevert();
  197. else if (repo.readSquashCommitMsg() != null)
  198. repo.writeSquashCommitMsg(null /* delete */);
  199. }
  200. setCallable(false);
  201. return result;
  202. } catch (IOException e) {
  203. throw new JGitInternalException(
  204. JGitText.get().exceptionCaughtDuringExecutionOfResetCommand,
  205. e);
  206. }
  207. }
  208. private RevCommit parseCommit(final ObjectId commitId) {
  209. RevCommit commit;
  210. RevWalk rw = new RevWalk(repo);
  211. try {
  212. commit = rw.parseCommit(commitId);
  213. } catch (IOException e) {
  214. throw new JGitInternalException(MessageFormat.format(
  215. JGitText.get().cannotReadCommit, commitId.toString()), e);
  216. } finally {
  217. rw.release();
  218. }
  219. return commit;
  220. }
  221. private ObjectId resolveRefToCommitId() {
  222. try {
  223. return repo.resolve(getRefOrHEAD() + "^{commit}"); //$NON-NLS-1$
  224. } catch (IOException e) {
  225. throw new JGitInternalException(
  226. MessageFormat.format(JGitText.get().cannotRead, getRefOrHEAD()),
  227. e);
  228. }
  229. }
  230. /**
  231. * @param ref
  232. * the ref to reset to, defaults to HEAD if not specified
  233. * @return this instance
  234. */
  235. public ResetCommand setRef(String ref) {
  236. this.ref = ref;
  237. return this;
  238. }
  239. /**
  240. * @param mode
  241. * the mode of the reset command
  242. * @return this instance
  243. */
  244. public ResetCommand setMode(ResetType mode) {
  245. if (!filepaths.isEmpty())
  246. throw new JGitInternalException(MessageFormat.format(
  247. JGitText.get().illegalCombinationOfArguments,
  248. "[--mixed | --soft | --hard]", "<paths>...")); //$NON-NLS-1$
  249. this.mode = mode;
  250. return this;
  251. }
  252. /**
  253. * @param path
  254. * repository-relative path of file/directory to reset (with
  255. * <code>/</code> as separator)
  256. * @return this instance
  257. */
  258. public ResetCommand addPath(String path) {
  259. if (mode != null)
  260. throw new JGitInternalException(MessageFormat.format(
  261. JGitText.get().illegalCombinationOfArguments, "<paths>...",
  262. "[--mixed | --soft | --hard]")); //$NON-NLS-1$
  263. filepaths.add(path);
  264. return this;
  265. }
  266. private String getRefOrHEAD() {
  267. if (ref != null)
  268. return ref;
  269. else
  270. return Constants.HEAD;
  271. }
  272. private void resetIndexForPaths(ObjectId commitTree) {
  273. DirCache dc = null;
  274. try {
  275. dc = repo.lockDirCache();
  276. DirCacheBuilder builder = dc.builder();
  277. final TreeWalk tw = new TreeWalk(repo);
  278. tw.addTree(new DirCacheBuildIterator(builder));
  279. if (commitTree != null)
  280. tw.addTree(commitTree);
  281. else
  282. tw.addTree(new EmptyTreeIterator());
  283. tw.setFilter(PathFilterGroup.createFromStrings(filepaths));
  284. tw.setRecursive(true);
  285. while (tw.next()) {
  286. final CanonicalTreeParser tree = tw.getTree(1,
  287. CanonicalTreeParser.class);
  288. // only keep file in index if it's in the commit
  289. if (tree != null) {
  290. // revert index to commit
  291. DirCacheEntry entry = new DirCacheEntry(tw.getRawPath());
  292. entry.setFileMode(tree.getEntryFileMode());
  293. entry.setObjectId(tree.getEntryObjectId());
  294. builder.add(entry);
  295. }
  296. }
  297. builder.commit();
  298. } catch (IOException e) {
  299. throw new RuntimeException(e);
  300. } finally {
  301. if (dc != null)
  302. dc.unlock();
  303. }
  304. }
  305. private void resetIndex(ObjectId commitTree) throws IOException {
  306. DirCache dc = repo.lockDirCache();
  307. TreeWalk walk = null;
  308. try {
  309. DirCacheBuilder builder = dc.builder();
  310. walk = new TreeWalk(repo);
  311. if (commitTree != null)
  312. walk.addTree(commitTree);
  313. else
  314. walk.addTree(new EmptyTreeIterator());
  315. walk.addTree(new DirCacheIterator(dc));
  316. walk.setRecursive(true);
  317. while (walk.next()) {
  318. AbstractTreeIterator cIter = walk.getTree(0,
  319. AbstractTreeIterator.class);
  320. if (cIter == null) {
  321. // Not in commit, don't add to new index
  322. continue;
  323. }
  324. final DirCacheEntry entry = new DirCacheEntry(walk.getRawPath());
  325. entry.setFileMode(cIter.getEntryFileMode());
  326. entry.setObjectIdFromRaw(cIter.idBuffer(), cIter.idOffset());
  327. DirCacheIterator dcIter = walk.getTree(1,
  328. DirCacheIterator.class);
  329. if (dcIter != null && dcIter.idEqual(cIter)) {
  330. DirCacheEntry indexEntry = dcIter.getDirCacheEntry();
  331. entry.setLastModified(indexEntry.getLastModified());
  332. entry.setLength(indexEntry.getLength());
  333. }
  334. builder.add(entry);
  335. }
  336. builder.commit();
  337. } finally {
  338. dc.unlock();
  339. if (walk != null)
  340. walk.release();
  341. }
  342. }
  343. private void checkoutIndex(ObjectId commitTree) throws IOException,
  344. GitAPIException {
  345. DirCache dc = repo.lockDirCache();
  346. try {
  347. DirCacheCheckout checkout = new DirCacheCheckout(repo, dc,
  348. commitTree);
  349. checkout.setFailOnConflict(false);
  350. try {
  351. checkout.checkout();
  352. } catch (org.eclipse.jgit.errors.CheckoutConflictException cce) {
  353. throw new CheckoutConflictException(checkout.getConflicts(),
  354. cce);
  355. }
  356. } finally {
  357. dc.unlock();
  358. }
  359. }
  360. private void resetMerge() throws IOException {
  361. repo.writeMergeHeads(null);
  362. repo.writeMergeCommitMsg(null);
  363. }
  364. private void resetCherryPick() throws IOException {
  365. repo.writeCherryPickHead(null);
  366. repo.writeMergeCommitMsg(null);
  367. }
  368. private void resetRevert() throws IOException {
  369. repo.writeRevertHead(null);
  370. repo.writeMergeCommitMsg(null);
  371. }
  372. }