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

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

Introduction

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

Prototype

public RebaseCommand setUpstream(String upstream) throws RefNotFoundException 

Source Link

Document

Set the upstream branch

Usage

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

License:Open Source License

/**
 * //from  w  w w  . j  a  v  a  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 .ja va2  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  ava 2s  .  co  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.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public RebaseResponse rebase(RebaseRequest request) throws GitException {
    RebaseResult result;// w  ww .java2s  . 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.RebaseOperation.java

License:Open Source License

public void execute(IProgressMonitor m) throws CoreException {
    if (result != null)
        throw new CoreException(
                new Status(IStatus.ERROR, Activator.getPluginId(), CoreText.OperationAlreadyExecuted));
    IProgressMonitor monitor;/*  w w w  .  jav a2  s . c  o  m*/
    if (m == null)
        monitor = new NullProgressMonitor();
    else
        monitor = m;

    IWorkspaceRunnable action = new IWorkspaceRunnable() {
        public void run(IProgressMonitor actMonitor) throws CoreException {
            RebaseCommand cmd = new Git(repository).rebase()
                    .setProgressMonitor(new EclipseGitProgressTransformer(actMonitor));
            try {
                if (operation == Operation.BEGIN)
                    result = cmd.setUpstream(ref.getName()).call();
                else
                    result = cmd.setOperation(operation).call();

            } catch (NoHeadException e) {
                throw new CoreException(Activator.error(e.getMessage(), e));
            } catch (RefNotFoundException e) {
                throw new CoreException(Activator.error(e.getMessage(), e));
            } catch (JGitInternalException e) {
                throw new CoreException(Activator.error(e.getMessage(), e));
            } catch (GitAPIException e) {
                throw new CoreException(Activator.error(e.getMessage(), e));
            }
        }
    };
    ResourcesPlugin.getWorkspace().run(action, monitor);
}

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  w w. j av a  2 s . c  om
        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.flowerplatform.web.git.operation.internal.PullCommand.java

License:Open Source License

/**
 * Executes the {@code Pull} command with all the options and parameters
 * collected by the setter methods (e.g.
 * {@link #setProgressMonitor(ProgressMonitor)}) of this class. Each
 * instance of this class should only be used for one invocation of the
 * command. Don't call this method twice on an instance.
 *
 * @return the result of the pull//from  w  w  w.j av a  2 s  .  co m
 * @throws WrongRepositoryStateException
 * @throws InvalidConfigurationException
 * @throws DetachedHeadException
 * @throws InvalidRemoteException
 * @throws CanceledException
 * @throws RefNotFoundException
 * @throws NoHeadException
 * @throws org.eclipse.jgit.api.errors.TransportException
 * @throws GitAPIException
 */
@SuppressWarnings("restriction")
public PullResult call() throws GitAPIException, WrongRepositoryStateException, InvalidConfigurationException,
        DetachedHeadException, InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException,
        org.eclipse.jgit.api.errors.TransportException {
    checkCallable();

    monitor.beginTask(JGitText.get().pullTaskName, 2);

    Object[] data = GitPlugin.getInstance().getUtils().getFetchPushUpstreamDataRefSpecAndRemote(repo);

    String fullBranch = (String) data[0];
    String branchName = fullBranch.substring(Constants.R_HEADS.length());

    if (!repo.getRepositoryState().equals(RepositoryState.SAFE))
        throw new WrongRepositoryStateException(MessageFormat.format(JGitText.get().cannotPullOnARepoWithState,
                repo.getRepositoryState().name()));

    // get the configured remote for the currently checked out branch
    // stored in configuration key branch.<branch name>.remote
    Config repoConfig = repo.getConfig();
    String remote = repoConfig.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
            ConfigConstants.CONFIG_KEY_REMOTE);
    if (remote == null)
        // fall back to default remote
        remote = Constants.DEFAULT_REMOTE_NAME;

    // get the name of the branch in the remote repository
    // stored in configuration key branch.<branch name>.merge
    String remoteBranchName = (String) data[1];

    // determines whether rebase should be used after fetching
    boolean doRebase = (boolean) data[3];

    final boolean isRemote = !remote.equals("."); //$NON-NLS-1$
    String remoteUri;
    FetchResult fetchRes;
    if (isRemote) {
        remoteUri = (String) data[2];

        if (monitor.isCancelled())
            throw new CanceledException(
                    MessageFormat.format(JGitText.get().operationCanceled, JGitText.get().pullTaskName));

        RefSpec refSpec = new RefSpec();
        refSpec = refSpec.setForceUpdate(true);
        refSpec = refSpec.setSourceDestination(remoteBranchName, fullBranch);

        FetchCommand fetch = new Git(repo).fetch().setRemote(remote).setRefSpecs(refSpec);

        fetch.setProgressMonitor(monitor);
        configure(fetch);

        fetchRes = fetch.call();
    } else {
        // we can skip the fetch altogether
        remoteUri = "local repository";
        fetchRes = null;
    }

    monitor.update(1);

    if (monitor.isCancelled())
        throw new CanceledException(
                MessageFormat.format(JGitText.get().operationCanceled, JGitText.get().pullTaskName));

    // we check the updates to see which of the updated branches
    // corresponds
    // to the remote branch name
    AnyObjectId commitToMerge;
    if (isRemote) {
        Ref r = null;
        if (fetchRes != null) {
            r = fetchRes.getAdvertisedRef(remoteBranchName);
            if (r == null)
                r = fetchRes.getAdvertisedRef(Constants.R_HEADS + remoteBranchName);
        }
        if (r == null)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().couldNotGetAdvertisedRef, remoteBranchName));
        else
            commitToMerge = r.getObjectId();
    } else {
        try {
            commitToMerge = repo.resolve(remoteBranchName);
            if (commitToMerge == null)
                throw new RefNotFoundException(
                        MessageFormat.format(JGitText.get().refNotResolved, remoteBranchName));
        } catch (IOException e) {
            throw new JGitInternalException(JGitText.get().exceptionCaughtDuringExecutionOfPullCommand, e);
        }
    }

    String upstreamName = "branch \'" + Repository.shortenRefName(remoteBranchName) + "\' of " + remoteUri;

    PullResult result;
    if (doRebase) {
        RebaseCommand rebase = new Git(repo).rebase();
        RebaseResult rebaseRes = rebase.setUpstream(commitToMerge).setUpstreamName(upstreamName)
                .setProgressMonitor(monitor).setOperation(Operation.BEGIN).call();
        result = new PullResult(fetchRes, remote, rebaseRes);
    } else {
        MergeCommand merge = new Git(repo).merge();
        merge.include(upstreamName, commitToMerge);
        MergeResult mergeRes = merge.call();
        monitor.update(1);
        result = new PullResult(fetchRes, remote, mergeRes);
    }
    monitor.endTask();
    return result;
}

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

License:Open Source License

public void execute() throws Exception {
    ProgressMonitor monitor = ProgressMonitor.create(GitPlugin.getInstance().getMessage("git.rebase"), channel);

    monitor.beginTask(GitPlugin.getInstance().getMessage("git.rebase.title", new Object[] { refName }), 2);

    //      IProject[] validProjects = GitPlugin.getInstance().getGitUtils().getValidProjects(repository);
    //      GitPlugin.getInstance().getGitUtils().backupProjectConfigFiles(null, validProjects);

    RebaseCommand cmd = new Git(repository).rebase().setProgressMonitor(new GitProgressMonitor(monitor));

    try {//w w w  .  j  ava2 s.co  m
        cmd.setUpstream(refName);
        rebaseResult = (RebaseResult) GitPlugin.getInstance().getUtils()
                .runGitCommandInUserRepoConfig(repository, cmd);

    } catch (Exception e) {
        throw e;
    } finally {
        //         if (refreshNeeded()) {
        //            GitPlugin.getInstance().getGitUtils().refreshValidProjects(validProjects, new SubProgressMonitor(monitor, 1));
        //         }
        //         GitPlugin.getInstance().getGitUtils().restoreProjectConfigFiles(repository, null);
        monitor.done();
    }
}

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   ww w . j a va  2  s .co m*/
        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;
}