Example usage for org.eclipse.jgit.api Git reset

List of usage examples for org.eclipse.jgit.api Git reset

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git reset.

Prototype

public ResetCommand reset() 

Source Link

Document

Return a command object to execute a reset command

Usage

From source file:br.com.riselabs.cotonet.builder.NetworkBuilder.java

License:Open Source License

/**
 * Returns the conflicting files of the given scenario.
 * //from  w  w  w .  ja v  a2s  .  co m
 * @param scenario
 * @return
 * @throws CheckoutConflictException
 * @throws GitAPIException
 */
private List<File> getConflictingFiles(MergeScenario scenario)
        throws CheckoutConflictException, GitAPIException {
    Git git = Git.wrap(getProject().getRepository());
    // this is for the cases of restarting after exception in a conflict
    // scenario analysis
    try {
        git.reset().setRef(scenario.getLeft().getName()).setMode(ResetType.HARD).call();
    } catch (JGitInternalException e) {
        Logger.log(log, "[" + project.getName() + "] JGit Reset Command ended with exception."
                + " Trying external reset command.");
        ExternalGitCommand egit = new ExternalGitCommand();
        try {
            egit.setType(CommandType.RESET).setDirectory(project.getRepository().getDirectory().getParentFile())
                    .call();
        } catch (BlameException e1) {
            Logger.logStackTrace(log, e1);
            return null;
        }
    }

    CheckoutCommand ckoutCmd = git.checkout();
    ckoutCmd.setName(scenario.getLeft().getName());
    ckoutCmd.setStartPoint(scenario.getLeft());
    ckoutCmd.call();

    MergeCommand mergeCmd = git.merge();
    mergeCmd.setCommit(false);
    mergeCmd.setStrategy(MergeStrategy.RECURSIVE);
    mergeCmd.include(scenario.getRight());

    Set<String> conflictingPaths;
    try {
        // dealing with MissingObjectException
        MergeResult mResult = mergeCmd.call();
        // dealing with Ghosts conflicts
        conflictingPaths = mResult.getConflicts().keySet();
    } catch (NullPointerException | JGitInternalException e) {
        StringBuilder sb = new StringBuilder();
        sb.append("[" + project.getName() + ":" + project.getUrl() + "] " + "Skipping merge scenario due to '"
                + e.getMessage() + "'\n");
        sb.append("--> Exception: " + e.getClass());
        sb.append("--> Skipped scenario:\n");
        sb.append("::Base:" + scenario.getBase().getName() + "\n");
        sb.append("::Left:" + scenario.getLeft().getName() + "\n");
        sb.append("::Right:" + scenario.getRight().getName() + "\n");
        Logger.log(log, sb.toString());
        return null;
    }
    List<File> result = new ArrayList<File>();
    for (String path : conflictingPaths) {
        result.add(new File(getProject().getRepository().getDirectory().getParent(), path));
    }
    return result;
}

From source file:com.barchart.jenkins.cascade.PluginScmGit.java

License:BSD License

/**
 * Reset repository state.//w w w .  java2  s. c  om
 */
public static Ref doReset(final File workspace) {
    try {
        final Git git = Git.open(workspace);
        return git.reset().setMode(ResetType.HARD).call();
    } catch (final Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:com.door43.translationstudio.ui.dialogs.BackupDialog.java

private boolean resetToMasterBackup(TargetTranslation targetTranslation) {
    try { // restore state before the pull
        Git git = targetTranslation.getRepo().getGit();
        ResetCommand resetCommand = git.reset();
        resetCommand.setMode(ResetCommand.ResetType.HARD).setRef("backup-master").call();
    } catch (Exception e) {
        e.printStackTrace();/*w  w w . j ava2 s .c om*/
        return false;
    }
    return true;
}

From source file:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java

License:Apache License

/**
 * This method is used to clone repository from github using the URL and branch to local destination folder.
 * //ww w. j a va  2s  .  c  om
 * @param repoURL
 *            repository url to clone.
 * @param branch
 *            specific branch name of the repository to clone
 * @param localEiffelRepoPath
 *            destination path to clone the repo.
 */
private void cloneEiffelRepo(final String repoURL, final String branch, final File localEiffelRepoPath) {
    Git localGitRepo = null;

    // checking for repository exists or not in the localEiffelRepoPath
    try {
        if (!localEiffelRepoPath.exists()) {
            // cloning github repository by using URL and branch name into local
            localGitRepo = Git.cloneRepository().setURI(repoURL).setBranch("master")
                    .setDirectory(localEiffelRepoPath).call();
        } else {
            // If required repository already exists
            localGitRepo = Git.open(localEiffelRepoPath);

            // Reset to normal if uncommitted changes are present
            localGitRepo.reset().call();

            //Checkout to master before pull the changes
            localGitRepo.checkout().setName(EiffelConstants.MASTER).call();

            // To get the latest changes from remote repository.
            localGitRepo.pull().call();
        }

        //checkout to input branch after changes pulled into local
        localGitRepo.checkout().setName(branch).call();

    } catch (Exception e) {
        LOGGER.info(
                "please check proxy settings if proxy enabled update proxy.properties file to clone behind proxy");
        e.printStackTrace();
    }
}

From source file:com.gitblit.servlet.GitServletTest.java

License:Apache License

private void testRefChange(AccessPermission permission, Status expectedCreate, Status expectedDelete,
        Status expectedRewind) throws Exception {

    final String originName = "ticgit.git";
    final String forkName = "refchecks/ticgit.git";
    final String workingCopy = "refchecks/ticgit-wc";

    // lower access restriction on origin repository
    RepositoryModel origin = repositories().getRepositoryModel(originName);
    origin.accessRestriction = AccessRestrictionType.NONE;
    repositories().updateRepositoryModel(origin.name, origin, false);

    UserModel user = getUser();// w  ww.j a  v a 2 s .  co  m
    delete(user);

    CredentialsProvider cp = new UsernamePasswordCredentialsProvider(user.username, user.password);

    // fork from original to a temporary bare repo
    File refChecks = new File(GitBlitSuite.REPOSITORIES, forkName);
    if (refChecks.exists()) {
        FileUtils.delete(refChecks, FileUtils.RECURSIVE);
    }
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(url + "/" + originName);
    clone.setDirectory(refChecks);
    clone.setBare(true);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);
    GitBlitSuite.close(clone.call());

    // elevate repository to clone permission
    RepositoryModel model = repositories().getRepositoryModel(forkName);
    switch (permission) {
    case VIEW:
        model.accessRestriction = AccessRestrictionType.CLONE;
        break;
    case CLONE:
        model.accessRestriction = AccessRestrictionType.CLONE;
        break;
    default:
        model.accessRestriction = AccessRestrictionType.PUSH;
    }
    model.authorizationControl = AuthorizationControl.NAMED;

    // grant user specified
    user.setRepositoryPermission(model.name, permission);

    gitblit().addUser(user);
    repositories().updateRepositoryModel(model.name, model, false);

    // clone temp bare repo to working copy
    File local = new File(GitBlitSuite.REPOSITORIES, workingCopy);
    if (local.exists()) {
        FileUtils.delete(local, FileUtils.RECURSIVE);
    }
    clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/{1}", url, model.name));
    clone.setDirectory(local);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(cp);

    try {
        GitBlitSuite.close(clone.call());
    } catch (GitAPIException e) {
        if (permission.atLeast(AccessPermission.CLONE)) {
            throw e;
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);

            // user does not have clone permission
            assertTrue(e.getMessage(), e.getMessage().contains("not permitted"));
            return;
        }
    }

    Git git = Git.open(local);

    // commit a file and push it
    File file = new File(local, "PUSHCHK");
    OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("push test").call();
    Iterable<PushResult> results = null;
    try {
        results = git.push().setCredentialsProvider(cp).setRemote("origin").call();
    } catch (GitAPIException e) {
        if (permission.atLeast(AccessPermission.PUSH)) {
            throw e;
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);

            // user does not have push permission
            assertTrue(e.getMessage(), e.getMessage().contains("not permitted"));
            GitBlitSuite.close(git);
            return;
        }
    }

    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master");
        Status status = ref.getStatus();
        if (permission.atLeast(AccessPermission.PUSH)) {
            assertTrue("User failed to push commit?! " + status.name(), Status.OK.equals(status));
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);

            assertTrue("User was able to push commit! " + status.name(),
                    Status.REJECTED_OTHER_REASON.equals(status));
            GitBlitSuite.close(git);
            // skip delete test
            return;
        }
    }

    // create a local branch and push the new branch back to the origin
    git.branchCreate().setName("protectme").call();
    RefSpec refSpec = new RefSpec("refs/heads/protectme:refs/heads/protectme");
    results = git.push().setCredentialsProvider(cp).setRefSpecs(refSpec).setRemote("origin").call();
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/protectme");
        Status status = ref.getStatus();
        if (Status.OK.equals(expectedCreate)) {
            assertTrue("User failed to push creation?! " + status.name(), status.equals(expectedCreate));
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);

            assertTrue("User was able to push ref creation! " + status.name(), status.equals(expectedCreate));
            GitBlitSuite.close(git);
            // skip delete test
            return;
        }
    }

    // delete the branch locally
    git.branchDelete().setBranchNames("protectme").call();

    // push a delete ref command
    refSpec = new RefSpec(":refs/heads/protectme");
    results = git.push().setCredentialsProvider(cp).setRefSpecs(refSpec).setRemote("origin").call();
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/protectme");
        Status status = ref.getStatus();
        if (Status.OK.equals(expectedDelete)) {
            assertTrue("User failed to push ref deletion?! " + status.name(), status.equals(Status.OK));
        } else {
            // close serving repository
            GitBlitSuite.close(refChecks);

            assertTrue("User was able to push ref deletion?! " + status.name(), status.equals(expectedDelete));
            GitBlitSuite.close(git);
            // skip rewind test
            return;
        }
    }

    // rewind master by two commits
    git.reset().setRef("HEAD~2").setMode(ResetType.HARD).call();

    // commit a change on this detached HEAD
    file = new File(local, "REWINDCHK");
    os = new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    RevCommit commit = git.commit().setMessage("rewind master and new commit").call();

    // Reset master to our new commit now we our local branch tip is no longer
    // upstream of the remote branch tip.  It is an alternate tip of the branch.
    JGitUtils.setBranchRef(git.getRepository(), "refs/heads/master", commit.getName());

    // Try pushing our new tip to the origin.
    // This requires the server to "rewind" it's master branch and update it
    // to point to our alternate tip.  This leaves the original master tip
    // unreferenced.
    results = git.push().setCredentialsProvider(cp).setRemote("origin").setForce(true).call();
    for (PushResult result : results) {
        RemoteRefUpdate ref = result.getRemoteUpdate("refs/heads/master");
        Status status = ref.getStatus();
        if (Status.OK.equals(expectedRewind)) {
            assertTrue("User failed to rewind master?! " + status.name(), status.equals(expectedRewind));
        } else {
            assertTrue("User was able to rewind master?! " + status.name(), status.equals(expectedRewind));
        }
    }
    GitBlitSuite.close(git);

    // close serving repository
    GitBlitSuite.close(refChecks);

    delete(user);
}

From source file:com.github.rwhogg.git_vcr.App.java

License:Open Source License

/**
 * Clean up the Git repo// w w  w .  j  av  a  2s  .c o m
 * @param git Git to use
 * @param oldCommit Hash of the commit to return to
 */
private static void cleanupGit(Git git, String oldCommit) {
    try {
        git.reset().setMode(ResetType.HARD).call();
        git.checkout().setName(oldCommit).call();
    } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) {
        Util.error("there was an checkout conflict!");
    } catch (GitAPIException e) {
        Util.error("there was an unspecified Git API error!");
    }
    git.close();
}

From source file:com.hazelcast.simulator.utils.jars.GitSupport.java

License:Open Source License

private void resetHard(Git git) throws GitAPIException {
    git.reset().setMode(ResetCommand.ResetType.HARD).call();
}

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 {/* www . j  av  a  2  s  .c  om*/
        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.searchcode.app.jobs.IndexGitRepoJob.java

private RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    try {//from w  ww  .j a  va  2 s . co m
        Repository localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));

        Ref head = localRepository.getRef("HEAD");

        Git git = new Git(localRepository);
        git.reset();
        git.clean();

        PullCommand pullCmd = git.pull();

        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");

        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;

            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");

            ObjectReader reader = localRepository.newObjectReader();

            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);

            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);

            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }

    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

License:Open Source License

/**
 * Update a git repository and return if it has changed and the differences
 *//*from  w  w w  .  j  ava 2s.  co  m*/
public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName,
        String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);

    Repository localRepository = null;
    Git git = null;

    try {
        localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));

        Ref head = localRepository.getRef("HEAD");
        git = new Git(localRepository);

        git.reset();
        git.clean();

        PullCommand pullCmd = git.pull();

        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }

        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");

        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;

            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");

            ObjectReader reader = localRepository.newObjectReader();

            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);

            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);

            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();

            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }

    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(localRepository);
        Singleton.getHelpers().closeQuietly(git);
    }

    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}