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:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

@Override
public Collection<PropertyFileDiff> reset(ProjectVersion project, IProgressMonitor monitor)
        throws TeamProviderException {

    List<PropertyFileDiff> updatedFiles = new ArrayList<PropertyFileDiff>();
    try {// ww w. j a v a2s .  c om
        Repository repository = createRepository(project);
        SubMonitor subMon = SubMonitor.convert(monitor, "Reset", 100);
        Git git = new Git(repository);
        subMon.subTask("Calculating Diff");
        DiffCommand diffCommand = git.diff();
        diffCommand.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(30)));
        diffCommand.setOldTree(prepareTreeParser(repository, "refs/remotes/origin/" + project.getName()));
        diffCommand.setNewTree(null);
        List<DiffEntry> diffs = diffCommand.call();
        for (DiffEntry diffEntry : diffs) {
            checkCanceled(monitor);
            PropertyFileDiff fileDiff = createDiff(diffEntry, monitor);
            revertDiff(fileDiff);
            updatedFiles.add(fileDiff);
        }

        subMon.subTask("Executing Reset");
        ResetCommand reset = git.reset();
        reset.setMode(ResetType.HARD);
        reset.setRef("refs/remotes/origin/" + project.getName());
        reset.call();

        CleanCommand clean = git.clean();
        clean.setCleanDirectories(true);
        Set<String> call = clean.call();
        LOGGER.info("cleaned " + call);

    } catch (IOException e) {
        LOGGER.error("reset failed", e);
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        LOGGER.error("reset failed", e);
        throw new TeamProviderException(e);
    }
    return updatedFiles;
}

From source file:org.jboss.forge.addon.git.GitUtilsImpl.java

License:Open Source License

@Override
public void resetHard(final Git repo, String newBase) throws GitAPIException {
    repo.reset().setMode(ResetCommand.ResetType.HARD).setRef(newBase).call();
}

From source file:org.jboss.forge.git.GitUtils.java

License:Open Source License

public static void resetHard(final Git repo, String newBase) throws GitAPIException {
    repo.reset().setMode(ResetCommand.ResetType.HARD).setRef(newBase).call();
}

From source file:org.kie.workbench.common.migration.MigrationToolTest.java

License:Apache License

private void resetRepoToPreviousDrlCommit(final Git projectRepo) throws GitAPIException {
    final String previousDrlCommitRef = "HEAD~2";

    projectRepo.reset().setMode(ResetCommand.ResetType.HARD).setRef(previousDrlCommitRef).call();
}

From source file:org.kie.workbench.common.services.backend.compiler.impl.utils.JGitUtils.java

License:Apache License

public static Boolean pullAndRebase(final Git git) {
    Boolean result = Boolean.FALSE;
    try {//from w  w w.  j ava 2  s. c  o  m
        git.reset().setMode(ResetCommand.ResetType.HARD).call();
        final RebaseResult rr = git.pull().setRemote(REMOTE).setRebase(Boolean.TRUE).call().getRebaseResult();

        if (rr.getStatus().equals(RebaseResult.Status.UP_TO_DATE)
                || rr.getStatus().equals(RebaseResult.Status.FAST_FORWARD)) {
            result = Boolean.TRUE;
        }
        if (rr.getStatus().equals(RebaseResult.Status.UNCOMMITTED_CHANGES)) {
            PullResult pr = git.pull().call();
            if (pr.isSuccessful()) {
                result = Boolean.TRUE;
            } else {
                result = Boolean.FALSE;
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
    return result;
}

From source file:org.n52.wps.repository.git.GitAlgorithmRepository.java

License:Open Source License

private void rollbackFromFailedMerge(Git git, ObjectId old) throws GitAPIException {
    // old objectId is the one before merge so we should be safe to have the right rollback id
    logger.warn("Doing a `reset --hard {}' from faild merge. Pull and merge manually!", old);
    git.reset().setMode(ResetCommand.ResetType.HARD).setRef(old.toString()).call();
}

From source file:org.ocpsoft.redoculous.model.impl.GitRepository.java

License:Open Source License

@Override
public void initRef(String ref) {
    File repoDir = getRepoDir();//from  ww w. jav  a 2  s  .c  om

    File refDir = getRefDir(ref);
    File refCacheDir = getCachedRefDir(ref);

    ref = resolveRef(ref);

    if (!refDir.exists()) {
        log.info("Creating ref copy [" + getUrl() + "] [" + ref + "] [" + getKey() + "]");
        refDir.mkdirs();
        refCacheDir.mkdirs();
        Git git = null;
        try {
            git = Git.open(repoDir);
            git.reset().setMode(ResetType.HARD).call();
            git.clean().setCleanDirectories(true).call();
            git.checkout().setName(ref).call();

            log.info("Deleting cache for [" + getUrl() + "] [" + ref + "] [" + getKey() + "]");
            Files.delete(refDir, true);
            Files.delete(refCacheDir, true);
            refCacheDir.mkdirs();
            Files.copyDirectory(repoDir, refDir, new FileFilter() {
                @Override
                public boolean accept(File file) {
                    return !(file.getName().equals(".git") || file.getName().equals(".gitignore"));
                }
            });
        } catch (Exception e) {
            if (git != null) {
                git.getRepository().close();
                git = null;
            }
            Files.delete(refDir, true);
            Files.delete(refCacheDir, true);
            throw new RewriteException(
                    "Could checkout ref [" + ref + "] from repository [" + getUrl() + "] [" + getKey() + "].",
                    e);
        } finally {
            if (git != null) {
                git.getRepository().close();
            }
        }
    }
}

From source file:org.ocpsoft.redoculous.model.impl.GitRepository.java

License:Open Source License

@Override
public void update() {
    File repoDir = getRepoDir();//from  w w w. j av a2s. co  m

    Git git = null;
    RedoculousProgressMonitor monitor = new RedoculousProgressMonitor();
    try {
        log.info("Handling update request for [" + getUrl() + "] [" + getKey() + "]");
        git = Git.open(repoDir);

        git.fetch().setTagOpt(TagOpt.FETCH_TAGS).setRemote("origin")
                .setRefSpecs(new RefSpec("+refs/heads/*:refs/remotes/origin/*")).setProgressMonitor(monitor)
                .call();

        git.fetch().setTagOpt(TagOpt.FETCH_TAGS).setRemote("origin")
                .setRefSpecs(new RefSpec("+refs/tags/*:refs/tags/*")).setProgressMonitor(monitor).call();

        git.reset().setMode(ResetType.HARD).setRef("refs/remotes/origin/" + git.getRepository().getBranch())
                .call();

        git.clean().setCleanDirectories(true).call();

        Files.delete(getRefsDir(), true);
        Files.delete(getCacheDir(), true);
    } catch (Exception e) {
        throw new RuntimeException("Could not update repository [" + getUrl() + "] [" + getKey() + "]", e);
    } finally {
        if (git != null)
            git.getRepository().close();
    }
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepository.java

License:Apache License

private Ref resetHard(Git git, String label, String ref) {
    ResetCommand reset = git.reset();
    reset.setRef(ref);//from  w  w  w  .j a v  a 2  s.  c  o m
    reset.setMode(ResetType.HARD);
    try {
        Ref resetRef = reset.call();
        if (resetRef != null) {
            this.logger.info("Reset label " + label + " to version " + resetRef.getObjectId());
        }
        return resetRef;
    } catch (Exception ex) {
        String message = "Could not reset to remote for " + label + " (current ref=" + ref + "), remote: "
                + git.getRepository().getConfig().getString("remote", "origin", "url");
        warn(message, ex);
        return null;
    }
}

From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryIntegrationTests.java

License:Apache License

/**
 * Tests a special use case where the remote repository has been updated with a forced
 * push conflicting with the local repo of the Config Server. The Config Server has to
 * reset hard on the new reference because a simple pull operation could result in a
 * conflicting local repository./*w  w  w .  j  ava 2s .  c om*/
 */
@Test
public void pullDirtyRepo() throws Exception {
    ConfigServerTestUtils.prepareLocalRepo();
    String uri = ConfigServerTestUtils.copyLocalRepo("config-copy");

    // Create a remote bare repository.
    Repository remote = ConfigServerTestUtils.prepareBareRemote();

    Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile());
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", remote.getDirectory().getAbsolutePath());
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.save();

    // Pushes the raw branch to remote repository.
    git.push().call();

    String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator().next().getName();

    this.context = new SpringApplicationBuilder(TestConfiguration.class).web(false)
            .run("--spring.cloud.config.server.git.uri=" + uri);

    JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class);

    // Fetches the repository for the first time.
    SearchPathLocator.Locations locations = repository.getLocations("bar", "test", "raw");
    assertEquals(locations.getVersion(), commitToRevertBeforePull);

    // Resets to the original commit.
    git.reset().setMode(ResetType.HARD).setRef("master").call();

    // Generate a conflicting commit who will be forced on the origin.
    Path applicationFilePath = Paths.get(ResourceUtils.getFile(uri).getAbsoluteFile() + "/application.yml");

    Files.write(applicationFilePath, Arrays.asList("info:", "  foo: bar", "raw: false"), StandardCharsets.UTF_8,
            StandardOpenOption.TRUNCATE_EXISTING);
    git.add().addFilepattern(".").call();
    git.commit().setMessage("Conflicting commit.").call();
    git.push().setForce(true).call();
    String conflictingCommit = git.log().setMaxCount(1).call().iterator().next().getName();

    // Reset to the raw branch.
    git.reset().setMode(ResetType.HARD).setRef(commitToRevertBeforePull).call();

    // Triggers the repository refresh.
    locations = repository.getLocations("bar", "test", "raw");
    assertEquals(locations.getVersion(), conflictingCommit);

    assertTrue("Local repository is not cleaned after retrieving resources.", git.status().call().isClean());
}