Example usage for org.eclipse.jgit.api CheckoutCommand getResult

List of usage examples for org.eclipse.jgit.api CheckoutCommand getResult

Introduction

In this page you can find the example usage for org.eclipse.jgit.api CheckoutCommand getResult.

Prototype

public CheckoutResult getResult() 

Source Link

Document

Get the result, never null

Usage

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

License:BSD License

/**
 * See {@link Git#checkout()}/*w w  w . j a  va  2 s.  co  m*/
 */
public static CheckoutResult doCheckout(final File workspace, final String localBranch, final String remoteName,
        final String remoteBranch) {
    try {
        final Git git = Git.open(workspace);
        final CheckoutCommand command = git.checkout().setName(localBranch).setForce(true);
        if (findRef(workspace, localBranch) == null) {
            command.setCreateBranch(true).setUpstreamMode(SetupUpstreamMode.TRACK)
                    .setStartPoint(remote(remoteName, remoteBranch)).call();
        } else {
            command.call();
        }
        return command.getResult();
    } catch (final Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ejwa.gitdepmavenplugin.DownloaderMojo.java

License:Open Source License

private void checkout(Git git, Pom pom, GitDependency dependency) throws MojoExecutionException {
    final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency);
    final String version = dependencyHandler.getDependencyVersion(pom);

    try {//from   w  w w. ja  v  a2  s .c  o  m
        final Repository repository = git.getRepository();
        final ObjectId rev = repository.resolve(version);
        final RevCommit rc = new RevWalk(repository).parseCommit(rev);
        final CheckoutCommand checkout = git.checkout();

        checkout.setName("maven-gitdep-branch-" + rc.getCommitTime());
        checkout.setStartPoint(rc);
        checkout.setCreateBranch(true);
        checkout.call();

        final Status status = checkout.getResult().getStatus();

        if (status != Status.OK) {
            throw new MojoExecutionException(
                    String.format("Invalid checkout state (%s) of dependency.", status));
        }
    } catch (IOException | InvalidRefNameException | RefAlreadyExistsException | RefNotFoundException ex) {
        throw new MojoExecutionException(String.format("Failed to check out dependency for %s.%s",
                dependency.getGroupId(), dependency.getArtifactId()), ex);
    }
}

From source file:com.ejwa.mavengitdepplugin.DownloaderMojo.java

License:Open Source License

private void checkout(Git git, POM pom, GitDependency dependency) {
    final GitDependencyHandler dependencyHandler = new GitDependencyHandler(dependency);
    final String version = dependencyHandler.getDependencyVersion(pom);

    try {/*  ww w  .  j  ava2  s .  c  o  m*/
        final ObjectId rev = git.getRepository().resolve(version);
        final RevCommit rc = new RevWalk(git.getRepository()).parseCommit(rev);
        final CheckoutCommand checkout = git.checkout();

        checkout.setName("maven-gitdep-branch-" + rc.getCommitTime());
        checkout.setStartPoint(rc);
        checkout.setCreateBranch(true);
        checkout.call();

        final Status status = checkout.getResult().getStatus();

        if (!status.equals(Status.OK)) {
            getLog().error("Status of checkout: " + status);
            throw new IllegalStateException("Invalid checkout state of dependency.");
        }
    } catch (Exception ex) {
        getLog().error(ex);
        throw new IllegalStateException("Failed to check out dependency.");
    }
}

From source file:com.mpdeimos.ct_tests.vcs.GitFileDiffTest.java

License:Apache License

@Test
public void testAddedFiles() {

    try {/*from   ww  w.j  av  a2 s.  c  o  m*/
        //         ArrayList<RevCommit> commits = new ArrayList<RevCommit>();
        //         
        //         Repository repository = new FileRepository(gitDir);
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setWorkTree(useTestFile("diff1")).build();
        ObjectId head = repository.resolve("new");
        //         TreeWalk treeWalk = TreeUtils.diffWithParents(repository, head);
        //         scan = DiffEntry.scan(treeWalk);
        //         treeWalk.release();

        CommitFinder finder = new CommitFinder(repository);
        GitCommitListFilter filter = new GitCommitListFilter();
        finder.setFilter(filter);
        finder.findFrom(head);
        for (Commit commit : filter.getCommits()) {
            //            ResetCommand reset = new Git(repository).reset();
            //            reset.setMode(ResetType.HARD);
            //            reset.setRef(commit.getId());
            CheckoutCommand checkout = new Git(repository).checkout();
            checkout.setName(commit.getId());
            //            checkout.setStartPoint(commit.getId());
            //            checkout.addPath(".");
            try {
                //               Ref call = reset.call();
                checkout.call();
                System.out.println(checkout.getResult().getStatus() + " checked out " + commit.getMessage());
            } catch (Exception e) {
                fail(e.getMessage());
            }

            //            System.out.println(change.getCommit().getFullMessage());

        }

        //         head = repository.resolve("HEAD~1");
        //         RevWalk revWalk = new RevWalk(repository);
        //         RevCommit tip = revWalk.parseCommit(head);
        //         revWalk.markStart(tip);
        //         revWalk.
        //         TreeWalk treeWalk = new TreeWalk(repository);
        //         treeWalk.setRecursive(true);
        //         treeWalk.addTree(tip.getTree());
        //         

        //         revWalk.markStart(tip);

        //         GitFileDiff[] compute = GitFileDiff.compute(treeWalk, tip);

        //         System.out.println(compute);

    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:com.rimerosolutions.ant.git.tasks.CheckoutTask.java

License:Apache License

@Override
protected void doExecute() throws BuildException {
    try {/* ww w. j a va2  s  .c  o  m*/
        CheckoutCommand checkoutCommand = git.checkout();

        if (createBranch) {
            checkoutCommand.setCreateBranch(true);

            if (trackBranchOnCreate) {
                checkoutCommand.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
            }
        }

        if (!GitTaskUtils.isNullOrBlankString(branchName)) {
            checkoutCommand.setName(branchName);
        }

        if (!GitTaskUtils.isNullOrBlankString(startPoint)) {
            checkoutCommand.setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + startPoint);
        }

        checkoutCommand.call();

        CheckoutResult checkoutResult = checkoutCommand.getResult();

        if (checkoutResult.getStatus().equals(CheckoutResult.Status.CONFLICTS)) {
            String conflicts = checkoutResult.getConflictList().toString();

            throw new GitBuildException(String.format("Conflicts were found:%s.", conflicts));
        } else if (checkoutResult.getStatus().equals(CheckoutResult.Status.NONDELETED)) {
            String undeleted = checkoutResult.getUndeletedList().toString();

            throw new GitBuildException(String.format("Some files could not be deleted:%s.", undeleted));
        }
    } catch (RefAlreadyExistsException e) {
        throw new GitBuildException(
                String.format("Cannot create branch '%s', as it already exists!", branchName), e);
    } catch (RefNotFoundException e) {
        throw new GitBuildException(String.format("The branch '%s' was not found.", branchName), e);
    } catch (InvalidRefNameException e) {
        throw new GitBuildException("An invalid branch name was specified.", e);
    } catch (CheckoutConflictException e) {
        throw new GitBuildException("Some checkout conflicts were found.", e);
    } catch (GitAPIException e) {
        throw new GitBuildException(String.format("Could not checkout branch '%s'.", branchName), e);
    }
}

From source file:org.eclipse.egit.ui.internal.fetch.FetchGerritChangePage.java

License:Open Source License

private void createBranch(final String textForBranch, RevCommit commit, IProgressMonitor monitor)
        throws CoreException, GitAPIException {
    monitor.setTaskName(UIText.FetchGerritChangePage_CreatingBranchTaskName);
    CreateLocalBranchOperation bop = new CreateLocalBranchOperation(repository, textForBranch, commit);
    bop.execute(monitor);/* w w w .  j  a  v  a 2  s.  c  o  m*/
    CheckoutCommand co = new Git(repository).checkout();
    try {
        co.setName(textForBranch).call();
    } catch (CheckoutConflictException e) {
        final CheckoutResult result = co.getResult();

        if (result.getStatus() == Status.CONFLICTS) {
            final Shell shell = getWizard().getContainer().getShell();

            shell.getDisplay().asyncExec(new Runnable() {
                public void run() {
                    new CheckoutConflictDialog(shell, repository, result.getConflictList()).open();
                }
            });
        }
    }
    monitor.worked(1);
}

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

License:Open Source License

private boolean handlePut(HttpServletRequest request, HttpServletResponse response, String pathString)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException,
        JGitInternalException, GitAPIException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    if (path.segment(0).equals("file") && path.segmentCount() > 1) { //$NON-NLS-1$

        // make sure a clone is addressed
        WebProject webProject = WebProject.fromId(path.segment(1));
        if (isAccessAllowed(request.getRemoteUser(), webProject)) {
            URI contentLocation = URI.create(webProject.getId());
            IPath projectPath = new Path(contentLocation.getPath()).append(path.removeFirstSegments(2));
            projectPath = path.hasTrailingSeparator() ? projectPath : projectPath.removeLastSegments(1);
            File gitDir = GitUtils.getGitDirs(new Path("file").append(projectPath), Traverse.CURRENT).values() //$NON-NLS-1$
                    .iterator().next();/*from  ww  w .j a  va2 s  . c  om*/

            // make sure required fields are set
            JSONObject toCheckout = OrionServlet.readJSONRequest(request);
            JSONArray paths = toCheckout.optJSONArray(ProtocolConstants.KEY_PATH);
            String branch = toCheckout.optString(GitConstants.KEY_BRANCH_NAME);
            if ((paths == null || paths.length() == 0) && (branch == null || branch.isEmpty())) {
                String msg = NLS.bind("Either '{0}' or '{1}' should be provided: {2}",
                        new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_BRANCH_NAME, toCheckout });
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }

            Git git = new Git(new FileRepository(gitDir));
            if (paths != null) {
                CheckoutCommand checkout = git.checkout();
                for (int i = 0; i < paths.length(); i++) {
                    checkout.addPath(paths.getString(i));
                }
                checkout.call();
                return true;
            } else if (branch != null) {
                CheckoutCommand co = git.checkout();
                try {
                    co.setName(branch).call();
                    return true;
                } catch (JGitInternalException e) {
                    if (Status.CONFLICTS.equals(co.getResult().getStatus())) {
                        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                                HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
                    }
                    // TODO: handle other exceptions
                } catch (RefNotFoundException e) {
                    String msg = NLS.bind("Branch name not found: {0}", branch);
                    return statusHandler.handleRequest(request, response,
                            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
                }

            }
        } else {
            String msg = NLS.bind("Nothing found for the given ID: {0}", path);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
        }
    }
    String msg = NLS.bind("Invalid checkout request {0}", pathString);
    return statusHandler.handleRequest(request, response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}

From source file:org.flowerplatform.web.git.operation.CheckoutOperation.java

License:Open Source License

public boolean execute() {
    ProgressMonitor monitor = ProgressMonitor
            .create(GitPlugin.getInstance().getMessage("git.checkout.monitor.title"), channel);

    try {/*from   w  w  w. ja v a2 s . c  o  m*/
        monitor.beginTask(
                GitPlugin.getInstance().getMessage("git.checkout.monitor.message", new Object[] { name }), 4);
        monitor.setTaskName("Getting remote branch...");
        Git git = new Git(repository);
        Ref ref;
        if (node instanceof Ref) {
            ref = (Ref) node;
        } else {
            // get remote branch
            String dst = Constants.R_REMOTES + remote.getName();
            String remoteRefName = dst + "/" + upstreamBranch.getShortName();
            ref = repository.getRef(remoteRefName);
            if (ref == null) { // doesn't exist, fetch it
                RefSpec refSpec = new RefSpec();
                refSpec = refSpec.setForceUpdate(true);
                refSpec = refSpec.setSourceDestination(upstreamBranch.getName(), remoteRefName);

                git.fetch().setRemote(new URIish(remote.getUri()).toPrivateString()).setRefSpecs(refSpec)
                        .call();

                ref = repository.getRef(remoteRefName);
            }
        }
        monitor.worked(1);
        monitor.setTaskName("Creating local branch...");

        // create local branch
        git.branchCreate().setName(name).setStartPoint(ref.getName())
                .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM).call();

        if (!(node instanceof Ref)) {
            // save upstream configuration
            StoredConfig config = repository.getConfig();

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_MERGE,
                    upstreamBranch.getName());

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REMOTE,
                    remote.getName());

            if (rebase) {
                config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, name,
                        ConfigConstants.CONFIG_KEY_REBASE, true);
            } else {
                config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REBASE);
            }
            config.save();
        }
        monitor.worked(1);
        monitor.setTaskName("Creating working directory");

        // create working directory for local branch
        File mainRepoFile = repository.getDirectory().getParentFile();
        File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + name);
        if (wdirFile.exists()) {
            GitPlugin.getInstance().getUtils().delete(wdirFile);
        }
        GitPlugin.getInstance().getUtils().run_git_workdir_cmd(mainRepoFile.getAbsolutePath(),
                wdirFile.getAbsolutePath());
        monitor.worked(1);
        monitor.setTaskName("Checkout branch");

        // checkout local branch
        Repository wdirRepo = GitPlugin.getInstance().getUtils().getRepository(wdirFile);
        git = new Git(wdirRepo);

        CheckoutCommand cc = git.checkout().setName(name).setForce(true);
        cc.call();

        // show checkout result
        if (cc.getResult().getStatus() == CheckoutResult.Status.CONFLICTS)
            channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.title"),
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.message"),
                    cc.getResult().getConflictList().toString(),
                    DisplaySimpleMessageClientCommand.ICON_INFORMATION));

        else if (cc.getResult().getStatus() == CheckoutResult.Status.NONDELETED) {
            // double-check if the files are still there
            boolean show = false;
            List<String> pathList = cc.getResult().getUndeletedList();
            for (String path1 : pathList) {
                if (new File(wdirRepo.getWorkTree(), path1).exists()) {
                    show = true;
                    break;
                }
            }
            if (show) {
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.message",
                                Repository.shortenRefName(name)),
                        cc.getResult().getUndeletedList().toString(),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
            }
        } else if (cc.getResult().getStatus() == CheckoutResult.Status.OK) {
            if (ObjectId.isId(wdirRepo.getFullBranch()))
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.message"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
        }
        monitor.worked(1);
        return true;
    } catch (Exception e) {
        channel.appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    } finally {
        monitor.done();
    }
}

From source file:org.jboss.as.server.controller.git.GitRepository.java

License:Apache License

public GitRepository(GitRepositoryConfiguration gitConfig)
        throws IllegalArgumentException, IOException, ConfigXMLParseException, GeneralSecurityException {
    this.basePath = gitConfig.getBasePath();
    this.branch = gitConfig.getBranch();
    this.ignored = gitConfig.getIgnored();
    this.defaultRemoteRepository = gitConfig.getRepository();
    File baseDir = basePath.toFile();
    File gitDir = new File(baseDir, DOT_GIT);
    if (gitConfig.getAuthenticationConfig() != null) {
        CredentialsProvider/*  w w  w .  ja  v  a  2 s  . c om*/
                .setDefault(new ElytronClientCredentialsProvider(gitConfig.getAuthenticationConfig()));
    }
    if (gitDir.exists()) {
        try {
            repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
        } catch (IOException ex) {
            throw ServerLogger.ROOT_LOGGER.failedToPullRepository(ex, gitConfig.getRepository());
        }
        try (Git git = Git.wrap(repository)) {
            git.clean();
            if (!isLocalGitRepository(gitConfig.getRepository())) {
                String remote = getRemoteName(gitConfig.getRepository());
                checkoutToSelectedBranch(git);
                PullResult result = git.pull().setRemote(remote).setRemoteBranchName(branch)
                        .setStrategy(MergeStrategy.RESOLVE).call();
                if (!result.isSuccessful()) {
                    throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, gitConfig.getRepository());
                }
            } else {
                if (!this.branch.equals(repository.getBranch())) {
                    CheckoutCommand checkout = git.checkout().setName(branch);
                    checkout.call();
                    if (checkout.getResult().getStatus() == CheckoutResult.Status.ERROR) {
                        throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, gitConfig.getRepository());
                    }
                }
            }
        } catch (GitAPIException ex) {
            throw ServerLogger.ROOT_LOGGER.failedToPullRepository(ex, gitConfig.getRepository());
        }
    } else {
        if (isLocalGitRepository(gitConfig.getRepository())) {
            try (Git git = Git.init().setDirectory(baseDir).call()) {
                final AddCommand addCommand = git.add();
                addCommand.addFilepattern("data/content/");
                Path configurationDir = basePath.resolve("configuration");
                try (Stream<Path> files = Files.list(configurationDir)) {
                    files.filter(configFile -> !"logging.properties".equals(configFile.getFileName().toString())
                            && Files.isRegularFile(configFile))
                            .forEach(configFile -> addCommand.addFilepattern(getPattern(configFile)));
                }
                addCommand.call();
                createGitIgnore(git, basePath);
                git.commit().setMessage(ServerLogger.ROOT_LOGGER.repositoryInitialized()).call();
            } catch (GitAPIException | IOException ex) {
                throw ServerLogger.ROOT_LOGGER.failedToInitRepository(ex, gitConfig.getRepository());
            }
        } else {
            clearExistingFiles(basePath, gitConfig.getRepository());
            try (Git git = Git.init().setDirectory(baseDir).call()) {
                String remoteName = UUID.randomUUID().toString();
                StoredConfig config = git.getRepository().getConfig();
                config.setString("remote", remoteName, "url", gitConfig.getRepository());
                config.setString("remote", remoteName, "fetch",
                        "+" + R_HEADS + "*:" + R_REMOTES + remoteName + "/*");
                config.save();
                git.clean();
                git.pull().setRemote(remoteName).setRemoteBranchName(branch).setStrategy(MergeStrategy.RESOLVE)
                        .call();
                checkoutToSelectedBranch(git);
                if (createGitIgnore(git, basePath)) {
                    git.commit().setMessage(ServerLogger.ROOT_LOGGER.addingIgnored()).call();
                }
            } catch (GitAPIException ex) {
                throw ServerLogger.ROOT_LOGGER.failedToInitRepository(ex, gitConfig.getRepository());
            }
        }
        repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
    }
    ServerLogger.ROOT_LOGGER.usingGit();
}

From source file:org.jboss.as.server.controller.git.GitRepository.java

License:Apache License

private void checkoutToSelectedBranch(final Git git) throws IOException, GitAPIException {
    boolean createBranch = !ObjectId.isId(branch);
    if (createBranch) {
        Ref ref = git.getRepository().exactRef(R_HEADS + branch);
        if (ref != null) {
            createBranch = false;/*  w  w w  .  j av a 2  s. co m*/
        }
    }
    CheckoutCommand checkout = git.checkout().setCreateBranch(createBranch).setName(branch);
    checkout.call();
    if (checkout.getResult().getStatus() == CheckoutResult.Status.ERROR) {
        throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, defaultRemoteRepository);
    }
}