Example usage for org.eclipse.jgit.api CreateBranchCommand setUpstreamMode

List of usage examples for org.eclipse.jgit.api CreateBranchCommand setUpstreamMode

Introduction

In this page you can find the example usage for org.eclipse.jgit.api CreateBranchCommand setUpstreamMode.

Prototype

public CreateBranchCommand setUpstreamMode(SetupUpstreamMode mode) 

Source Link

Document

Set the upstream mode

Usage

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public void switchBranch(String branchName) throws RefNotFoundException, Exception {
    Repository repository = git.getRepository();
    if (branchName != null && !repository.getBranch().equals(branchName)) {
        log.info("Switching branch from {} to {}", repository.getBranch(), branchName);
        CheckoutCommand checkout = git.checkout();
        if (isTag(branchName)) {
            checkout.setName(branchName);
        } else {//from   www .  jav  a  2 s  . co m
            checkout.setName("refs/heads/" + branchName);
            if (repository.getRef("refs/heads/" + branchName) == null) {
                CreateBranchCommand create = git.branchCreate();
                create.setName(branchName);
                create.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
                create.setStartPoint("origin/" + branchName);
                create.call();
            }
        }
        checkout.call();
    }
}

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

License:Open Source License

/**
 * /* w ww  .  j  a  v  a 2s .c om*/
 * Creates new branch from a particular start point
 * 
 * @param name
 *            the branch name
 * @param startPoint
 *            valid tree-ish object example: "5c15e8", "master", "HEAD",
 *            "21d5a96070353d01c0f30bc0559ab4de4f5e3ca0"
 * @throws RefAlreadyExistsException
 * @throws RefNotFoundException
 * @throws InvalidRefNameException
 * @throws GitAPIException
 */
public void createBranch(String name, String startPoint)
        throws RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, GitAPIException {
    repository.getConfig().setString(BRANCH, name, MERGE, REFS_HEADS_MASTER);
    CreateBranchCommand createBranchCommand = git.branchCreate();
    createBranchCommand.setName(name);
    createBranchCommand.setStartPoint(startPoint);
    createBranchCommand.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
    createBranchCommand.call();
}

From source file:org.ajoberstar.gradle.git.tasks.GitBranchCreate.java

License:Apache License

/**
 * Execute the creation or update of the branch.
 *//* www  . j a va  2s . c  om*/
@TaskAction
void branchCreate() {
    CreateBranchCommand cmd = getGit().branchCreate();
    cmd.setName(getBranchName());
    cmd.setStartPoint(getStartPoint());
    cmd.setForce(getForce());

    if (getMode() != null) {
        switch (getMode()) {
        case NO_TRACK:
            cmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            break;
        case TRACK:
            cmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
            break;
        case SET_UPSTREAM:
            cmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM);
            break;
        default:
            throw new AssertionError("Illegal mode: " + getMode());
        }
    }

    try {
        cmd.call();
    } catch (InvalidRefNameException e) {
        throw new GradleException("Invalid branch name: " + getName(), e);
    } catch (RefNotFoundException e) {
        throw new GradleException("Can't find start point: " + getStartPoint(), e);
    } catch (RefAlreadyExistsException e) {
        throw new GradleException("Branch " + getName() + " already exists. Use force=true to modify.", e);
    } catch (GitAPIException e) {
        throw new GradleException("Problem creating or updating branch " + getName(), e);
    }
}

From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

private static void createBranch(SetupTaskContext context, Git git, String checkoutBranch, String remoteName)
        throws Exception {
    context.log("Creating local branch " + checkoutBranch);

    CreateBranchCommand command = git.branchCreate();
    command.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
    command.setName(checkoutBranch);/*from w  w  w  . j a  v  a 2 s  . c  o m*/
    command.setStartPoint("refs/remotes/" + remoteName + "/" + checkoutBranch);
    command.call();

    StoredConfig config = git.getRepository().getConfig();
    config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, checkoutBranch, ConfigConstants.CONFIG_KEY_REBASE,
            true);
    config.save();
}

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

License:Open Source License

private boolean handlePost(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException,
        JGitInternalException, GitAPIException {
    Path p = new Path(path);
    // expected path /gitapi/branch/file/{path}
    if (p.segment(0).equals("file")) { //$NON-NLS-1$

        JSONObject toCreate = OrionServlet.readJSONRequest(request);
        String branchName = toCreate.optString(ProtocolConstants.KEY_NAME, null);
        String startPoint = toCreate.optString(GitConstants.KEY_BRANCH_NAME, null);

        if (branchName == null || branchName.isEmpty()) {
            if (startPoint == null || startPoint.isEmpty())
                return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                        HttpServletResponse.SC_BAD_REQUEST, "Branch name must be provided", null));
            else {
                String shortName = Repository.shortenRefName(startPoint);
                branchName = shortName.substring(shortName.lastIndexOf("/") + 1); //$NON-NLS-1$
            }//  www .  j ava2  s  . c  om
        }

        File gitDir = GitUtils.getGitDir(p);
        Repository db = new FileRepository(gitDir);
        Git git = new Git(db);

        CreateBranchCommand cc = git.branchCreate();
        cc.setName(branchName);

        if (startPoint != null && !startPoint.isEmpty()) {
            cc.setStartPoint(startPoint);
            cc.setUpstreamMode(SetupUpstreamMode.TRACK);
        }

        Ref ref = cc.call();

        // TODO: what if something went wrong, handle exception
        JSONObject result = BranchToJSONConverter.toJSON(ref, db, getURI(request), 2);
        OrionServlet.writeJSONResponse(request, response, result);
        response.setHeader(ProtocolConstants.HEADER_LOCATION, result.getString(ProtocolConstants.KEY_LOCATION));
        response.setStatus(HttpServletResponse.SC_CREATED);
        return true;
    }
    String msg = NLS.bind("Failed to create a branch for {0}", path); //$NON-NLS-1$
    return statusHandler.handleRequest(request, response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}

From source file:org.fedoraproject.eclipse.packager.git.FedoraPackagerGitCloneOperation.java

License:Open Source License

/**
 * Create local branches based on existing remotes (uses the JGit API).
 * //  w w w.j a v  a  2 s .co  m
 * @param monitor
 * @throws CoreException
 */
private void createLocalBranches(Git git, IProgressMonitor monitor) throws CoreException {
    monitor.beginTask(FedoraPackagerGitText.FedoraPackagerGitCloneWizard_createLocalBranchesJob,
            IProgressMonitor.UNKNOWN);

    try {
        // get a list of remote branches
        ListBranchCommand branchList = git.branchList();
        branchList.setListMode(ListMode.REMOTE); // want all remote branches
        List<Ref> remoteRefs = branchList.call();
        for (Ref remoteRef : remoteRefs) {
            String name = remoteRef.getName();
            int index = (Constants.R_REMOTES + "origin/").length(); //$NON-NLS-1$
            // Remove "refs/remotes/origin/" part in branch name
            name = name.substring(index);
            // Use "f14"-like branch naming
            if (name.endsWith("/" + Constants.MASTER)) { //$NON-NLS-1$
                index = name.indexOf("/" + Constants.MASTER); //$NON-NLS-1$
                name = name.substring(0, index);
            }
            // Create all remote branches, except "master"
            if (!name.equals(Constants.MASTER)) {
                CreateBranchCommand branchCreateCmd = git.branchCreate();
                branchCreateCmd.setName(name);
                // Need to set starting point this way in order for tracking
                // to work properly. See: https://bugs.eclipse.org/bugs/show_bug.cgi?id=333899
                branchCreateCmd.setStartPoint(remoteRef.getName());
                // Add remote tracking config in order to not confuse
                // fedpkg
                branchCreateCmd.setUpstreamMode(SetupUpstreamMode.TRACK);
                branchCreateCmd.call();
            }
        }
    } catch (JGitInternalException e) {
        e.printStackTrace();
    } catch (RefAlreadyExistsException e) {
        e.printStackTrace();
    } catch (RefNotFoundException e) {
        e.printStackTrace();
    } catch (InvalidRefNameException e) {
        e.printStackTrace();
    }
}

From source file:org.fedoraproject.eclipse.packager.git.GitUtils.java

License:Open Source License

/**
 * Create local branches based on existing remotes (uses the JGit API).
 *
 * @param git//from   w  ww  . j a  va2 s  . c o m
 * @param monitor
 * @throws CoreException
 */
public static void createLocalBranches(Git git, IProgressMonitor monitor) throws CoreException {
    monitor.beginTask(FedoraPackagerGitText.FedoraPackagerGitCloneWizard_createLocalBranchesJob,
            IProgressMonitor.UNKNOWN);
    try {
        // get a list of remote branches
        ListBranchCommand branchList = git.branchList();
        branchList.setListMode(ListMode.REMOTE); // want all remote branches
        List<Ref> remoteRefs = branchList.call();
        for (Ref remoteRef : remoteRefs) {
            String name = remoteRef.getName();
            int index = (Constants.R_REMOTES + "origin/").length(); //$NON-NLS-1$
            // Remove "refs/remotes/origin/" part in branch name
            name = name.substring(index);
            // Use "f14"-like branch naming
            if (name.endsWith("/" + Constants.MASTER)) { //$NON-NLS-1$
                index = name.indexOf("/" + Constants.MASTER); //$NON-NLS-1$
                name = name.substring(0, index);
            }
            // Create all remote branches, except "master"
            if (!name.equals(Constants.MASTER)) {
                CreateBranchCommand branchCreateCmd = git.branchCreate();
                branchCreateCmd.setName(name);
                // Need to set starting point this way in order for tracking
                // to work properly. See:
                // https://bugs.eclipse.org/bugs/show_bug.cgi?id=333899
                branchCreateCmd.setStartPoint(remoteRef.getName());
                // Add remote tracking config in order to not confuse
                // fedpkg
                branchCreateCmd.setUpstreamMode(SetupUpstreamMode.TRACK);
                if (monitor.isCanceled()) {
                    throw new OperationCanceledException();
                }
                branchCreateCmd.call();
            }
        }
    } catch (JGitInternalException e) {
        e.printStackTrace();
    } catch (RefAlreadyExistsException e) {
        e.printStackTrace();
    } catch (RefNotFoundException e) {
        e.printStackTrace();
    } catch (InvalidRefNameException e) {
        e.printStackTrace();
    }
}

From source file:util.ChkoutCmd.java

License:Eclipse Distribution License

/**
 * @throws RefAlreadyExistsException// w  w  w. j  av a 2 s  . c o  m
 *             when trying to create (without force) a branch with a name
 *             that already exists
 * @throws RefNotFoundException
 *             if the start point or branch can not be found
 * @throws InvalidRefNameException
 *             if the provided name is <code>null</code> or otherwise
 *             invalid
 * @throws CheckoutConflictException
 *             if the checkout results in a conflict
 * @return the newly created branch
 */
public Ref call() throws GitAPIException, RefAlreadyExistsException, RefNotFoundException,
        InvalidRefNameException, CheckoutConflictException {
    checkCallable();
    processOptions();
    try {
        if (checkoutAllPaths || !paths.isEmpty()) {
            checkoutPaths();
            status = new CheckoutResult(Status.OK, paths);
            setCallable(false);
            return null;
        }

        if (createBranch) {
            Git git = new Git(repo);
            CreateBranchCommand command = git.branchCreate();
            command.setName(name);
            command.setStartPoint(getStartPoint().name());
            if (upstreamMode != null)
                command.setUpstreamMode(upstreamMode);
            command.call();
        }

        Ref headRef = repo.getRef(Constants.HEAD);
        String shortHeadRef = getShortBranchName(headRef);
        String refLogMessage = "checkout: moving from " + shortHeadRef; //$NON-NLS-1$
        ObjectId branch = repo.resolve(name);
        if (branch == null)
            throw new RefNotFoundException(MessageFormat.format(JGitText.get().refNotResolved, name));

        RevWalk revWalk = new RevWalk(repo);
        AnyObjectId headId = headRef.getObjectId();
        RevCommit headCommit = headId == null ? null : revWalk.parseCommit(headId);
        RevCommit newCommit = revWalk.parseCommit(branch);
        RevTree headTree = headCommit == null ? null : headCommit.getTree();
        DirCacheCheckout dco;
        DirCache dc = repo.lockDirCache();
        try {
            dco = new DirCacheCheckout(repo, headTree, dc, newCommit.getTree());
            dco.setFailOnConflict(false);
            try {
                dco.checkout();
            } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
                status = new CheckoutResult(Status.CONFLICTS, dco.getConflicts());
                throw new CheckoutConflictException(dco.getConflicts(), e);
            }
        } finally {
            dc.unlock();
        }
        Ref ref = repo.getRef(name);
        if (ref != null && !ref.getName().startsWith(Constants.R_HEADS))
            ref = null;
        String toName = Repository.shortenRefName(name);
        RefUpdate refUpdate = repo.updateRef(Constants.HEAD, ref == null);
        refUpdate.setForceUpdate(force);
        refUpdate.setRefLogMessage(refLogMessage + " to " + toName, false); //$NON-NLS-1$
        Result updateResult;
        if (ref != null)
            updateResult = refUpdate.link(ref.getName());
        else {
            refUpdate.setNewObjectId(newCommit);
            updateResult = refUpdate.forceUpdate();
        }

        setCallable(false);

        boolean ok = false;
        switch (updateResult) {
        case NEW:
            ok = true;
            break;
        case NO_CHANGE:
        case FAST_FORWARD:
        case FORCED:
            ok = true;
            break;
        default:
            break;
        }

        if (!ok)
            throw new JGitInternalException(
                    MessageFormat.format(JGitText.get().checkoutUnexpectedResult, updateResult.name()));

        if (!dco.getToBeDeleted().isEmpty()) {
            status = new CheckoutResult(Status.NONDELETED, dco.getToBeDeleted());
        } else
            status = new CheckoutResult(new ArrayList<String>(dco.getUpdated().keySet()), dco.getRemoved());

        return ref;
    } catch (IOException ioe) {
        throw new JGitInternalException(ioe.getMessage(), ioe);
    } finally {
        if (status == null)
            status = CheckoutResult.ERROR_RESULT;
    }
}