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

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

Introduction

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

Prototype

public Status getStatus() 

Source Link

Document

Get the status

Usage

From source file:com.maiereni.synchronizer.git.utils.GitDownloaderImpl.java

License:Apache License

private List<Change> update(final Git git, final GitProperties properties, final Ref localBranch,
        final Ref tagRef) throws Exception {
    logger.debug("Fetch from remote");
    List<Change> ret = null;
    FetchCommand cmd = git.fetch();/*from  w  ww.  j  ava  2 s  .  c o  m*/
    if (StringUtils.isNotBlank(properties.getUserName()) && StringUtils.isNotBlank(properties.getPassword())) {
        logger.debug("Set credentials");
        cmd.setCredentialsProvider(
                new UsernamePasswordCredentialsProvider(properties.getUserName(), properties.getPassword()));
    }
    if (tagRef != null) {
        RefSpec spec = new RefSpec().setSourceDestination(localBranch.getName(), tagRef.getName());
        List<RefSpec> specs = new ArrayList<RefSpec>();
        specs.add(spec);
        cmd.setRefSpecs(specs);
    }
    FetchResult fr = cmd.call();
    Collection<Ref> refs = fr.getAdvertisedRefs();
    for (Ref ref : refs) {
        if (ref.getName().equals("HEAD")) {
            ret = checkDifferences(git, localBranch, ref);
            logger.debug("Rebase on HEAD");
            RebaseResult rebaseResult = git.rebase().setUpstream(ref.getObjectId()).call();
            if (rebaseResult.getStatus().isSuccessful()) {

            }
        }
    }
    return ret;
}

From source file:com.microsoft.gittf.core.tasks.PullTask.java

License:Open Source License

private TaskStatus rebase(TaskProgressMonitor progressMonitor, ObjectId commitId) {
    try {/* w  ww. j av  a2s.c o  m*/
        getRebaseCommand().setOperation(Operation.BEGIN);
        getRebaseCommand().setUpstream(commitId);
        getRebaseCommand().setProgressMonitor(new RebaseMergeJGITProgressMonitor(progressMonitor));

        RebaseResult rebaseResults = getRebaseCommand().call();

        progressMonitor.endTask();

        RebaseResult.Status status = rebaseResults.getStatus();

        switch (status) {
        case UP_TO_DATE:
            progressMonitor.displayMessage(Messages.getString("PullTask.Rebase.AlreadyUpToDate")); //$NON-NLS-1$
            break;

        case ABORTED:
        case FAILED:
            progressMonitor.displayMessage(Messages.formatString("PullTask.Rebase.FailedFormat", //$NON-NLS-1$
                    ObjectIdUtil.abbreviate(repository, commitId)));
            displayFailures(progressMonitor, rebaseResults.getFailingPaths());
            break;

        case FAST_FORWARD:
        case OK:
            progressMonitor.displayMessage(Messages.formatString("PullTask.Rebase.RebaseSuccessfulFormat", //$NON-NLS-1$
                    ObjectIdUtil.abbreviate(repository, commitId)));
            break;

        case NOTHING_TO_COMMIT:
            progressMonitor.displayMessage(Messages.formatString("PullTask.Rebase.NothingToCommitFormat", //$NON-NLS-1$
                    ObjectIdUtil.abbreviate(repository, commitId)));
            break;

        case STOPPED:
            progressMonitor.displayMessage(Messages.formatString("PullTask.Rebase.StoppedFormat", //$NON-NLS-1$
                    ObjectIdUtil.abbreviate(repository, commitId)));
            break;
        }

        RepositoryUtil.fixFileAttributes(repository);
    } catch (Exception e) {
        log.error("An error occurred while merging.", e); //$NON-NLS-1$

        return new TaskStatus(TaskStatus.ERROR, e);
    }

    return TaskStatus.OK_STATUS;
}

From source file:com.mooregreatsoftware.gitprocess.lib.Rebaser.java

License:Apache License

public static Either<String, SuccessfulRebase> rebase(GitLib gitLib, Branch baseBranch) {
    final Branch currentBranch = gitLib.branches().currentBranch();

    if (currentBranch == null)
        return left("No branch is currently checked out");

    LOG.debug("Rebasing {} with {}", currentBranch, baseBranch.shortName());

    final Either<Throwable, RebaseResult> rebaseResults = Try
            .of(() -> gitLib.jgit().rebase().setUpstream(baseBranch.objectId()).call()).toEither();

    if (rebaseResults.isLeft())
        return left(rebaseResults.toString());

    final RebaseResult rebaseResult = rebaseResults.get();

    return rebaseResult.getStatus().isSuccessful() ? right(new SuccessfulRebase(rebaseResult))
            : left(statusToErrorMessage(rebaseResult));
}

From source file:com.mooregreatsoftware.gitprocess.lib.Rebaser.java

License:Apache License

/**
 * All this is from the comments. It's accessible in MergeResults.Status, but not here :-(
 *///from  w w  w  . j  a v  a  2  s  .  c  o  m
protected static String statusToErrorMessage(RebaseResult rebaseResult) {
    final RebaseResult.Status status = rebaseResult.getStatus();
    switch (status) {
    case OK:
        return "OK; Rebase was successful, HEAD points to the new commit";
    case STOPPED:
        return "Stopped due to a conflict; must either abort or resolve or skip";
    case ABORTED:
        return "Aborted; the original HEAD was restored";
    case EDIT:
        return "Stopped for editing in the context of an interactive rebase";
    case FAILED:
        return "Failed; the original HEAD was restored";
    case UNCOMMITTED_CHANGES:
        return "The repository contains uncommitted changes and the rebase is not a fast-forward";
    case CONFLICTS:
        return "Conflicts: checkout of target HEAD failed";
    case UP_TO_DATE:
        return "Already up-to-date";
    case FAST_FORWARD:
        return "Fast-forward, HEAD points to the new commit";
    default:
        return status.toString();
    }
}

From source file:com.verigreen.jgit.JGitOperator.java

License:Apache License

@Override
public boolean rebase(String upStreamBranchName) {

    RebaseCommand command = _git.rebase();
    RebaseResult result = null;
    try {/*  w ww. j a v  a 2s  .c o m*/
        command.setUpstream(upStreamBranchName);
        result = command.call();
        // if there are merge conflicts (rebase interactive) - reset the repository
        if (!result.getStatus().isSuccessful()) {
            _git.rebase().setOperation(Operation.ABORT).call();
        }
    } catch (Throwable e) {
        throw new RuntimeException(String.format("Failed to rebase with upstream [%s]", upStreamBranchName), e);
    }

    return result.getStatus().isSuccessful();
}

From source file:io.fabric8.git.internal.DefaultPullPushPolicy.java

License:Apache License

@Override
public synchronized PullPolicyResult doPull(GitContext context, CredentialsProvider credentialsProvider,
        boolean allowVersionDelete) {
    Repository repository = git.getRepository();
    StoredConfig config = repository.getConfig();
    String remoteUrl = config.getString("remote", remoteRef, "url");
    if (remoteUrl == null) {
        LOGGER.debug("No remote repository defined, so not doing a pull");
        return new AbstractPullPolicyResult();
    }//w ww.j  av a 2 s .  c  om

    LOGGER.info("Performing a pull on remote URL: {}", remoteUrl);

    Exception lastException = null;
    try {
        git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setRemote(remoteRef)
                .call();
    } catch (GitAPIException | JGitInternalException ex) {
        lastException = ex;
    }

    // No meaningful processing after GitAPIException
    if (lastException != null) {
        LOGGER.warn("Pull failed because of: {}", lastException.toString());
        return new AbstractPullPolicyResult(lastException);
    }

    // Get local and remote branches
    Map<String, Ref> localBranches = new HashMap<String, Ref>();
    Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
    Set<String> allBranches = new HashSet<String>();
    try {
        for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
            if (ref.getName().startsWith("refs/remotes/" + remoteRef + "/")) {
                String name = ref.getName().substring(("refs/remotes/" + remoteRef + "/").length());
                remoteBranches.put(name, ref);
                allBranches.add(name);
            } else if (ref.getName().startsWith("refs/heads/")) {
                String name = ref.getName().substring(("refs/heads/").length());
                localBranches.put(name, ref);
                allBranches.add(name);
            }
        }

        boolean localUpdate = false;
        boolean remoteUpdate = false;
        Set<String> versions = new TreeSet<>();

        // Remote repository has no branches, force a push
        if (remoteBranches.isEmpty()) {
            LOGGER.debug("Pulled from an empty remote repository");
            return new AbstractPullPolicyResult(versions, false, !localBranches.isEmpty(), null);
        } else {
            LOGGER.debug("Processing remote branches: {}", remoteBranches);
        }

        // Verify master branch and do a checkout of it when we have it locally (already)
        IllegalStateAssertion.assertTrue(remoteBranches.containsKey(GitHelpers.MASTER_BRANCH),
                "Remote repository does not have a master branch");
        if (localBranches.containsKey(GitHelpers.MASTER_BRANCH)) {
            git.checkout().setName(GitHelpers.MASTER_BRANCH).setForce(true).call();
        }

        // Iterate over all local/remote branches
        for (String branch : allBranches) {

            // Delete a local branch that does not exist remotely, but not master 
            boolean allowDelete = allowVersionDelete && !GitHelpers.MASTER_BRANCH.equals(branch);
            if (localBranches.containsKey(branch) && !remoteBranches.containsKey(branch)) {
                if (allowDelete) {
                    LOGGER.debug("Deleting local branch: {}", branch);
                    git.branchDelete().setBranchNames(branch).setForce(true).call();
                    localUpdate = true;
                } else {
                    remoteUpdate = true;
                }
            }

            // Create a local branch that exists remotely
            else if (!localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) {
                LOGGER.debug("Adding local branch: {}", branch);
                git.checkout().setCreateBranch(true).setName(branch).setStartPoint(remoteRef + "/" + branch)
                        .setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call();
                versions.add(branch);
                localUpdate = true;
            }

            // Update a local branch that also exists remotely
            else if (localBranches.containsKey(branch) && remoteBranches.containsKey(branch)) {
                ObjectId localObjectId = localBranches.get(branch).getObjectId();
                ObjectId remoteObjectId = remoteBranches.get(branch).getObjectId();
                String localCommit = localObjectId.getName();
                String remoteCommit = remoteObjectId.getName();
                if (!localCommit.equals(remoteCommit)) {
                    git.clean().setCleanDirectories(true).call();
                    git.checkout().setName("HEAD").setForce(true).call();
                    git.checkout().setName(branch).setForce(true).call();
                    MergeResult mergeResult = git.merge().setFastForward(FastForwardMode.FF_ONLY)
                            .include(remoteObjectId).call();
                    MergeStatus mergeStatus = mergeResult.getMergeStatus();
                    LOGGER.debug("Updating local branch {} with status: {}", branch, mergeStatus);
                    if (mergeStatus == MergeStatus.FAST_FORWARD) {
                        localUpdate = true;
                    } else if (mergeStatus == MergeStatus.ALREADY_UP_TO_DATE) {
                        remoteUpdate = true;
                    } else if (mergeStatus == MergeStatus.ABORTED) {
                        LOGGER.debug("Cannot fast forward branch {}, attempting rebase", branch);
                        RebaseResult rebaseResult = git.rebase().setUpstream(remoteCommit).call();
                        RebaseResult.Status rebaseStatus = rebaseResult.getStatus();
                        if (rebaseStatus == RebaseResult.Status.OK) {
                            localUpdate = true;
                            remoteUpdate = true;
                        } else {
                            LOGGER.warn("Rebase on branch {} failed, restoring remote branch", branch);
                            git.rebase().setOperation(Operation.ABORT).call();
                            git.checkout().setName(GitHelpers.MASTER_BRANCH).setForce(true).call();
                            git.branchDelete().setBranchNames(branch).setForce(true).call();
                            git.checkout().setCreateBranch(true).setName(branch)
                                    .setStartPoint(remoteRef + "/" + branch)
                                    .setUpstreamMode(SetupUpstreamMode.TRACK).setForce(true).call();
                            localUpdate = true;
                        }
                    }
                }
                versions.add(branch);
            }
        }

        PullPolicyResult result = new AbstractPullPolicyResult(versions, localUpdate, remoteUpdate, null);
        LOGGER.info("Pull result: {}", result);
        return result;
    } catch (Exception ex) {
        return new AbstractPullPolicyResult(ex);
    }
}

From source file:org.codehaus.mojo.versions.BumpMojo.java

License:Apache License

void gitRebase() throws MojoExecutionException {
    try {/*from  w w w  .  ja  va2s. c  o  m*/
        RebaseCommand ff = git.rebase();

        String masterOrigin = git.getRepository().getConfig().getString("branch", master, "remote");
        String masterMerge = git.getRepository().getConfig().getString("branch", master, "merge");

        masterMerge = Repository.shortenRefName(masterMerge);

        RevWalk walk = new RevWalk(git.getRepository());
        RevCommit commit = walk
                .parseCommit(git.getRepository().getRef(masterOrigin + "/" + masterMerge).getObjectId());

        ff.setUpstream(commit);
        RebaseResult f = ff.call();
        if (!f.getStatus().isSuccessful()) {
            throw new MojoExecutionException(f.getStatus().toString());
        }
    } catch (GitAPIException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (MissingObjectException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (IncorrectObjectTypeException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.dstadler.jgit.porcelain.RebaseToOriginMaster.java

License:Apache License

public static void main(String[] args) throws IOException, GitAPIException {
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        // all refs
        try (Git git = new Git(repository)) {
            InteractiveHandler handler = new InteractiveHandler() {
                @Override/* w ww  .  ja  v a 2 s  .  c o  m*/
                public void prepareSteps(List<RebaseTodoLine> steps) {
                    // the handler receives the list of commits that are rebased, i.e. the ones on the local branch
                    for (RebaseTodoLine step : steps) {
                        // for each step, you can decide which action should be taken
                        // default is PICK
                        try {
                            // by selecting "EDIT", the rebase will stop and ask you to edit the commit-contents
                            step.setAction(Action.EDIT);
                        } catch (IllegalTodoFileModification e) {
                            throw new IllegalStateException(e);
                        }
                    }
                }

                @Override
                public String modifyCommitMessage(String oldMessage) {
                    return oldMessage;
                }
            };

            RebaseResult result = git.rebase().setUpstream("origin/master").runInteractively(handler).call();
            System.out.println("Rebase had state: " + result.getStatus() + ": " + result.getConflicts());

            // because of the "EDIT" in the InteractiveHandler, the rebase was stopped in-between
            // now you can adjust the commit and continue rebasing with setOperation(RebaseCommand.Operation.CONTINUE)
            // to use the local changes for the commit or setOperation(RebaseCommand.Operation.SKIP) to skip this
            // commit (i.e. remove it from the branch!)

            if (!result.getStatus().isSuccessful()) {
                // if rebasing stopped or failed, you can get back to the original state by running it with setOperation(RebaseCommand.Operation.ABORT)
                result = git.rebase().setUpstream("origin/master").runInteractively(handler)
                        .setOperation(RebaseCommand.Operation.ABORT).call();
                System.out.println(
                        "Aborted reabse with state: " + result.getStatus() + ": " + result.getConflicts());
            }
        }
    }
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public RebaseResponse rebase(RebaseRequest request) throws GitException {
    RebaseResult result;
    RebaseStatus status;//from w w  w.  j  a  v  a2  s.  c  o  m
    List<String> failed;
    List<String> conflicts;
    try {
        RebaseCommand rebaseCommand = getGit().rebase();
        setRebaseOperation(rebaseCommand, request);
        String branch = request.getBranch();
        if (branch != null && !branch.isEmpty()) {
            rebaseCommand.setUpstream(branch);
        }
        result = rebaseCommand.call();
    } catch (GitAPIException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
    switch (result.getStatus()) {
    case ABORTED:
        status = RebaseStatus.ABORTED;
        break;
    case CONFLICTS:
        status = RebaseStatus.CONFLICTING;
        break;
    case UP_TO_DATE:
        status = RebaseStatus.ALREADY_UP_TO_DATE;
        break;
    case FAST_FORWARD:
        status = RebaseStatus.FAST_FORWARD;
        break;
    case NOTHING_TO_COMMIT:
        status = RebaseStatus.NOTHING_TO_COMMIT;
        break;
    case OK:
        status = RebaseStatus.OK;
        break;
    case STOPPED:
        status = RebaseStatus.STOPPED;
        break;
    case UNCOMMITTED_CHANGES:
        status = RebaseStatus.UNCOMMITTED_CHANGES;
        break;
    case EDIT:
        status = RebaseStatus.EDITED;
        break;
    case INTERACTIVE_PREPARED:
        status = RebaseStatus.INTERACTIVE_PREPARED;
        break;
    case STASH_APPLY_CONFLICTS:
        status = RebaseStatus.STASH_APPLY_CONFLICTS;
        break;
    default:
        status = RebaseStatus.FAILED;
    }
    conflicts = result.getConflicts() != null ? result.getConflicts() : Collections.emptyList();
    failed = result.getFailingPaths() != null ? new ArrayList<>(result.getFailingPaths().keySet())
            : Collections.emptyList();
    return newDto(RebaseResponse.class).withStatus(status).withConflicts(conflicts).withFailed(failed);
}

From source file:org.eclipse.egit.core.test.op.RebaseOperationTest.java

License:Open Source License

@Test
@Ignore/* ww  w . jav a  2s  . c o  m*/
// currently not working as expected; see also TODO in RebaseCommand
public void testUpToDate() throws Exception {
    IFile file = project.createFile("theFile.txt", "Hello, world".getBytes("UTF-8"));
    // first commit in master: add theFile.txt
    RevCommit first = testRepository.addAndCommit(project.project, new File(file.getLocationURI()),
            "Adding theFile.txt");

    testRepository.createBranch(MASTER, TOPIC);

    // checkout topic
    testRepository.checkoutBranch(TOPIC);

    file = project.createFile("theSecondFile.txt", "Hello, world".getBytes("UTF-8"));
    // topic commit: add second file
    RevCommit topicCommit = testRepository.addAndCommit(project.project, new File(file.getLocationURI()),
            "Adding theSecondFile.txt");

    // parent of topic commit should be first master commit before rebase
    assertEquals(first, topicCommit.getParent(0));

    // rebase topic onto master
    RebaseOperation op = new RebaseOperation(testRepository.getRepository(),
            testRepository.getRepository().getRef(MASTER));
    op.execute(null);

    RebaseResult res = op.getResult();
    assertEquals(RebaseResult.Status.UP_TO_DATE, res.getStatus());

    RevCommit newTopic = new RevWalk(repository).parseCommit(repository.resolve(TOPIC));
    assertEquals(topicCommit, newTopic);
    assertEquals(first, newTopic.getParent(0));
}