ResetCommand.java

  1. /*
  2.  * Copyright (C) 2011-2013, Chris Aniszczyk <caniszczyk@gmail.com> and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */
  10. package org.eclipse.jgit.api;

  11. import java.io.IOException;
  12. import java.text.MessageFormat;
  13. import java.util.Collection;
  14. import java.util.LinkedList;

  15. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  16. import org.eclipse.jgit.api.errors.GitAPIException;
  17. import org.eclipse.jgit.api.errors.JGitInternalException;
  18. import org.eclipse.jgit.dircache.DirCache;
  19. import org.eclipse.jgit.dircache.DirCacheBuildIterator;
  20. import org.eclipse.jgit.dircache.DirCacheBuilder;
  21. import org.eclipse.jgit.dircache.DirCacheCheckout;
  22. import org.eclipse.jgit.dircache.DirCacheEntry;
  23. import org.eclipse.jgit.dircache.DirCacheIterator;
  24. import org.eclipse.jgit.internal.JGitText;
  25. import org.eclipse.jgit.lib.Constants;
  26. import org.eclipse.jgit.lib.NullProgressMonitor;
  27. import org.eclipse.jgit.lib.ObjectId;
  28. import org.eclipse.jgit.lib.ProgressMonitor;
  29. import org.eclipse.jgit.lib.Ref;
  30. import org.eclipse.jgit.lib.RefUpdate;
  31. import org.eclipse.jgit.lib.Repository;
  32. import org.eclipse.jgit.lib.RepositoryState;
  33. import org.eclipse.jgit.revwalk.RevCommit;
  34. import org.eclipse.jgit.revwalk.RevWalk;
  35. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  36. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  37. import org.eclipse.jgit.treewalk.EmptyTreeIterator;
  38. import org.eclipse.jgit.treewalk.TreeWalk;
  39. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;

  40. /**
  41.  * A class used to execute a {@code Reset} command. It has setters for all
  42.  * supported options and arguments of this command and a {@link #call()} method
  43.  * to finally execute the command. Each instance of this class should only be
  44.  * used for one invocation of the command (means: one call to {@link #call()})
  45.  *
  46.  * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-reset.html"
  47.  *      >Git documentation about Reset</a>
  48.  */
  49. public class ResetCommand extends GitCommand<Ref> {

  50.     /**
  51.      * Kind of reset
  52.      */
  53.     public enum ResetType {
  54.         /**
  55.          * Just change the ref, the index and workdir are not changed.
  56.          */
  57.         SOFT,

  58.         /**
  59.          * Change the ref and the index, the workdir is not changed.
  60.          */
  61.         MIXED,

  62.         /**
  63.          * Change the ref, the index and the workdir
  64.          */
  65.         HARD,

  66.         /**
  67.          * Resets the index and updates the files in the working tree that are
  68.          * different between respective commit and HEAD, but keeps those which
  69.          * are different between the index and working tree
  70.          */
  71.         MERGE, // TODO not implemented yet

  72.         /**
  73.          * Change the ref, the index and the workdir that are different between
  74.          * respective commit and HEAD
  75.          */
  76.         KEEP // TODO not implemented yet
  77.     }

  78.     // We need to be able to distinguish whether the caller set the ref
  79.     // explicitly or not, so we apply the default (HEAD) only later.
  80.     private String ref = null;

  81.     private ResetType mode;

  82.     private Collection<String> filepaths = new LinkedList<>();

  83.     private boolean isReflogDisabled;

  84.     private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;

  85.     /**
  86.      * <p>
  87.      * Constructor for ResetCommand.
  88.      * </p>
  89.      *
  90.      * @param repo
  91.      *            the {@link org.eclipse.jgit.lib.Repository}
  92.      */
  93.     public ResetCommand(Repository repo) {
  94.         super(repo);
  95.     }

  96.     /**
  97.      * {@inheritDoc}
  98.      * <p>
  99.      * Executes the {@code Reset} command. Each instance of this class should
  100.      * only be used for one invocation of the command. Don't call this method
  101.      * twice on an instance.
  102.      */
  103.     @Override
  104.     public Ref call() throws GitAPIException, CheckoutConflictException {
  105.         checkCallable();

  106.         try {
  107.             RepositoryState state = repo.getRepositoryState();
  108.             final boolean merging = state.equals(RepositoryState.MERGING)
  109.                     || state.equals(RepositoryState.MERGING_RESOLVED);
  110.             final boolean cherryPicking = state
  111.                     .equals(RepositoryState.CHERRY_PICKING)
  112.                     || state.equals(RepositoryState.CHERRY_PICKING_RESOLVED);
  113.             final boolean reverting = state.equals(RepositoryState.REVERTING)
  114.                     || state.equals(RepositoryState.REVERTING_RESOLVED);

  115.             final ObjectId commitId = resolveRefToCommitId();
  116.             // When ref is explicitly specified, it has to resolve
  117.             if (ref != null && commitId == null) {
  118.                 // @TODO throw an InvalidRefNameException. We can't do that
  119.                 // now because this would break the API
  120.                 throw new JGitInternalException(MessageFormat
  121.                         .format(JGitText.get().invalidRefName, ref));
  122.             }

  123.             final ObjectId commitTree;
  124.             if (commitId != null)
  125.                 commitTree = parseCommit(commitId).getTree();
  126.             else
  127.                 commitTree = null;

  128.             if (!filepaths.isEmpty()) {
  129.                 // reset [commit] -- paths
  130.                 resetIndexForPaths(commitTree);
  131.                 setCallable(false);
  132.                 return repo.exactRef(Constants.HEAD);
  133.             }

  134.             final Ref result;
  135.             if (commitId != null) {
  136.                 // write the ref
  137.                 final RefUpdate ru = repo.updateRef(Constants.HEAD);
  138.                 ru.setNewObjectId(commitId);

  139.                 String refName = Repository.shortenRefName(getRefOrHEAD());
  140.                 if (isReflogDisabled) {
  141.                     ru.disableRefLog();
  142.                 } else {
  143.                     String message = refName + ": updating " + Constants.HEAD; //$NON-NLS-1$
  144.                     ru.setRefLogMessage(message, false);
  145.                 }
  146.                 if (ru.forceUpdate() == RefUpdate.Result.LOCK_FAILURE)
  147.                     throw new JGitInternalException(MessageFormat.format(
  148.                             JGitText.get().cannotLock, ru.getName()));

  149.                 ObjectId origHead = ru.getOldObjectId();
  150.                 if (origHead != null)
  151.                     repo.writeOrigHead(origHead);
  152.             }
  153.             result = repo.exactRef(Constants.HEAD);

  154.             if (mode == null)
  155.                 mode = ResetType.MIXED;

  156.             switch (mode) {
  157.                 case HARD:
  158.                     checkoutIndex(commitTree);
  159.                     break;
  160.                 case MIXED:
  161.                     resetIndex(commitTree);
  162.                     break;
  163.                 case SOFT: // do nothing, only the ref was changed
  164.                     break;
  165.                 case KEEP: // TODO
  166.                 case MERGE: // TODO
  167.                     throw new UnsupportedOperationException();

  168.             }

  169.             if (mode != ResetType.SOFT) {
  170.                 if (merging)
  171.                     resetMerge();
  172.                 else if (cherryPicking)
  173.                     resetCherryPick();
  174.                 else if (reverting)
  175.                     resetRevert();
  176.                 else if (repo.readSquashCommitMsg() != null)
  177.                     repo.writeSquashCommitMsg(null /* delete */);
  178.             }

  179.             setCallable(false);
  180.             return result;
  181.         } catch (IOException e) {
  182.             throw new JGitInternalException(MessageFormat.format(
  183.                     JGitText.get().exceptionCaughtDuringExecutionOfResetCommand,
  184.                     e.getMessage()), e);
  185.         }
  186.     }

  187.     private RevCommit parseCommit(ObjectId commitId) {
  188.         try (RevWalk rw = new RevWalk(repo)) {
  189.             return rw.parseCommit(commitId);
  190.         } catch (IOException e) {
  191.             throw new JGitInternalException(MessageFormat.format(
  192.                     JGitText.get().cannotReadCommit, commitId.toString()), e);
  193.         }
  194.     }

  195.     private ObjectId resolveRefToCommitId() {
  196.         try {
  197.             return repo.resolve(getRefOrHEAD() + "^{commit}"); //$NON-NLS-1$
  198.         } catch (IOException e) {
  199.             throw new JGitInternalException(
  200.                     MessageFormat.format(JGitText.get().cannotRead, getRefOrHEAD()),
  201.                     e);
  202.         }
  203.     }

  204.     /**
  205.      * Set the name of the <code>Ref</code> to reset to
  206.      *
  207.      * @param ref
  208.      *            the ref to reset to, defaults to HEAD if not specified
  209.      * @return this instance
  210.      */
  211.     public ResetCommand setRef(String ref) {
  212.         this.ref = ref;
  213.         return this;
  214.     }

  215.     /**
  216.      * Set the reset mode
  217.      *
  218.      * @param mode
  219.      *            the mode of the reset command
  220.      * @return this instance
  221.      */
  222.     public ResetCommand setMode(ResetType mode) {
  223.         if (!filepaths.isEmpty())
  224.             throw new JGitInternalException(MessageFormat.format(
  225.                     JGitText.get().illegalCombinationOfArguments,
  226.                     "[--mixed | --soft | --hard]", "<paths>...")); //$NON-NLS-1$ //$NON-NLS-2$
  227.         this.mode = mode;
  228.         return this;
  229.     }

  230.     /**
  231.      * Repository relative path of file or directory to reset
  232.      *
  233.      * @param path
  234.      *            repository-relative path of file/directory to reset (with
  235.      *            <code>/</code> as separator)
  236.      * @return this instance
  237.      */
  238.     public ResetCommand addPath(String path) {
  239.         if (mode != null)
  240.             throw new JGitInternalException(MessageFormat.format(
  241.                     JGitText.get().illegalCombinationOfArguments, "<paths>...", //$NON-NLS-1$
  242.                     "[--mixed | --soft | --hard]")); //$NON-NLS-1$
  243.         filepaths.add(path);
  244.         return this;
  245.     }

  246.     /**
  247.      * Whether to disable reflog
  248.      *
  249.      * @param disable
  250.      *            if {@code true} disables writing a reflog entry for this reset
  251.      *            command
  252.      * @return this instance
  253.      * @since 4.5
  254.      */
  255.     public ResetCommand disableRefLog(boolean disable) {
  256.         this.isReflogDisabled = disable;
  257.         return this;
  258.     }

  259.     /**
  260.      * Whether reflog is disabled
  261.      *
  262.      * @return {@code true} if writing reflog is disabled for this reset command
  263.      * @since 4.5
  264.      */
  265.     public boolean isReflogDisabled() {
  266.         return this.isReflogDisabled;
  267.     }

  268.     private String getRefOrHEAD() {
  269.         if (ref != null) {
  270.             return ref;
  271.         }
  272.         return Constants.HEAD;
  273.     }

  274.     /**
  275.      * The progress monitor associated with the reset operation. By default,
  276.      * this is set to <code>NullProgressMonitor</code>
  277.      *
  278.      * @see NullProgressMonitor
  279.      * @param monitor
  280.      *            a {@link org.eclipse.jgit.lib.ProgressMonitor}
  281.      * @return {@code this}
  282.      * @since 4.11
  283.      */
  284.     public ResetCommand setProgressMonitor(ProgressMonitor monitor) {
  285.         if (monitor == null) {
  286.             monitor = NullProgressMonitor.INSTANCE;
  287.         }
  288.         this.monitor = monitor;
  289.         return this;
  290.     }

  291.     private void resetIndexForPaths(ObjectId commitTree) {
  292.         DirCache dc = null;
  293.         try (TreeWalk tw = new TreeWalk(repo)) {
  294.             dc = repo.lockDirCache();
  295.             DirCacheBuilder builder = dc.builder();

  296.             tw.addTree(new DirCacheBuildIterator(builder));
  297.             if (commitTree != null)
  298.                 tw.addTree(commitTree);
  299.             else
  300.                 tw.addTree(new EmptyTreeIterator());
  301.             tw.setFilter(PathFilterGroup.createFromStrings(filepaths));
  302.             tw.setRecursive(true);

  303.             while (tw.next()) {
  304.                 final CanonicalTreeParser tree = tw.getTree(1,
  305.                         CanonicalTreeParser.class);
  306.                 // only keep file in index if it's in the commit
  307.                 if (tree != null) {
  308.                     // revert index to commit
  309.                     DirCacheEntry entry = new DirCacheEntry(tw.getRawPath());
  310.                     entry.setFileMode(tree.getEntryFileMode());
  311.                     entry.setObjectId(tree.getEntryObjectId());
  312.                     builder.add(entry);
  313.                 }
  314.             }

  315.             builder.commit();
  316.         } catch (IOException e) {
  317.             throw new RuntimeException(e);
  318.         } finally {
  319.             if (dc != null)
  320.                 dc.unlock();
  321.         }
  322.     }

  323.     private void resetIndex(ObjectId commitTree) throws IOException {
  324.         DirCache dc = repo.lockDirCache();
  325.         try (TreeWalk walk = new TreeWalk(repo)) {
  326.             DirCacheBuilder builder = dc.builder();

  327.             if (commitTree != null)
  328.                 walk.addTree(commitTree);
  329.             else
  330.                 walk.addTree(new EmptyTreeIterator());
  331.             walk.addTree(new DirCacheIterator(dc));
  332.             walk.setRecursive(true);

  333.             while (walk.next()) {
  334.                 AbstractTreeIterator cIter = walk.getTree(0,
  335.                         AbstractTreeIterator.class);
  336.                 if (cIter == null) {
  337.                     // Not in commit, don't add to new index
  338.                     continue;
  339.                 }

  340.                 final DirCacheEntry entry = new DirCacheEntry(walk.getRawPath());
  341.                 entry.setFileMode(cIter.getEntryFileMode());
  342.                 entry.setObjectIdFromRaw(cIter.idBuffer(), cIter.idOffset());

  343.                 DirCacheIterator dcIter = walk.getTree(1,
  344.                         DirCacheIterator.class);
  345.                 if (dcIter != null && dcIter.idEqual(cIter)) {
  346.                     DirCacheEntry indexEntry = dcIter.getDirCacheEntry();
  347.                     entry.setLastModified(indexEntry.getLastModifiedInstant());
  348.                     entry.setLength(indexEntry.getLength());
  349.                 }

  350.                 builder.add(entry);
  351.             }

  352.             builder.commit();
  353.         } finally {
  354.             dc.unlock();
  355.         }
  356.     }

  357.     private void checkoutIndex(ObjectId commitTree) throws IOException,
  358.             GitAPIException {
  359.         DirCache dc = repo.lockDirCache();
  360.         try {
  361.             DirCacheCheckout checkout = new DirCacheCheckout(repo, dc,
  362.                     commitTree);
  363.             checkout.setFailOnConflict(false);
  364.             checkout.setProgressMonitor(monitor);
  365.             try {
  366.                 checkout.checkout();
  367.             } catch (org.eclipse.jgit.errors.CheckoutConflictException cce) {
  368.                 throw new CheckoutConflictException(checkout.getConflicts(),
  369.                         cce);
  370.             }
  371.         } finally {
  372.             dc.unlock();
  373.         }
  374.     }

  375.     private void resetMerge() throws IOException {
  376.         repo.writeMergeHeads(null);
  377.         repo.writeMergeCommitMsg(null);
  378.     }

  379.     private void resetCherryPick() throws IOException {
  380.         repo.writeCherryPickHead(null);
  381.         repo.writeMergeCommitMsg(null);
  382.     }

  383.     private void resetRevert() throws IOException {
  384.         repo.writeRevertHead(null);
  385.         repo.writeMergeCommitMsg(null);
  386.     }

  387.     /** {@inheritDoc} */
  388.     @SuppressWarnings("nls")
  389.     @Override
  390.     public String toString() {
  391.         return "ResetCommand [repo=" + repo + ", ref=" + ref + ", mode=" + mode
  392.                 + ", isReflogDisabled=" + isReflogDisabled + ", filepaths="
  393.                 + filepaths + "]";
  394.     }

  395. }