Example usage for org.eclipse.jgit.api RebaseCommand call

List of usage examples for org.eclipse.jgit.api RebaseCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api RebaseCommand call.

Prototype

@Override
public RebaseResult call()
        throws GitAPIException, NoHeadException, RefNotFoundException, WrongRepositoryStateException 

Source Link

Document

Executes the Rebase command with all the options and parameters collected by the setter methods of this class.

Usage

From source file:com.sap.dirigible.ide.jgit.connector.JGitConnector.java

License:Open Source License

/**
 * /*from w w  w  .j  ava 2  s . co m*/
 * Tries to rebase the selected branch on top of the current one.
 * 
 * @param name
 *            the branch to rebase
 * @throws NoHeadException
 * @throws WrongRepositoryStateException
 * @throws GitAPIException
 */
public void rebase(String name) throws NoHeadException, WrongRepositoryStateException, GitAPIException {
    RebaseCommand rebaseCommand = git.rebase();
    rebaseCommand.setOperation(Operation.BEGIN);
    rebaseCommand.setUpstream(name);
    rebaseCommand.call();
}

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

License:Apache License

@Override
public boolean rebase(String upStreamBranchName) {

    RebaseCommand command = _git.rebase();
    RebaseResult result = null;/*from  w w w . j ava 2  s . c o  m*/
    try {
        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:org.codehaus.mojo.versions.BumpMojo.java

License:Apache License

void gitRebase() throws MojoExecutionException {
    try {//from w  w w.  j a v  a  2  s .c  om
        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.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public RebaseResponse rebase(RebaseRequest request) throws GitException {
    RebaseResult result;//from  ww w.j av a2s.  c o m
    RebaseStatus status;
    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.op.SquashCommitsOperation.java

License:Open Source License

@Override
public void execute(IProgressMonitor m) throws CoreException {

    IWorkspaceRunnable action = new IWorkspaceRunnable() {
        @Override/*from  w  w w  .j  a v  a2s  .  c o  m*/
        public void run(IProgressMonitor pm) throws CoreException {
            SubMonitor progress = SubMonitor.convert(pm, 2);

            progress.subTask(MessageFormat.format(CoreText.SquashCommitsOperation_squashing,
                    Integer.valueOf(commits.size())));

            InteractiveHandler handler = new InteractiveHandler() {
                @Override
                public void prepareSteps(List<RebaseTodoLine> steps) {
                    RevCommit firstCommit = commits.get(0);
                    for (RebaseTodoLine step : steps) {
                        if (isRelevant(step.getCommit())) {
                            try {
                                if (step.getCommit().prefixCompare(firstCommit) == 0)
                                    step.setAction(RebaseTodoLine.Action.PICK);
                                else
                                    step.setAction(RebaseTodoLine.Action.SQUASH);
                            } catch (IllegalTodoFileModification e) {
                                // shouldn't happen
                            }
                        }
                    }
                }

                private boolean isRelevant(AbbreviatedObjectId id) {
                    for (RevCommit commit : commits) {
                        if (id.prefixCompare(commit) == 0)
                            return true;
                    }
                    return false;
                }

                @Override
                public String modifyCommitMessage(String oldMessage) {
                    return messageHandler.modifyCommitMessage(oldMessage);
                }
            };
            try (Git git = new Git(repository)) {
                RebaseCommand command = git.rebase().setUpstream(commits.get(0).getParent(0))
                        .runInteractively(handler).setOperation(RebaseCommand.Operation.BEGIN);
                MergeStrategy strategy = Activator.getDefault().getPreferredMergeStrategy();
                if (strategy != null) {
                    command.setStrategy(strategy);
                }
                command.call();
            } catch (GitAPIException e) {
                throw new TeamException(e.getLocalizedMessage(), e.getCause());
            }
            progress.worked(1);

            ProjectUtil.refreshValidProjects(ProjectUtil.getValidOpenProjects(repository),
                    progress.newChild(1));
        }
    };
    ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, m);
}

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

License:Open Source License

private boolean rebase(HttpServletRequest request, HttpServletResponse response, Repository db,
        String commitToRebase, String rebaseOperation)
        throws ServletException, JSONException, AmbiguousObjectException, IOException {
    JSONObject result = new JSONObject();
    try {/*w ww  .java 2 s.  c o m*/
        Git git = new Git(db);
        RebaseCommand rebase = git.rebase();
        Operation operation;
        if (rebaseOperation != null) {
            operation = Operation.valueOf(rebaseOperation);
        } else {
            operation = Operation.BEGIN;
        }
        if (commitToRebase != null && !commitToRebase.isEmpty()) {
            ObjectId objectId = db.resolve(commitToRebase);
            rebase.setUpstream(objectId);
        } else if (operation.equals(Operation.BEGIN)) {
            return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_BAD_REQUEST, "Missing commit refId.", null));
        }
        rebase.setOperation(operation);
        RebaseResult rebaseResult = rebase.call();
        result.put(GitConstants.KEY_RESULT, rebaseResult.getStatus().name());
    } catch (UnmergedPathsException e) {
        // this error should be handled by client, so return a proper status
        result.put(GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_UNMERGED_PATHS.name());
    } catch (WrongRepositoryStateException e) {
        // this error should be handled by client, so return a proper status
        result.put(GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_WRONG_REPOSITORY_STATE.name());
    } catch (IllegalArgumentException e) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Invalid rebase operation.", e));
    } catch (GitAPIException e) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when rebasing.", e));
    } catch (JGitInternalException e) {
        // get cause and try to handle 
        if (e.getCause() instanceof org.eclipse.jgit.errors.CheckoutConflictException) {
            // this error should be handled by client, so return a proper status
            result.put(GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_PENDING_CHANGES.name());
        } else {
            return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when rebasing.", e));
        }
    }
    OrionServlet.writeJSONResponse(request, response, result);
    return true;
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

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

    SubMonitor subMon = SubMonitor.convert(monitor, 100);
    List<PropertyFileDiff> updatedFiles = new ArrayList<PropertyFileDiff>();
    try {/*from   www. jav  a  2 s .  c  om*/
        Repository repository = createRepository(project);
        Git git = Git.wrap(repository);
        FetchCommand fetchCommand = git.fetch();
        URI uri = project.getParent().getRepositoryURI();
        if (uri != null)
            fetchCommand.setRemote(stripUserInfo(uri).toString());
        String refspecString = "refs/heads/{0}:refs/remotes/origin/{0}";
        refspecString = MessageFormat.format(refspecString, project.getName());
        RefSpec spec = new RefSpec(refspecString);
        fetchCommand.setRefSpecs(spec);
        subMon.subTask("Fetching from remote");
        if (!"https".equals(uri.scheme()) && !"http".equals(uri.scheme()))
            fetchCommand.setTransportConfigCallback(createTransportConfigCallback(project.getParent()));
        fetchCommand.setCredentialsProvider(createCredentialsProvider(project.getParent()));
        fetchCommand.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(80)));
        fetchCommand.call();
        ObjectId remoteHead = repository.resolve("refs/remotes/origin/" + project.getName() + "^{tree}");

        DiffCommand diff = git.diff();
        subMon.subTask("Caculating Diff");
        diff.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(20)));
        diff.setOldTree(new FileTreeIterator(repository));
        CanonicalTreeParser p = new CanonicalTreeParser();
        ObjectReader reader = repository.newObjectReader();
        try {
            p.reset(reader, remoteHead);
        } finally {
            reader.release();
        }
        diff.setNewTree(p);
        checkCanceled(subMon);
        List<DiffEntry> diffs = diff.call();
        for (DiffEntry diffEntry : diffs) {
            checkCanceled(subMon);
            updatedFiles.add(convertDiffEntry(diffEntry));
            LOGGER.trace(diffEntry.toString());
        }
        if (!updatedFiles.isEmpty()) {
            checkCanceled(subMon);
            //no more cancel after this point
            ObjectId lastCommitID = repository
                    .resolve("refs/remotes/origin/" + project.getName() + "^{commit}");
            LOGGER.info("Merging remote commit {} to {}/{}",
                    new Object[] { lastCommitID, project.getName(), project.getParent().getName() });
            //TODO: use rebase here?
            if (isRebase(project)) {
                RebaseCommand rebase = git.rebase();
                rebase.setUpstream("refs/remotes/origin/" + project.getName());
                RebaseResult result = rebase.call();
                if (result.getStatus().isSuccessful()) {
                    LOGGER.info("Rebase finished: {}", result.getStatus());
                } else {
                    LOGGER.error("Rebase of {} failed. Attempting abort", project.relativePath());
                    rebase = git.rebase();
                    rebase.setOperation(Operation.ABORT);
                    result = rebase.call();
                    LOGGER.error("Abort finished with {}", result.getStatus());
                }
            } else {
                MergeCommand merge = git.merge();
                merge.include(lastCommitID);
                MergeResult mergeResult = merge.call();

                LOGGER.info("Merge finished: {}", mergeResult.getMergeStatus());
            }
        } else
            LOGGER.info("Update finished successfully. Nothing to merge, already up to date");
    } catch (JGitInternalException e) {
        throw new TeamProviderException(e);
    } catch (InvalidRemoteException e) {
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        throw new TeamProviderException(e);
    } catch (AmbiguousObjectException e) {
        throw new TeamProviderException(e);
    } catch (IOException e) {
        throw new TeamProviderException(e);
    } finally {
        monitor.done();
    }
    return updatedFiles;
}