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:io.fabric8.itests.smoke.embedded.RemoteGitRepositoryTest.java

License:Apache License

/** 
 * Test that the remote repo can diverge in a non-conflicting way
 * We rebase local canges on to of remote changes in case of non-fast-forward pull
 *///from   ww w  . j  av a2s  .co m
@Test
public void rebaseOnFailedPull() throws Exception {

    final String versionId = "1.0";
    Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfE"));
    Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfF"));

    checkoutRequiredBranch(versionId);
    RevCommit head = CommitUtils.getHead(git.getRepository());

    ProfileBuilder pbuilder = ProfileBuilder.Factory.create(versionId, "prfE");
    profileRegistry.createProfile(pbuilder.getProfile());
    Assert.assertTrue(remoteProfileExists("1.0", "prfE"));

    // Remove the last commit from the remote repository
    git.reset().setMode(ResetType.HARD).setRef(head.getName()).call();
    Assert.assertFalse(remoteProfileExists("1.0", "prfE"));

    createProfileRemote(versionId, "prfF", null);
    Assert.assertTrue(remoteProfileExists("1.0", "prfF"));

    GitOperation<Profile> gitop = new GitOperation<Profile>() {
        public Profile call(Git git, GitContext context) throws Exception {
            return profileRegistry.getProfile(versionId, "prfF");
        }
    };
    GitContext context = new GitContext().requirePull();
    gitDataStore.gitOperation(context, gitop, null);

    Assert.assertTrue(profileRegistry.hasProfile(versionId, "prfE"));
    Assert.assertTrue(profileRegistry.hasProfile(versionId, "prfF"));

    profileRegistry.deleteProfile(versionId, "prfE");
    profileRegistry.deleteProfile(versionId, "prfF");
    Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfE"));
    Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfF"));
}

From source file:io.fabric8.itests.smoke.embedded.RemoteGitRepositoryTest.java

License:Apache License

/**
 * Test that repomote content overrides local content in case of a conflicting pull
 *///from  w  w  w.ja va2s  . c o  m
@Test
public void rejectOnFailedPull() throws Exception {

    final String versionId = "1.0";
    Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfG"));

    checkoutRequiredBranch(versionId);
    RevCommit head = CommitUtils.getHead(git.getRepository());

    ProfileBuilder pbuilder = ProfileBuilder.Factory.create(versionId, "prfG");
    profileRegistry.createProfile(pbuilder.addAttribute("foo", "aaa").getProfile());
    Profile profile = profileRegistry.getRequiredProfile(versionId, "prfG");
    Assert.assertEquals("aaa", profile.getAttributes().get("foo"));

    // Remove the last commit from the remote repository
    git.reset().setMode(ResetType.HARD).setRef(head.getName()).call();
    Assert.assertFalse(remoteProfileExists("1.0", "prfG"));

    createProfileRemote(versionId, "prfG", Collections.singletonMap("foo", "bbb"));
    Assert.assertTrue(remoteProfileExists("1.0", "prfG"));

    GitOperation<Profile> gitop = new GitOperation<Profile>() {
        public Profile call(Git git, GitContext context) throws Exception {
            return profileRegistry.getProfile(versionId, "prfG");
        }
    };
    GitContext context = new GitContext().requirePull();
    gitDataStore.gitOperation(context, gitop, null);

    Profile prfG = profileRegistry.getProfile(versionId, "prfG");
    Assert.assertEquals("bbb", prfG.getAttributes().get("foo"));

    profileRegistry.deleteProfile(versionId, "prfG");
    Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfG"));
}

From source file:org.eclipse.egit.core.op.RemoveFromIndexOperation.java

License:Open Source License

private static GitCommand<?> prepareCommand(Repository repository, Collection<String> paths) {
    Git git = new Git(repository);
    if (hasHead(repository)) {
        ResetCommand resetCommand = git.reset();
        resetCommand.setRef(HEAD);/*  www. ja  v  a 2s . co  m*/
        for (String path : paths)
            resetCommand.addPath(getCommandPath(path));
        return resetCommand;
    } else {
        RmCommand rmCommand = git.rm();
        rmCommand.setCached(true);
        for (String path : paths)
            rmCommand.addFilepattern(getCommandPath(path));
        return rmCommand;
    }
}

From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

private static void resetHard(SetupTaskContext context, Git git) throws Exception {
    context.log("Resetting hard");

    ResetCommand command = git.reset();
    command.setMode(ResetType.HARD);/*from w  ww.jav a 2  s. c om*/
    command.call();
}

From source file:org.eclipse.orion.server.git.servlets.GitIndexHandlerV1.java

License:Open Source License

private boolean handlePost(HttpServletRequest request, HttpServletResponse response, Repository db, IPath path)
        throws ServletException, NoFilepatternException, IOException, JSONException {
    JSONObject toReset = OrionServlet.readJSONRequest(request);
    String resetType = toReset.optString(GitConstants.KEY_RESET_TYPE, null);
    if (resetType != null) {
        JSONArray paths = toReset.optJSONArray(ProtocolConstants.KEY_PATH);
        if (paths != null) {
            String msg = NLS.bind("Mixing {0} and {1} parameters is not allowed.",
                    new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_RESET_TYPE });
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }/*from   w  w  w .j a v a2  s . c  o  m*/
        String ref = toReset.optString(GitConstants.KEY_TAG_COMMIT, Constants.HEAD);
        try {
            ResetType type = ResetType.valueOf(resetType);
            switch (type) {
            case MIXED:
            case HARD:
                Git git = new Git(db);
                // "git reset --{type} HEAD ."
                git.reset().setMode(type).setRef(ref).call();
                return true;
            case KEEP:
            case MERGE:
            case SOFT:
                String msg = NLS.bind("The reset type is not yet supported: {0}.", resetType);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_IMPLEMENTED, msg, null));
            }
        } catch (IllegalArgumentException e) {
            String msg = NLS.bind("Unknown or malformed reset type: {0}.", resetType);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
    } else {
        String commit = toReset.optString(GitConstants.KEY_TAG_COMMIT, null);
        if (commit != null) {
            String msg = NLS.bind("Mixing {0} and {1} parameters is not allowed.",
                    new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_TAG_COMMIT });
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
        JSONArray paths = toReset.optJSONArray(ProtocolConstants.KEY_PATH);
        Git git = new Git(db);
        ResetCommand reset = git.reset().setRef(Constants.HEAD);
        if (paths != null) {
            for (int i = 0; i < paths.length(); i++) {
                reset.addPath(paths.getString(i));
            }
        } else {
            String p = path.removeFirstSegments(2).toString();
            if (p.isEmpty()) {
                String msg = "Path cannot be empty.";
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }
            reset.addPath(p);
        }
        reset.call();
        return true;
    }
    return false;
}

From source file:org.enterprisedomain.classmaker.impl.ProjectImpl.java

License:Apache License

/**
 * <!-- begin-user-doc --> <!-- end-user-doc -->
 * /*  w  w w.j  a v a 2 s  .  c o m*/
 * @generated NOT
 */
public void checkout(Version version, long time) {
    Revision revision = null;
    if (getRevisions().containsKey(version)) {
        setProjectVersion(version);
        if (getProjectName().isEmpty())
            return;
        Git git = null;
        @SuppressWarnings("unchecked")
        SCMOperator<Git> operator = (SCMOperator<Git>) getWorkspace().getSCMRegistry().get(getProjectName());
        Ref ref = null;
        try {
            git = operator.getRepositorySCM();
            ref = git.getRepository().findRef(version.toString());
            if (ref != null)
                git.checkout().setName(ref.getName()).call();
        } catch (CheckoutConflictException e) {
            if (git != null) {
                try {
                    ResetCommand reset = git.reset().setMode(ResetType.HARD);
                    if (ref != null)
                        reset.setRef(ref.getName());
                    reset.call();
                } catch (CheckoutConflictException ex) {
                    ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(ex));
                } catch (GitAPIException ex) {
                    ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(ex));
                }
            }
        } catch (Exception e) {
            ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
        } finally {
            try {
                operator.ungetRepositorySCM();
            } catch (Exception e) {
                ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
            }
        }
        revision = getRevisions().get(version);
        if (revision.getStateHistory().containsKey(time)) {
            State state = revision.getStateHistory().get((Object) time);
            EList<String> commits = state.getCommitIds();
            if (!commits.isEmpty()) {
                revision.checkout(time, state.getCommitId());
            } else
                revision.checkout(time);
        }
    } else
        throw new IllegalStateException(NLS.bind(Messages.VersionNotExists, version));
}

From source file:org.exist.git.xquery.Reset.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    ResetType type;/*from  w ww  .  jav a 2 s  .co m*/

    String sType = args[1].getStringValue();
    if ("KEEP".equalsIgnoreCase(sType)) {
        type = ResetType.KEEP;
    } else if ("MERGE".equalsIgnoreCase(sType)) {
        type = ResetType.MERGE;
    } else if ("HARD".equalsIgnoreCase(sType)) {
        type = ResetType.HARD;
    } else if ("SOFT".equalsIgnoreCase(sType)) {
        type = ResetType.SOFT;
    } else if ("MIXED".equalsIgnoreCase(sType)) {
        type = ResetType.MIXED;
    } else {
        throw new XPathException(this, "Unknow type '" + sType + "'.");
    }

    try {
        String localPath = args[0].getStringValue();
        if (!(localPath.endsWith("/")))
            localPath += File.separator;

        Git git = Git.open(new Resource(localPath), FS);

        git.reset().setMode(type).call();

        return BooleanValue.TRUE;
    } catch (Throwable e) {
        throw new XPathException(this, Module.EXGIT001, e);
    }
}

From source file:org.gradle.vcs.git.internal.GitVersionControlSystem.java

License:Apache License

private static void cloneRepo(File workingDir, GitVersionControlSpec gitSpec, VersionRef ref) {
    CloneCommand clone = Git.cloneRepository().setURI(gitSpec.getUrl().toString()).setDirectory(workingDir)
            .setCloneSubmodules(true);//  ww  w.j a  v a2s.  com
    Git git = null;
    try {
        git = clone.call();
        git.reset().setMode(ResetCommand.ResetType.HARD).setRef(ref.getCanonicalId()).call();
    } catch (GitAPIException e) {
        throw wrapGitCommandException("clone", gitSpec.getUrl(), workingDir, e);
    } catch (JGitInternalException e) {
        throw wrapGitCommandException("clone", gitSpec.getUrl(), workingDir, e);
    } finally {
        if (git != null) {
            git.close();
        }
    }
}

From source file:org.gradle.vcs.git.internal.GitVersionControlSystem.java

License:Apache License

private static void resetRepo(File workingDir, GitVersionControlSpec gitSpec, VersionRef ref) {
    Git git = null;
    try {//from   w  w w  . ja  v  a2 s  .  co  m
        git = Git.open(workingDir);
        git.reset().setMode(ResetCommand.ResetType.HARD).setRef(ref.getCanonicalId()).call();
        updateSubModules(git);
    } catch (IOException e) {
        throw wrapGitCommandException("reset", gitSpec.getUrl(), workingDir, e);
    } catch (GitAPIException e) {
        throw wrapGitCommandException("reset", gitSpec.getUrl(), workingDir, e);
    } catch (JGitInternalException e) {
        throw wrapGitCommandException("reset", gitSpec.getUrl(), workingDir, e);
    } finally {
        if (git != null) {
            git.close();
        }
    }
}

From source file:org.gradle.vcs.git.internal.GitVersionControlSystem.java

License:Apache License

private static void updateSubModules(Git git) throws IOException, GitAPIException {
    SubmoduleWalk walker = SubmoduleWalk.forIndex(git.getRepository());
    try {// www  . j a  v a 2  s . c o  m
        while (walker.next()) {
            Repository submodule = walker.getRepository();
            try {
                Git submoduleGit = Git.wrap(submodule);
                submoduleGit.fetch().call();
                git.submoduleUpdate().addPath(walker.getPath()).call();
                submoduleGit.reset().setMode(ResetCommand.ResetType.HARD).call();
                updateSubModules(submoduleGit);
            } finally {
                submodule.close();
            }
        }
    } finally {
        walker.close();
    }
}