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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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.NullProgressMonitor;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.ProgressMonitor;
  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.EmptyTreeIterator;
  71. import org.eclipse.jgit.treewalk.TreeWalk;
  72. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  73. /**
  74. * A class used to execute a {@code Reset} command. It has setters for all
  75. * supported options and arguments of this command and a {@link #call()} method
  76. * to finally execute the command. Each instance of this class should only be
  77. * used for one invocation of the command (means: one call to {@link #call()})
  78. *
  79. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-reset.html"
  80. * >Git documentation about Reset</a>
  81. */
  82. public class ResetCommand extends GitCommand<Ref> {
  83. /**
  84. * Kind of reset
  85. */
  86. public enum ResetType {
  87. /**
  88. * Just change the ref, the index and workdir are not changed.
  89. */
  90. SOFT,
  91. /**
  92. * Change the ref and the index, the workdir is not changed.
  93. */
  94. MIXED,
  95. /**
  96. * Change the ref, the index and the workdir
  97. */
  98. HARD,
  99. /**
  100. * Resets the index and updates the files in the working tree that are
  101. * different between respective commit and HEAD, but keeps those which
  102. * are different between the index and working tree
  103. */
  104. MERGE, // TODO not implemented yet
  105. /**
  106. * Change the ref, the index and the workdir that are different between
  107. * respective commit and HEAD
  108. */
  109. KEEP // TODO not implemented yet
  110. }
  111. // We need to be able to distinguish whether the caller set the ref
  112. // explicitly or not, so we apply the default (HEAD) only later.
  113. private String ref = null;
  114. private ResetType mode;
  115. private Collection<String> filepaths = new LinkedList<>();
  116. private boolean isReflogDisabled;
  117. private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
  118. /**
  119. * <p>
  120. * Constructor for ResetCommand.
  121. * </p>
  122. *
  123. * @param repo
  124. * the {@link org.eclipse.jgit.lib.Repository}
  125. */
  126. public ResetCommand(Repository repo) {
  127. super(repo);
  128. }
  129. /**
  130. * {@inheritDoc}
  131. * <p>
  132. * Executes the {@code Reset} command. Each instance of this class should
  133. * only be used for one invocation of the command. Don't call this method
  134. * twice on an instance.
  135. */
  136. @Override
  137. public Ref call() throws GitAPIException, CheckoutConflictException {
  138. checkCallable();
  139. try {
  140. RepositoryState state = repo.getRepositoryState();
  141. final boolean merging = state.equals(RepositoryState.MERGING)
  142. || state.equals(RepositoryState.MERGING_RESOLVED);
  143. final boolean cherryPicking = state
  144. .equals(RepositoryState.CHERRY_PICKING)
  145. || state.equals(RepositoryState.CHERRY_PICKING_RESOLVED);
  146. final boolean reverting = state.equals(RepositoryState.REVERTING)
  147. || state.equals(RepositoryState.REVERTING_RESOLVED);
  148. final ObjectId commitId = resolveRefToCommitId();
  149. // When ref is explicitly specified, it has to resolve
  150. if (ref != null && commitId == null) {
  151. // @TODO throw an InvalidRefNameException. We can't do that
  152. // now because this would break the API
  153. throw new JGitInternalException(MessageFormat
  154. .format(JGitText.get().invalidRefName, ref));
  155. }
  156. final ObjectId commitTree;
  157. if (commitId != null)
  158. commitTree = parseCommit(commitId).getTree();
  159. else
  160. commitTree = null;
  161. if (!filepaths.isEmpty()) {
  162. // reset [commit] -- paths
  163. resetIndexForPaths(commitTree);
  164. setCallable(false);
  165. return repo.exactRef(Constants.HEAD);
  166. }
  167. final Ref result;
  168. if (commitId != null) {
  169. // write the ref
  170. final RefUpdate ru = repo.updateRef(Constants.HEAD);
  171. ru.setNewObjectId(commitId);
  172. String refName = Repository.shortenRefName(getRefOrHEAD());
  173. if (isReflogDisabled) {
  174. ru.disableRefLog();
  175. } else {
  176. String message = refName + ": updating " + Constants.HEAD; //$NON-NLS-1$
  177. ru.setRefLogMessage(message, false);
  178. }
  179. if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE)
  180. throw new JGitInternalException(MessageFormat.format(
  181. JGitText.get().cannotLock, ru.getName()));
  182. ObjectId origHead = ru.getOldObjectId();
  183. if (origHead != null)
  184. repo.writeOrigHead(origHead);
  185. }
  186. result = repo.exactRef(Constants.HEAD);
  187. if (mode == null)
  188. mode = ResetType.MIXED;
  189. switch (mode) {
  190. case HARD:
  191. checkoutIndex(commitTree);
  192. break;
  193. case MIXED:
  194. resetIndex(commitTree);
  195. break;
  196. case SOFT: // do nothing, only the ref was changed
  197. break;
  198. case KEEP: // TODO
  199. case MERGE: // TODO
  200. throw new UnsupportedOperationException();
  201. }
  202. if (mode != ResetType.SOFT) {
  203. if (merging)
  204. resetMerge();
  205. else if (cherryPicking)
  206. resetCherryPick();
  207. else if (reverting)
  208. resetRevert();
  209. else if (repo.readSquashCommitMsg() != null)
  210. repo.writeSquashCommitMsg(null /* delete */);
  211. }
  212. setCallable(false);
  213. return result;
  214. } catch (IOException e) {
  215. throw new JGitInternalException(MessageFormat.format(
  216. JGitText.get().exceptionCaughtDuringExecutionOfResetCommand,
  217. e.getMessage()), e);
  218. }
  219. }
  220. private RevCommit parseCommit(ObjectId commitId) {
  221. try (RevWalk rw = new RevWalk(repo)) {
  222. return rw.parseCommit(commitId);
  223. } catch (IOException e) {
  224. throw new JGitInternalException(MessageFormat.format(
  225. JGitText.get().cannotReadCommit, commitId.toString()), e);
  226. }
  227. }
  228. private ObjectId resolveRefToCommitId() {
  229. try {
  230. return repo.resolve(getRefOrHEAD() + "^{commit}"); //$NON-NLS-1$
  231. } catch (IOException e) {
  232. throw new JGitInternalException(
  233. MessageFormat.format(JGitText.get().cannotRead, getRefOrHEAD()),
  234. e);
  235. }
  236. }
  237. /**
  238. * Set the name of the <code>Ref</code> to reset to
  239. *
  240. * @param ref
  241. * the ref to reset to, defaults to HEAD if not specified
  242. * @return this instance
  243. */
  244. public ResetCommand setRef(String ref) {
  245. this.ref = ref;
  246. return this;
  247. }
  248. /**
  249. * Set the reset mode
  250. *
  251. * @param mode
  252. * the mode of the reset command
  253. * @return this instance
  254. */
  255. public ResetCommand setMode(ResetType mode) {
  256. if (!filepaths.isEmpty())
  257. throw new JGitInternalException(MessageFormat.format(
  258. JGitText.get().illegalCombinationOfArguments,
  259. "[--mixed | --soft | --hard]", "<paths>...")); //$NON-NLS-1$ //$NON-NLS-2$
  260. this.mode = mode;
  261. return this;
  262. }
  263. /**
  264. * Repository relative path of file or directory to reset
  265. *
  266. * @param path
  267. * repository-relative path of file/directory to reset (with
  268. * <code>/</code> as separator)
  269. * @return this instance
  270. */
  271. public ResetCommand addPath(String path) {
  272. if (mode != null)
  273. throw new JGitInternalException(MessageFormat.format(
  274. JGitText.get().illegalCombinationOfArguments, "<paths>...", //$NON-NLS-1$
  275. "[--mixed | --soft | --hard]")); //$NON-NLS-1$
  276. filepaths.add(path);
  277. return this;
  278. }
  279. /**
  280. * Whether to disable reflog
  281. *
  282. * @param disable
  283. * if {@code true} disables writing a reflog entry for this reset
  284. * command
  285. * @return this instance
  286. * @since 4.5
  287. */
  288. public ResetCommand disableRefLog(boolean disable) {
  289. this.isReflogDisabled = disable;
  290. return this;
  291. }
  292. /**
  293. * Whether reflog is disabled
  294. *
  295. * @return {@code true} if writing reflog is disabled for this reset command
  296. * @since 4.5
  297. */
  298. public boolean isReflogDisabled() {
  299. return this.isReflogDisabled;
  300. }
  301. private String getRefOrHEAD() {
  302. if (ref != null)
  303. return ref;
  304. else
  305. return Constants.HEAD;
  306. }
  307. /**
  308. * The progress monitor associated with the reset operation. By default,
  309. * this is set to <code>NullProgressMonitor</code>
  310. *
  311. * @see NullProgressMonitor
  312. * @param monitor
  313. * a {@link org.eclipse.jgit.lib.ProgressMonitor}
  314. * @return {@code this}
  315. * @since 4.11
  316. */
  317. public ResetCommand setProgressMonitor(ProgressMonitor monitor) {
  318. if (monitor == null) {
  319. monitor = NullProgressMonitor.INSTANCE;
  320. }
  321. this.monitor = monitor;
  322. return this;
  323. }
  324. private void resetIndexForPaths(ObjectId commitTree) {
  325. DirCache dc = null;
  326. try (TreeWalk tw = new TreeWalk(repo)) {
  327. dc = repo.lockDirCache();
  328. DirCacheBuilder builder = dc.builder();
  329. tw.addTree(new DirCacheBuildIterator(builder));
  330. if (commitTree != null)
  331. tw.addTree(commitTree);
  332. else
  333. tw.addTree(new EmptyTreeIterator());
  334. tw.setFilter(PathFilterGroup.createFromStrings(filepaths));
  335. tw.setRecursive(true);
  336. while (tw.next()) {
  337. final CanonicalTreeParser tree = tw.getTree(1,
  338. CanonicalTreeParser.class);
  339. // only keep file in index if it's in the commit
  340. if (tree != null) {
  341. // revert index to commit
  342. DirCacheEntry entry = new DirCacheEntry(tw.getRawPath());
  343. entry.setFileMode(tree.getEntryFileMode());
  344. entry.setObjectId(tree.getEntryObjectId());
  345. builder.add(entry);
  346. }
  347. }
  348. builder.commit();
  349. } catch (IOException e) {
  350. throw new RuntimeException(e);
  351. } finally {
  352. if (dc != null)
  353. dc.unlock();
  354. }
  355. }
  356. private void resetIndex(ObjectId commitTree) throws IOException {
  357. DirCache dc = repo.lockDirCache();
  358. try (TreeWalk walk = new TreeWalk(repo)) {
  359. DirCacheBuilder builder = dc.builder();
  360. if (commitTree != null)
  361. walk.addTree(commitTree);
  362. else
  363. walk.addTree(new EmptyTreeIterator());
  364. walk.addTree(new DirCacheIterator(dc));
  365. walk.setRecursive(true);
  366. while (walk.next()) {
  367. AbstractTreeIterator cIter = walk.getTree(0,
  368. AbstractTreeIterator.class);
  369. if (cIter == null) {
  370. // Not in commit, don't add to new index
  371. continue;
  372. }
  373. final DirCacheEntry entry = new DirCacheEntry(walk.getRawPath());
  374. entry.setFileMode(cIter.getEntryFileMode());
  375. entry.setObjectIdFromRaw(cIter.idBuffer(), cIter.idOffset());
  376. DirCacheIterator dcIter = walk.getTree(1,
  377. DirCacheIterator.class);
  378. if (dcIter != null && dcIter.idEqual(cIter)) {
  379. DirCacheEntry indexEntry = dcIter.getDirCacheEntry();
  380. entry.setLastModified(indexEntry.getLastModifiedInstant());
  381. entry.setLength(indexEntry.getLength());
  382. }
  383. builder.add(entry);
  384. }
  385. builder.commit();
  386. } finally {
  387. dc.unlock();
  388. }
  389. }
  390. private void checkoutIndex(ObjectId commitTree) throws IOException,
  391. GitAPIException {
  392. DirCache dc = repo.lockDirCache();
  393. try {
  394. DirCacheCheckout checkout = new DirCacheCheckout(repo, dc,
  395. commitTree);
  396. checkout.setFailOnConflict(false);
  397. checkout.setProgressMonitor(monitor);
  398. try {
  399. checkout.checkout();
  400. } catch (org.eclipse.jgit.errors.CheckoutConflictException cce) {
  401. throw new CheckoutConflictException(checkout.getConflicts(),
  402. cce);
  403. }
  404. } finally {
  405. dc.unlock();
  406. }
  407. }
  408. private void resetMerge() throws IOException {
  409. repo.writeMergeHeads(null);
  410. repo.writeMergeCommitMsg(null);
  411. }
  412. private void resetCherryPick() throws IOException {
  413. repo.writeCherryPickHead(null);
  414. repo.writeMergeCommitMsg(null);
  415. }
  416. private void resetRevert() throws IOException {
  417. repo.writeRevertHead(null);
  418. repo.writeMergeCommitMsg(null);
  419. }
  420. /** {@inheritDoc} */
  421. @SuppressWarnings("nls")
  422. @Override
  423. public String toString() {
  424. return "ResetCommand [repo=" + repo + ", ref=" + ref + ", mode=" + mode
  425. + ", isReflogDisabled=" + isReflogDisabled + ", filepaths="
  426. + filepaths + "]";
  427. }
  428. }