Example usage for org.eclipse.jgit.api CheckoutResult getStatus

List of usage examples for org.eclipse.jgit.api CheckoutResult getStatus

Introduction

In this page you can find the example usage for org.eclipse.jgit.api CheckoutResult getStatus.

Prototype

public Status getStatus() 

Source Link

Document

Get status

Usage

From source file:bench.MainJgit.java

License:BSD License

/**
 *//*from  ww w . ja v  a2s  .c o  m*/
public static void main(final String[] args) throws Exception {

    final File baseDir = new File(".");

    final File folder = new File(baseDir, "target");

    final File workspace = new File(folder, "workspace");

    FileUtils.delete(workspace, FileUtils.IGNORE_ERRORS | FileUtils.RECURSIVE);

    FileUtils.mkdirs(workspace, true);

    final String remoteURI = "git@github.com:barchart/barchart-jenkins-tester.git";
    final String remoteName = "archon";
    final String remoteBranch = "master";

    final String localBranch = "cascade";

    {
        final Git git = PluginScmGit.doClone(workspace, remoteURI, remoteName);
        final Repository repo = git.getRepository();
        System.out.println("repo " + repo);
    }

    {
        final CheckoutResult result = PluginScmGit.doCheckout(workspace, localBranch, remoteName, remoteBranch);
        System.out.println("checkout " + result.getStatus());
    }

    {
        final CheckoutResult result = PluginScmGit.doCheckout(workspace, localBranch, remoteName, remoteBranch);
        System.out.println("checkout " + result.getStatus());
    }

    {
        final RefSpec fetchSpec = PluginScmGit.refFetch(remoteBranch, remoteName, remoteBranch);

        final FetchResult fetchResult = PluginScmGit.doFetch(workspace, remoteName, fetchSpec);
        System.out.println("fetch satus: " + fetchResult.getAdvertisedRefs());

        final String refHead = PluginScmGit.refHeads(remoteBranch);

        final Ref remoteHead = fetchResult.getAdvertisedRef(refHead);

        final ObjectId commit = remoteHead.getObjectId();

        final MergeResult mergeResult = PluginScmGit.doMerge(workspace, commit);

        final MergeStatus mergeStatus = mergeResult.getMergeStatus();
        System.out.println("merge status: " + mergeStatus);

    }

}

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

License:BSD License

/**
 * Copy from remote into local.//from   ww  w  . j a v  a 2  s .c  om
 */
public static void scmCheckout(final BuildContext<CascadeBuild> context, final MavenModuleSet project)
        throws IOException, InterruptedException {

    final String message = checkScm(project);

    if (message != null) {
        throw new IllegalStateException(message);
    }

    final GitSCM gitScm = (GitSCM) project.getScm();
    final FilePath workspace = workspace(context, project);

    /** Remote objects. */
    final BuildLogger logger = context.logger();
    final String localBranch = localBranchName(gitScm);
    final String remoteURI = remoteURI(gitScm);
    final String remoteName = remoteName(gitScm);
    final String remoteBranch = remoteBranchName(gitScm);

    /** Remote operation. */
    final FileCallable<String> callable = new FileCallable<String>() {

        private static final long serialVersionUID = 1L;

        public String invoke(final File basedir, final VirtualChannel channel)
                throws IOException, InterruptedException {

            final boolean hasRepo = PluginScmGit.doRepoTest(basedir);

            if (hasRepo) {

                logger.logTab("repository present");

                final Status status = PluginScmGit.doStatus(basedir);

                if (!status.isClean()) {
                    logger.logTab("repository needs cleanup");
                    PluginScmGit.doReset(basedir);
                }

                /** Spec for the fetch mapping. */
                final RefSpec fetchSpec = PluginScmGit.refFetch(remoteBranch, remoteName, remoteBranch);

                final FetchResult fetchResult = PluginScmGit.doFetch(basedir, remoteName, fetchSpec);

                logger.logTab("fetch result: " + fetchResult.getTrackingRefUpdates().size());

                /** Spec of the head of the remote branch. */
                final String refHead = PluginScmGit.refHeads(remoteBranch);

                /** Reference to head of the remote branch. */
                final Ref remoteHead = fetchResult.getAdvertisedRef(refHead);
                if (remoteHead == null) {
                    logger.logErr("remote branch not found: " + refHead);
                    throw new IllegalStateException("Unexpected");
                }

                final ObjectId commit = remoteHead.getObjectId();

                final MergeResult mergeResult = PluginScmGit.doMerge(basedir, commit);

                final MergeStatus mergeStatus = mergeResult.getMergeStatus();

                logger.logTab("merge result: " + mergeStatus);

                if (!mergeStatus.isSuccessful()) {
                    logger.logTab("repository needs clone");
                    PluginScmGit.doClone(basedir, remoteURI, remoteName);
                }

            } else {

                logger.logTab("repository needs clone");
                PluginScmGit.doClone(basedir, remoteURI, remoteName);

            }

            final CheckoutResult checkoutResult = PluginScmGit.doCheckout(basedir, localBranch, remoteName,
                    remoteBranch);

            final CheckoutResult.Status checkoutStatus = checkoutResult.getStatus();

            logger.logTab("checkout status: " + checkoutStatus);

            if (!PluginScmGit.isSuccess(checkoutStatus)) {
                throw new IllegalStateException("Unexpected");
            }

            /** FIXME checkout does not work */
            PluginScmGit.doReset(basedir);

            final Ref ref = PluginScmGit.findRef(basedir, localBranch);

            logger.logTab(localBranch + ": " + ref.getObjectId().name());

            /** TODO delete local tags */

            return null;
        }
    };

    workspace.act(callable);

}

From source file:com.genuitec.eclipse.gerrit.tools.internal.changes.commands.SwitchToChangeBranchCommand.java

License:Open Source License

public void execute(final ExecutionEvent event, final Repository repository, final String branchRef) {
    BranchOperationUI op = BranchOperationUI.checkout(repository, branchRef).doneCallback(new DoneCallback() {

        public void done(CheckoutResult result) {

            if (result.getStatus() == CheckoutResult.Status.OK) {
                IPath path = new Path(branchRef);
                String stableBranch = path.segment(3);
                if (stableBranch.equals("features") && path.segmentCount() > 6) { //$NON-NLS-1$
                    stableBranch = path.removeFirstSegments(3).uptoSegment(3).toString();
                }/* www. j  av a 2 s  .  c  om*/
                String newUpstreamRef = branchRef + ":refs/for/" + stableBranch; //$NON-NLS-1$
                repository.getConfig().setString("remote", "origin", "push", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        newUpstreamRef);
                repository.getConfig().setBoolean("branch", //$NON-NLS-1$
                        path.removeFirstSegments(2).removeTrailingSeparator().makeRelative().toString(),
                        "rebase", true); //$NON-NLS-1$
                try {
                    repository.getConfig().save();
                } catch (IOException e) {
                    RepositoryUtils.handleException(e);
                }
            }
        }
    });
    op.start();
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.fbranches.commands.SwitchToBranchCommand.java

License:Open Source License

protected void execute(ExecutionEvent event, final Repository repository, final String branchRef)
        throws ExecutionException {
    //check if local branch exists
    final String branchName = branchRef.substring("refs/heads/".length()); //$NON-NLS-1$
    try {/*from   www.  j a v a2 s.  com*/
        if (repository.getRef(branchRef) == null) {
            //create local branch
            String remoteBranchRef = "refs/remotes/origin/" + branchName; //$NON-NLS-1$
            Ref remoteRef = repository.getRef(remoteBranchRef);
            if (remoteRef == null) {
                throw new RuntimeException(
                        MessageFormat.format("Remote branch {0} doesn't exist", remoteBranchRef));
            }
            new Git(repository).branchCreate().setName(branchName).setStartPoint(remoteBranchRef)
                    .setUpstreamMode(SetupUpstreamMode.TRACK).call();
            repository.getConfig().setBoolean("branch", branchName, "rebase", true); //$NON-NLS-1$//$NON-NLS-2$
        }
    } catch (Exception e1) {
        RepositoryUtils.handleException(e1);
        return;
    }

    BranchOperationUI op = BranchOperationUI.checkout(repository, branchRef).doneCallback(new DoneCallback() {

        public void done(CheckoutResult result) {

            if (result.getStatus() == CheckoutResult.Status.OK) {
                String newUpstreamRef = branchRef + ":refs/for/" + branchName; //$NON-NLS-1$
                repository.getConfig().setString("remote", "origin", "push", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        newUpstreamRef);
                //ensure in rebase mode
                repository.getConfig().setBoolean("branch", branchName, "rebase", true); //$NON-NLS-1$//$NON-NLS-2$
                try {
                    repository.getConfig().save();
                } catch (IOException e) {
                    RepositoryUtils.handleException(e);
                }
            }
        }
    });
    op.start();
}

From source file:com.genuitec.org.eclipse.egit.ui.internal.branch.BranchOperationUI.java

License:Open Source License

/**
 * @param result/*w  w  w  .j  av  a 2  s  .  c  o  m*/
 *            the result to show
 */
public void show(final CheckoutResult result) {
    if (result.getStatus() == CheckoutResult.Status.CONFLICTS) {
        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
            public void run() {
                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                CleanupUncomittedChangesDialog cleanupUncomittedChangesDialog = new CleanupUncomittedChangesDialog(
                        shell, UIText.BranchResultDialog_CheckoutConflictsTitle,
                        NLS.bind(UIText.BranchResultDialog_CheckoutConflictsMessage,
                                Repository.shortenRefName(target)),
                        repository, result.getConflictList());
                cleanupUncomittedChangesDialog.open();
                if (cleanupUncomittedChangesDialog.shouldContinue()) {
                    BranchOperationUI op = BranchOperationUI.checkoutWithoutQuestion(repository, target)
                            .doneCallback(doneCallback);
                    op.start();
                }
            }
        });
    } else if (result.getStatus() == CheckoutResult.Status.NONDELETED) {
        // double-check if the files are still there
        boolean show = false;
        List<String> pathList = result.getUndeletedList();
        for (String path : pathList)
            if (new File(repository.getWorkTree(), path).exists()) {
                show = true;
                break;
            }
        if (!show)
            return;
        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
            public void run() {
                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                new NonDeletedFilesDialog(shell, repository, result.getUndeletedList()).open();
            }
        });
    } else if (result.getStatus() == CheckoutResult.Status.OK) {
        if (RepositoryUtil.isDetachedHead(repository))
            showDetachedHeadWarning();
    }
    if (doneCallback != null) {
        doneCallback.done(result);
    }
}

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

License:Apache License

@Override
protected void doExecute() throws BuildException {
    try {/*from w w w .  j a  va 2  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.gitflow.op.FeatureTrackOperation.java

License:Open Source License

@Override
public void execute(IProgressMonitor monitor) throws CoreException {
    try {//from w  w w .j  av  a2s.co  m
        String newLocalBranch = repository.getConfig().getFeatureBranchName(featureName);
        operationResult = fetch(monitor, timeout);

        if (repository.hasBranch(newLocalBranch)) {
            String errorMessage = String.format(CoreText.FeatureTrackOperation_localBranchExists,
                    newLocalBranch);
            throw new CoreException(error(errorMessage));
        }
        CreateLocalBranchOperation createLocalBranchOperation = new CreateLocalBranchOperation(
                repository.getRepository(), newLocalBranch, remoteFeature, BranchRebaseMode.NONE);
        createLocalBranchOperation.execute(monitor);

        BranchOperation branchOperation = new BranchOperation(repository.getRepository(), newLocalBranch);
        branchOperation.execute(monitor);
        CheckoutResult result = branchOperation.getResult();
        if (!Status.OK.equals(result.getStatus())) {
            String errorMessage = String.format(CoreText.FeatureTrackOperation_checkoutReturned, newLocalBranch,
                    result.getStatus().name());
            throw new CoreException(error(errorMessage));
        }

        try {
            repository.setRemote(newLocalBranch, DEFAULT_REMOTE_NAME);
            repository.setUpstreamBranchName(newLocalBranch,
                    repository.getConfig().getFullFeatureBranchName(featureName));
        } catch (IOException e) {
            throw new CoreException(error(CoreText.FeatureTrackOperation_unableToStoreGitConfig, e));
        }
    } catch (URISyntaxException e) {
        throw new CoreException(error(e.getMessage(), e));
    } catch (InvocationTargetException e) {
        Throwable targetException = e.getTargetException();
        throw new CoreException(error(targetException.getMessage(), targetException));
    } catch (GitAPIException e) {
        throw new CoreException(error(e.getMessage(), e));
    }

}

From source file:org.eclipse.egit.gitflow.ui.internal.actions.FeatureCheckoutHandler.java

License:Open Source License

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    final GitFlowRepository gfRepo = GitFlowHandlerUtil.getRepository(event);
    if (gfRepo == null) {
        return error(UIText.Handlers_noGitflowRepositoryFound);
    }/*from   w w w. j a  v a2  s .  c om*/

    Repository repository = gfRepo.getRepository();

    final List<Ref> refs = gfRepo.getFeatureBranches();

    FeatureBranchSelectionDialog dialog = new FeatureBranchSelectionDialog(HandlerUtil.getActiveShell(event),
            refs, UIText.FeatureCheckoutHandler_selectFeature, UIText.FeatureCheckoutHandler_localFeatures,
            Constants.R_HEADS + gfRepo.getConfig().getFeaturePrefix(), gfRepo);

    if (dialog.open() != Window.OK) {
        return null;
    }
    final Ref ref = dialog.getSelectedNode();

    try {
        String featureName = gfRepo.getFeatureBranchName(ref);
        // TODO: consider using BranchOperationUI because checkout can take
        // a long time on large repositories
        FeatureCheckoutOperation checkoutOperation = new FeatureCheckoutOperation(gfRepo, featureName);
        JobUtil.scheduleUserWorkspaceJob(checkoutOperation, UIText.FeatureCheckoutHandler_checkingOutFeature,
                JobFamilies.GITFLOW_FAMILY);
        IJobManager jobMan = Job.getJobManager();
        try {
            jobMan.join(GITFLOW_FAMILY, null);
        } catch (OperationCanceledException | InterruptedException e) {
            return error(e.getMessage(), e);
        }

        CheckoutResult result = checkoutOperation.getResult();
        if (!CheckoutResult.Status.OK.equals(result.getStatus())) {
            Shell shell = HandlerUtil.getActiveShell(event);
            if (!handleUncommittedFiles(gfRepo.getRepository(), shell, repository.getWorkTree().getName())) {
                return Status.CANCEL_STATUS;
            } else {
                JobUtil.scheduleUserWorkspaceJob(checkoutOperation,
                        UIText.FeatureCheckoutHandler_checkingOutFeature, JobFamilies.GITFLOW_FAMILY);
            }
        }
    } catch (GitAPIException e) {
        throw new RuntimeException(e);
    }

    return null;
}

From source file:org.eclipse.egit.ui.internal.branch.BranchResultDialog.java

License:Open Source License

/**
 * @param result/*from   w  w  w  . jav a 2 s  .c  o  m*/
 *            the result to show
 * @param repository
 * @param target
 *            the target (branch name or commit id)
 */
public static void show(final CheckoutResult result, final Repository repository, final String target) {
    BranchResultDialog.target = target;
    if (result.getStatus() == CheckoutResult.Status.CONFLICTS)
        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
            public void run() {
                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                new BranchResultDialog(shell, repository, result, target).open();
            }
        });
    else if (result.getStatus() == CheckoutResult.Status.NONDELETED) {
        // double-check if the files are still there
        boolean show = false;
        List<String> pathList = result.getUndeletedList();
        for (String path : pathList)
            if (new File(repository.getWorkTree(), path).exists()) {
                show = true;
                break;
            }
        if (!show)
            return;
        PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
            public void run() {
                Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
                new NonDeletedFilesDialog(shell, repository, result.getUndeletedList()).open();
            }
        });
    } else if (result.getStatus() == CheckoutResult.Status.OK) {
        try {
            if (ObjectId.isId(repository.getFullBranch()))
                showDetachedHeadWarning();
        } catch (IOException e) {
            Activator.logError(e.getMessage(), 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);// www.  j  av a2  s  .  co 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);
}