Example usage for org.eclipse.jgit.api ResetCommand call

List of usage examples for org.eclipse.jgit.api ResetCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api ResetCommand call.

Prototype

@Override
public Ref call() throws GitAPIException, CheckoutConflictException 

Source Link

Document

Executes the Reset command.

Usage

From source file:com.genuitec.org.eclipse.egit.core.op.ResetOperation.java

License:Open Source License

private void reset(IProgressMonitor monitor) throws CoreException {
    monitor.beginTask(NLS.bind(CoreText.ResetOperation_performingReset, type.toString().toLowerCase(), refName),
            2);/* w  ww.  java 2 s. com*/

    IProject[] validProjects = null;
    if (type == ResetType.HARD)
        validProjects = ProjectUtil.getValidOpenProjects(repository);

    ResetCommand reset = Git.wrap(repository).reset();
    reset.setMode(type);
    reset.setRef(refName);
    try {
        reset.call();
    } catch (GitAPIException e) {
        throw new TeamException(e.getLocalizedMessage(), e.getCause());
    }
    monitor.worked(1);

    // only refresh if working tree changes
    if (type == ResetType.HARD)
        ProjectUtil.refreshValidProjects(validProjects, !closeRemovedProjects,
                new SubProgressMonitor(monitor, 1));

    monitor.done();
}

From source file:com.mpdeimos.ct_tests.looper.GitRevisionLooper.java

License:Apache License

/** {@inheritDoc} */
@Override//  w w w .  j av a  2  s. c o m
public RevIterator iterator() {

    return new RevIterator() {
        int index = commits.size();

        @Override
        public void remove() {
            throw new IllegalStateException();
        }

        @Override
        public RevisionInfo next() {
            final Commit commit = commits.get(--index);

            return new RevisionInfo(commits.size() - index - 1, commit.getId(), commit, root) {
                /** {@inheritDoc} 
                 * @throws ConQATException */
                @Override
                public File getPath() throws ConQATException {
                    CheckoutCommand checkout = new CheckoutCommand(repository) {
                        /**/};
                    checkout.setName(commit.getId());
                    //checkout.setForce(true);
                    try {
                        checkout.call();
                    } catch (Exception e) {
                        getLogger().error(e);
                        ResetCommand reset = new ResetCommand(repository) {
                            /**/};
                        reset.setMode(ResetType.HARD);
                        reset.setRef(commit.getId());
                        try {
                            reset.call();
                            CheckoutCommand checkout2 = new CheckoutCommand(repository) {
                                /**/};
                            checkout2.setName(commit.getId());
                            //                        checkout2.setForce(true);
                            checkout2.call();
                        } catch (Exception e1) {
                            getLogger().error(e1);
                            throw new ConQATException(e1);
                        }
                    }
                    return super.getPath();
                }
            };
        }

        @Override
        public boolean hasNext() {
            return index > 0;
        }

        @Override
        public Commit peekCommit() {
            if (!hasNext())
                throw new IllegalStateException();

            return commits.get(index - 1);
        }
    };
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

private void resetLocalCommit(File appDir, boolean gitExists, Exception e) throws PhrescoException {
    try {/* w  ww.  ja  v  a 2s .  c  o m*/
        if (gitExists == true && e.getLocalizedMessage().contains("not authorized")) {
            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            Repository repository = builder.setGitDir(appDir).readEnvironment().findGitDir().build();
            Git git = new Git(repository);

            InitCommand initCommand = Git.init();
            initCommand.setDirectory(appDir);
            git = initCommand.call();

            ResetCommand reset = git.reset();
            ResetType mode = ResetType.SOFT;
            reset.setRef("HEAD~1").setMode(mode);
            reset.call();

            git.getRepository().close();
        }
    } catch (Exception pe) {
        new PhrescoException(pe);
    }
}

From source file:com.sap.dirigible.ide.jgit.connector.JGitConnector.java

License:Open Source License

/**
 * /*from w  w  w.  j  av  a 2  s .co  m*/
 * Hard reset the repository. Makes the working directory and staging index
 * content to exactly match the Git repository.
 * 
 * @throws CheckoutConflictException
 * @throws GitAPIException
 */
public void hardReset() throws CheckoutConflictException, GitAPIException {
    ResetCommand resetCommand = git.reset();
    resetCommand.setMode(ResetType.HARD);
    resetCommand.call();
}

From source file:com.verigreen.jgit.JGitOperator.java

License:Apache License

public void reset(String refToResetTo) {

    ResetCommand command = _git.reset();
    command.setRef(refToResetTo);//from w  w w .  jav  a 2  s . c o m
    command.setMode(ResetType.HARD);
    try {
        command.call();
    } catch (Throwable e) {
        throw new RuntimeException(String.format("Failed to reset to [%s]", refToResetTo), e);
    }
}

From source file:eu.numberfour.n4js.utils.git.GitUtils.java

License:Open Source License

/**
 * Hard resets the {@code HEAD} of the reference in the locally cloned Git repository. If the repository does not
 * exists yet at the given local clone path, then it also clones it, iff the {@code cloneIfMissing} argument is
 * {@code true}.//from ww w  .  j  a  v  a 2s .c  o m
 *
 * @param remoteUri
 *            the URI of the remote repository. Could be omitted if the {@code cloneIfMissing} is {@code false}.
 * @param localClonePath
 *            the local path of the cloned repository.
 * @param branch
 *            the name of the branch to reset the {@code HEAD} pointer.
 * @param cloneIfMissing
 *            {@code true} if the repository has to be cloned in case if its absence.
 */
public static void hardReset(final String remoteUri, final Path localClonePath, final String branch,
        final boolean cloneIfMissing) {

    LOGGER.info("Performing hard reset... [Local repository: " + localClonePath + ", remote URI: " + remoteUri
            + ", branch: " + branch + "]");

    checkNotNull(localClonePath, "localClonePath");
    if (cloneIfMissing) {
        checkNotNull(remoteUri, "remoteUri");
        clone(remoteUri, localClonePath, branch);
    }

    try (final Git git = open(localClonePath.toFile())) {
        if (!branch.equals(git.getRepository().getBranch())) {
            LOGGER.info("Current branch is: '" + git.getRepository().getBranch() + "'.");
            LOGGER.info("Switching to desired '" + branch + "' branch...");
            git.pull().setProgressMonitor(createMonitor()).call();
            final Iterable<Ref> localBranchRefs = git.branchList().call();
            final boolean createLocalBranch = !from(localBranchRefs).transform(ref -> ref.getName()).toSet()
                    .contains(branch);
            LOGGER.info("Creating local branch '" + branch + "'? --> " + (createLocalBranch ? "yes" : "no"));
            git.checkout().setCreateBranch(createLocalBranch).setName(branch)
                    .setStartPoint(R_REMOTES + "origin/" + branch).call();
            checkState(branch.equals(git.getRepository().getBranch()),
                    "Error when checking out '" + branch + "' branch.");
            LOGGER.info("Switched to '" + git.getRepository().getBranch() + "' branch.");
            git.pull().setProgressMonitor(createMonitor()).call();
        }
        LOGGER.info("Hard resetting local repository HEAD of the '" + branch + "' in '" + remoteUri + "'...");
        LOGGER.info("Local repository location: " + localClonePath + ".");
        final ResetCommand resetCommand = git.reset().setMode(HARD).setRef(HEAD);
        final Ref ref = resetCommand.call();
        LOGGER.info("Repository content has been successfully reset to '" + ref + "'.");
        final Collection<String> deletedFiles = git.clean().setCleanDirectories(true).call();
        LOGGER.info("Cleaned up " + deletedFiles.size() + " files:\n" + Joiner.on(",\n").join(deletedFiles));
    } catch (final RepositoryNotFoundException e) {
        if (cloneIfMissing) {
            Throwables.propagate(e);
        } else {
            final String message = "Git repository does not exist at " + localClonePath
                    + ". Git repository should be cloned manually.";
            throw new RuntimeException(message, e);
        }
    } catch (final Exception e) {
        LOGGER.error("Error when trying to hard reset to HEAD on '" + branch + "' branch in " + localClonePath
                + " repository.");
        Throwables.propagate(e);
    }
}

From source file:fr.treeptik.cloudunit.utils.GitUtils.java

License:Open Source License

/**
 * this method is associate with listGitTagsOfApplication() method
 * which list all tags with index, this is this index which must pass as parammeter of this method
 *
 * @param application//from   w w  w.j a v  a  2  s .  c om
 * @param indexChosen
 * @param dockerManagerAddress
 * @param containerGitAddress
 * @return
 * @throws InvalidRemoteException
 * @throws TransportException
 * @throws GitAPIException
 * @throws IOException
 */
public static List<String> resetOnChosenGitTag(Application application, int indexChosen,
        String dockerManagerAddress, String containerGitAddress)
        throws InvalidRemoteException, TransportException, GitAPIException, IOException {
    User user = application.getUser();
    String sshPort = application.getServers().get(0).getSshPort();
    String password = user.getPassword();
    String userNameGit = user.getLogin();
    String dockerManagerIP = dockerManagerAddress.substring(0, dockerManagerAddress.length() - 5);
    String remoteRepository = "ssh://" + userNameGit + "@" + dockerManagerIP + ":" + sshPort
            + containerGitAddress;
    File gitworkDir = Files.createTempDirectory("clone").toFile();
    CloneCommand clone = Git.cloneRepository();
    clone.setDirectory(gitworkDir);

    CredentialsProvider credentialsProvider = configCredentialsForGit(userNameGit, password);
    clone.setCredentialsProvider(credentialsProvider);
    clone.setURI(remoteRepository);
    Git git = clone.call();

    ListTagCommand listTagCommand = git.tagList();
    List<Ref> listRefs = listTagCommand.call();

    Ref ref = listRefs.get(indexChosen);

    ResetCommand resetCommand = git.reset();
    resetCommand.setMode(ResetType.HARD);
    resetCommand.setRef(ref.getName());
    resetCommand.call();

    PushCommand pushCommand = git.push();
    pushCommand.setCredentialsProvider(credentialsProvider);
    pushCommand.setForce(true);

    List<PushResult> listPushResults = (List<PushResult>) pushCommand.call();
    List<String> listPushResultsMessages = new ArrayList<>();
    for (PushResult pushResult : listPushResults) {
        listPushResultsMessages.add(pushResult.getMessages());
    }
    FilesUtils.deleteDirectory(gitworkDir);
    return listPushResultsMessages;
}

From source file:git_manager.tool.GitOperations.java

License:Open Source License

public void resetHard() {
    ResetCommand reset = git.reset();
    reset.setRef(Constants.HEAD);/*from   w ww  . j  a va 2 s .c om*/
    //      reset.addPath(".");
    reset.setMode(ResetType.HARD);
    try {
        // Though this should actually have GitManager.frame as the parent, I think 
        // having editor as the parent is far more convenient, since I observe that I generally 
        // tend to keep tool window at the corner and the processing IDE in the centre, 
        // and prefer the dialog box displaying at the center... I think...
        int x = Messages.showYesNoQuestion(editor, "Reset sketch to previous commit?",
                "Are you sure you want to reset the entire skecthbook to<br>the exact state it was in the previous commit?",
                "All changes made since then will be permanently lost.");
        if (x == JOptionPane.YES_OPTION) {
            x = Messages.showYesNoQuestion(editor, "Really reset sketch to previous commit?",
                    "Are you absolutely, positively sure you want to reset the entire<br>skecthbook to the exact state it was in the previous commit?",
                    "All changes made since then will be permanently lost, and even<br>git can't recover them.");
            if (x == JOptionPane.YES_OPTION) {
                reset.call();
                System.out
                        .println("Hard reset completed. Sketch is now exactly like the last snapshot/commit.");
            }
        }
    } catch (CheckoutConflictException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }
}

From source file:org.ajoberstar.gradle.git.tasks.GitReset.java

License:Apache License

/**
 * Reset the changes as configured.//from  w ww  .  j a  v  a 2  s  . c o m
 */
@TaskAction
public void reset() {
    ResetCommand cmd = getGit().reset();
    cmd.setRef(getRef());
    cmd.setMode(getResetType());

    List<String> pathsToReset = getPaths();
    for (String path : pathsToReset) {
        cmd.addPath(path);
    }

    try {
        cmd.call();
    } catch (CheckoutConflictException e) {
        throw new GradleException("The working tree changes conflict with the specified commit.", e);
    } catch (GitAPIException e) {
        throw new GradleException("Problem with reset.", e);
    }
    //TODO add progress monitor to log progress to Gradle status bar
}

From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java

License:Apache License

private void resetToRemoteHead(RepositoryContext gitRepoCtx, List<String> paths) {

    ResetCommand resetCmd = gitRepoCtx.getGit().reset();

    // reset type is HARD, to remote master branch
    resetCmd.setMode(ResetCommand.ResetType.HARD).setRef(
            GitDeploymentSynchronizerConstants.ORIGIN + "/" + GitDeploymentSynchronizerConstants.MASTER);

    // add paths//from  ww w  . j av  a 2s . co m
    for (String path : paths) {
        resetCmd.addPath(path);
        if (log.isDebugEnabled()) {
            log.debug("Added the file path " + path + " to reset");
        }
    }

    try {
        resetCmd.call();
        log.info("Reset the local branch to origin master successfully");

    } catch (GitAPIException e) {
        log.error("Reset to origin master failed", e);
    }

}