Example usage for org.eclipse.jgit.api Git branchCreate

List of usage examples for org.eclipse.jgit.api Git branchCreate

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git branchCreate.

Prototype

public CreateBranchCommand branchCreate() 

Source Link

Document

Return a command object used to create branches

Usage

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 ww  .  j a v a  2s  . 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$
            }/*from w ww .j  a v  a  2 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.enterprisedomain.classmaker.impl.RevisionImpl.java

License:Apache License

/**
 * <!-- begin-user-doc --> <!-- end-user-doc -->
 * //from w  w w  . j  av  a  2s . c o  m
 * @generated NOT
 */
public void create(IProgressMonitor monitor) throws CoreException {
    if (isStateSet()) {
        @SuppressWarnings("unchecked")
        SCMOperator<Git> operator = (SCMOperator<Git>) getProject().getWorkspace().getSCMRegistry()
                .get(getProject().getProjectName());
        try {
            Git git = operator.getRepositorySCM();
            git.branchCreate().setForce(true).setName(getVersion().toString()).call();
        } catch (Exception e) {
            throw new CoreException(ClassMakerPlugin.createErrorStatus(e));
        } finally {
            try {
                operator.ungetRepositorySCM();
            } catch (Exception e) {
                throw new CoreException(ClassMakerPlugin.createErrorStatus(e));
            }
        }
    }

}

From source file:org.exist.git.xquery.BranchCreate.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {/*from ww  w  .java 2s  .c  o  m*/
        String localPath = args[0].getStringValue();
        if (!(localPath.endsWith("/")))
            localPath += File.separator;

        Git git = Git.open(new Resource(localPath), FS);

        git.branchCreate().setName(args[1].getStringValue())
                .setStartPoint(
                        args.length <= 2 || args[2].isEmpty() ? Constants.HEAD : args[2].getStringValue())
                .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM).setForce(true).call();

        return BooleanValue.TRUE;
    } catch (Throwable e) {
        throw new XPathException(this, Module.EXGIT001, e);
    }
}

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).
 * /*from   w w  w . j a v a 2s.  c  o 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//w  w w.  j av  a2  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:org.flowerplatform.web.git.operation.CheckoutOperation.java

License:Open Source License

public boolean execute() {
    ProgressMonitor monitor = ProgressMonitor
            .create(GitPlugin.getInstance().getMessage("git.checkout.monitor.title"), channel);

    try {//from w w w.jav  a2s . c o m
        monitor.beginTask(
                GitPlugin.getInstance().getMessage("git.checkout.monitor.message", new Object[] { name }), 4);
        monitor.setTaskName("Getting remote branch...");
        Git git = new Git(repository);
        Ref ref;
        if (node instanceof Ref) {
            ref = (Ref) node;
        } else {
            // get remote branch
            String dst = Constants.R_REMOTES + remote.getName();
            String remoteRefName = dst + "/" + upstreamBranch.getShortName();
            ref = repository.getRef(remoteRefName);
            if (ref == null) { // doesn't exist, fetch it
                RefSpec refSpec = new RefSpec();
                refSpec = refSpec.setForceUpdate(true);
                refSpec = refSpec.setSourceDestination(upstreamBranch.getName(), remoteRefName);

                git.fetch().setRemote(new URIish(remote.getUri()).toPrivateString()).setRefSpecs(refSpec)
                        .call();

                ref = repository.getRef(remoteRefName);
            }
        }
        monitor.worked(1);
        monitor.setTaskName("Creating local branch...");

        // create local branch
        git.branchCreate().setName(name).setStartPoint(ref.getName())
                .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM).call();

        if (!(node instanceof Ref)) {
            // save upstream configuration
            StoredConfig config = repository.getConfig();

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_MERGE,
                    upstreamBranch.getName());

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REMOTE,
                    remote.getName());

            if (rebase) {
                config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, name,
                        ConfigConstants.CONFIG_KEY_REBASE, true);
            } else {
                config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REBASE);
            }
            config.save();
        }
        monitor.worked(1);
        monitor.setTaskName("Creating working directory");

        // create working directory for local branch
        File mainRepoFile = repository.getDirectory().getParentFile();
        File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + name);
        if (wdirFile.exists()) {
            GitPlugin.getInstance().getUtils().delete(wdirFile);
        }
        GitPlugin.getInstance().getUtils().run_git_workdir_cmd(mainRepoFile.getAbsolutePath(),
                wdirFile.getAbsolutePath());
        monitor.worked(1);
        monitor.setTaskName("Checkout branch");

        // checkout local branch
        Repository wdirRepo = GitPlugin.getInstance().getUtils().getRepository(wdirFile);
        git = new Git(wdirRepo);

        CheckoutCommand cc = git.checkout().setName(name).setForce(true);
        cc.call();

        // show checkout result
        if (cc.getResult().getStatus() == CheckoutResult.Status.CONFLICTS)
            channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.title"),
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.message"),
                    cc.getResult().getConflictList().toString(),
                    DisplaySimpleMessageClientCommand.ICON_INFORMATION));

        else if (cc.getResult().getStatus() == CheckoutResult.Status.NONDELETED) {
            // double-check if the files are still there
            boolean show = false;
            List<String> pathList = cc.getResult().getUndeletedList();
            for (String path1 : pathList) {
                if (new File(wdirRepo.getWorkTree(), path1).exists()) {
                    show = true;
                    break;
                }
            }
            if (show) {
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.message",
                                Repository.shortenRefName(name)),
                        cc.getResult().getUndeletedList().toString(),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
            }
        } else if (cc.getResult().getStatus() == CheckoutResult.Status.OK) {
            if (ObjectId.isId(wdirRepo.getFullBranch()))
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.message"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
        }
        monitor.worked(1);
        return true;
    } catch (Exception e) {
        channel.appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    } finally {
        monitor.done();
    }
}

From source file:org.gitective.tests.GitTestCase.java

License:Open Source License

/**
 * Create branch with name and checkout/*w  ww . j  a  va2  s.c  o  m*/
 *
 * @param repo
 * @param name
 * @return branch ref
 * @throws Exception
 */
protected Ref branch(File repo, String name) throws Exception {
    Git git = Git.open(repo);
    git.branchCreate().setName(name).call();
    return checkout(repo, name);
}

From source file:org.jboss.forge.addon.git.GitUtilsImpl.java

License:Open Source License

@Override
public Ref createBranch(Git git, String branchName) throws GitAPIException {
    Ref newBranch = git.branchCreate().setName(branchName).call();

    if (newBranch == null)
        throw new RuntimeException("Couldn't create new branch " + branchName);

    return newBranch;
}

From source file:org.jboss.forge.addon.git.GitUtilsTest.java

License:Open Source License

@Test
public void shouldCherryPickChanges() throws Exception {
    // git init/*from   w ww . ja  v a 2  s.  c  o  m*/
    // create new branch (b2) but stay on master
    // commit new file #1
    // switch to other branch
    // commit new file #2
    // switch to master
    // cherry pick the latest commit from b2
    // verify file #2 exists
    // verify number of commits (3 on master branch)

    String[] branchNames = { "master", "branch_two" };
    String[] files = { "test1.txt", "test2.txt" };

    Project project = projectFactory.createTempProject();
    Git repo = gitUtils.init(project.getRoot().reify(DirectoryResource.class));

    gitUtils.addAll(repo);
    gitUtils.commitAll(repo, "initial commit");

    repo.branchCreate().setName(branchNames[1]).call();

    FileResource<?> file0 = project.getRoot().getChild(files[0]).reify(FileResource.class);
    file0.createNewFile();
    gitUtils.add(repo, files[0]);
    gitUtils.commit(repo, "file added on " + branchNames[0]);

    gitUtils.switchBranch(repo, branchNames[1]);

    FileResource<?> file1 = project.getRoot().getChild(files[1]).reify(FileResource.class);
    file1.createNewFile();
    gitUtils.add(repo, files[1]);
    gitUtils.commit(repo, "file added on " + branchNames[1]);

    gitUtils.getLogForCurrentBranch(repo);

    gitUtils.switchBranch(repo, branchNames[0]);
    Ref branch2Ref = repo.getRepository().findRef(branchNames[1]);
    gitUtils.cherryPick(repo, branch2Ref);

    // assert file2 exists
    Assert.assertTrue("file from cherry picked commit should exist",
            project.getRoot().getChild(files[1]).exists());

    // assert number of commits (on master). Should be 3, latest created by the merge from cherry pick
    List<String> log = gitUtils.getLogForCurrentBranch(repo);
    Assert.assertEquals("wrong number of commits", 3, log.size());
}