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.jboss.forge.addon.git.GitUtilsTest.java

License:Open Source License

@Test
public void shouldCherryPickChangesWithoutNewCommit() throws Exception {
    // git init// w ww. j a v  a 2s.  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 (without committing) the latest commit from b2
    // verify file #2 exists
    // verify number of commits (2 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.cherryPickNoMerge(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 2 (cherry pick produced no merge)
    List<String> log = gitUtils.getLogForCurrentBranch(repo);
    Assert.assertEquals("wrong number of commits", 2, log.size());
}

From source file:org.jboss.forge.git.GitUtils.java

License:Open Source License

public static Ref createBranch(Git git, String branchName)
        throws RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, 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.git.GitUtilsTest.java

License:Open Source License

@Test
public void shouldCherryPickChanges() throws Exception {
    // git init/* w  w w . ja  v a  2  s .  c om*/
    // 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 = initializeJavaProject();
    Git repo = GitUtils.init(project.getProjectRoot());

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

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

    FileResource<?> file0 = project.getProjectRoot().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.getProjectRoot().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().getRef(branchNames[1]);
    GitUtils.cherryPick(repo, branch2Ref);

    // assert file2 exists
    Assert.assertTrue("file from cherry picked commit should exist",
            project.getProjectRoot().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());
}

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

License:Open Source License

@Test
public void shouldCherryPickChangesWithoutNewCommit() throws Exception {
    // git init//w  ww.j  a va2s .co  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 (without committing) the latest commit from b2
    // verify file #2 exists
    // verify number of commits (2 on master branch)

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

    Project project = initializeJavaProject();
    Git repo = GitUtils.init(project.getProjectRoot());

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

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

    FileResource<?> file0 = project.getProjectRoot().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.getProjectRoot().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().getRef(branchNames[1]);
    GitUtils.cherryPickNoMerge(repo, branch2Ref);

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

    // assert number of commits (on master). Should be 2 (cherry pick produced no merge)
    List<String> log = GitUtils.getLogForCurrentBranch(repo);
    Assert.assertEquals("wrong number of commits", 2, log.size());
}

From source file:org.jboss.forge.shell.plugins.builtin.ForgePlugin.java

License:Open Source License

@Command(value = "git-plugin", help = "Install a plugin from a public git repository")
public void installFromGit(@Option(description = "git repo", required = true) final String gitRepo,
        @Option(name = "ref", description = "branch or tag to build") final String refName,
        @Option(name = "checkoutDir", description = "directory in which to clone the repository") final Resource<?> checkoutDir,
        final PipeOut out) throws Exception {

    DirectoryResource workspace = shell.getCurrentDirectory().createTempResource();

    try {//from w  ww .j  a v a2 s.  c o m
        DirectoryResource buildDir = workspace.getChildDirectory("repo");
        if (checkoutDir != null) {
            if (!checkoutDir.exists() && (checkoutDir instanceof FileResource<?>)) {
                ((FileResource<?>) checkoutDir).mkdirs();
            }
            buildDir = checkoutDir.reify(DirectoryResource.class);
        }

        if (buildDir.exists()) {
            buildDir.delete(true);
            buildDir.mkdir();
        }

        prepareProxyForJGit();

        ShellMessages.info(out,
                "Checking out plugin source files to [" + buildDir.getFullyQualifiedName() + "] via 'git'");
        Git repo = GitUtils.clone(buildDir, gitRepo);

        Ref ref = null;
        String targetRef = refName;
        if (targetRef == null) {
            // Default to Forge runtime version if no Ref name is supplied.
            targetRef = environment.getRuntimeVersion();
        }

        if (targetRef != null) {
            // Try to find a Tag matching the given Ref name or runtime version
            Map<String, Ref> tags = repo.getRepository().getTags();
            ref = tags.get(targetRef);

            // Now try to find a matching Branch
            if (ref == null) {
                List<Ref> refs = GitUtils.getRemoteBranches(repo);
                for (Ref branchRef : refs) {
                    String branchName = branchRef.getName();
                    if (branchName != null && branchName.endsWith(targetRef)) {
                        ref = repo.branchCreate().setName(targetRef).setUpstreamMode(SetupUpstreamMode.TRACK)
                                .setStartPoint("origin/" + targetRef).call();
                    }
                }
            }

            // Now try to find a tag or branch with same Major.Minor.(x) version.
            if (ref == null) {
                // All
                List<String> sortedVersions = new ArrayList<String>();

                // Branches
                for (Ref branchRef : GitUtils.getRemoteBranches(repo)) {
                    String branchName = branchRef.getName();
                    branchName = branchName.replaceFirst("refs/heads/", "");
                    if (InstalledPluginRegistry.isApiCompatible(targetRef, branchName))
                        sortedVersions.add(branchName);
                }

                // Tags

                // Branches
                for (String tag : tags.keySet()) {
                    if (InstalledPluginRegistry.isApiCompatible(targetRef, tag))
                        sortedVersions.add(tag);
                }

                // Sort
                Collections.sort(sortedVersions);

                if (!sortedVersions.isEmpty()) {
                    String version = sortedVersions.get(sortedVersions.size() - 1);
                    if (InstalledPluginRegistry.isApiCompatible(targetRef, version)) {
                        ref = tags.get(version);

                        if (ref == null) {
                            ref = repo.branchCreate().setName(version).setUpstreamMode(SetupUpstreamMode.TRACK)
                                    .setStartPoint("origin/" + version).call();
                        }
                    }
                }
            }
        }

        if (ref == null) {
            ref = repo.getRepository().getRef("master");
        }

        if (ref != null) {
            ShellMessages.info(out, "Switching to branch/tag [" + ref.getName() + "]");
            GitUtils.checkout(repo, ref, false, SetupUpstreamMode.TRACK, false);
        } else if (refName != null) {
            throw new RuntimeException("Could not locate ref [" + targetRef + "] in repository ["
                    + repo.getRepository().getDirectory().getAbsolutePath() + "]");
        } else {
            ShellMessages.warn(out, "Could not find a Ref matching the current Forge version ["
                    + environment.getRuntimeVersion() + "], building Plugin from HEAD.");
        }

        buildFromCurrentProject(out, buildDir);
    } finally {
        if (checkoutDir != null) {
            ShellMessages.info(out, "Cleaning up temp workspace [" + workspace.getFullyQualifiedName() + "]");
            workspace.delete(true);
        }
    }

    ShellMessages.success(out, "Installed from [" + gitRepo + "] successfully.");
    restart();
}

From source file:org.kie.commons.java.nio.fs.jgit.util.JGitUtil.java

License:Apache License

public static void syncRepository(final Git git, final CredentialsProvider credentialsProvider,
        final String origin, boolean force) throws InvalidRemoteException {

    if (origin == null || origin.isEmpty()) {
        fetchRepository(git, credentialsProvider);
    } else {//  w  w  w . jav a  2s .c o m
        try {
            final StoredConfig config = git.getRepository().getConfig();
            config.setString("remote", "upstream", "url", origin);
            config.save();
        } catch (final Exception ex) {
            throw new RuntimeException(ex);
        }

        final List<RefSpec> specs = new ArrayList<RefSpec>();
        specs.add(new RefSpec("+refs/heads/*:refs/remotes/upstream/*"));
        specs.add(new RefSpec("+refs/tags/*:refs/tags/*"));
        specs.add(new RefSpec("+refs/notes/*:refs/notes/*"));

        try {
            git.fetch().setCredentialsProvider(credentialsProvider).setRefSpecs(specs).setRemote(origin).call();

            git.branchCreate().setName("master")
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM)
                    .setStartPoint("upstream/master").setForce(true).call();

        } catch (final InvalidRemoteException e) {
            throw e;
        } catch (final Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

From source file:org.kie.commons.java.nio.fs.jgit.util.JGitUtil.java

License:Apache License

public static void createBranch(final Git git, final String source, final String target) {
    try {//from www.j a  v a2s  . c om
        git.branchCreate().setName(target).setStartPoint(source).call();
    } catch (GitAPIException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.mule.module.git.GitConnector.java

License:Open Source License

/**
 * Create a local branch//from  w w w .  j  av  a  2 s .  com
 *
 * {@sample.xml ../../../doc/mule-module-git.xml.sample git:create-branch}
 *
 * @param branchName       Name of the new branch
 * @param force      If true and the branch with the given name already exists, the start-point of an existing branch will be set to a new start-point; if false, the existing branch will not be changed.
 * @param startPoint The new branch head will point to this commit. It may be given as a branch name, a commit-id, or a tag. If this option is omitted, the current HEAD will be used instead.
 * @param overrideDirectory Name of the directory to use for git repository
 */
@Processor
public void createBranch(String branchName, @Optional @Default("false") boolean force,
        @Optional @Default("HEAD") String startPoint, @Optional String overrideDirectory) {
    try {
        Git git = new Git(getGitRepo(overrideDirectory));
        CreateBranchCommand createBranch = git.branchCreate();
        createBranch.setName(branchName);
        createBranch.setForce(force);
        createBranch.setStartPoint(startPoint);
        createBranch.call();
    } catch (Exception e) {
        throw new RuntimeException("Unable to create branch " + branchName, e);
    }
}

From source file:org.wso2.carbon.appfactory.repository.mgt.git.JGitAgent.java

License:Apache License

/**
 * Create branch//  ww  w  . j  a  v  a  2 s .c o  m
 *
 * @param remoteRepoUrl remote repository url
 * @param newBranchName new branch name
 * @param branchFrom    name of the branch that going to branch from
 * @param repoFile      repository directory where {@code branchFrom} exists. If not exists will get cloned using
 *                      {@code remoteRepoUrl}
 * @return success
 * @throws RepositoryMgtException if error while branching
 */
public boolean branch(String remoteRepoUrl, String newBranchName, String branchFrom, File repoFile)
        throws RepositoryMgtException {
    try {
        Git gitRepo = getGitRepository(remoteRepoUrl, repoFile);
        gitRepo.branchCreate().setName(newBranchName).setStartPoint(branchFrom).call();
        return true;
    } catch (RepositoryMgtException e) {
        String msg = "Error while creating branch : " + newBranchName + " due to " + e.getMessage()
                + " from RepositoryMgtException";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    } catch (GitAPIException e) {
        String msg = "Error while creating branch : " + newBranchName + " due to " + e.getMessage()
                + " from GitAPIException";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    }
}

From source file:org.zanata.sync.plugin.git.service.impl.GitSyncService.java

License:Open Source License

private void checkOutBranch(File destPath, String branch) {
    try {/*  ww  w .j a  v  a2  s  . c om*/
        Git git = Git.open(destPath);
        List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
        /* refs will have name like these:
        refs/heads/master
        refs/remotes/origin/master
        refs/remotes/origin/zanata
        */
        Optional<Ref> localBranchRef = Optional.empty();
        Optional<Ref> remoteBranchRef = Optional.empty();
        for (Ref ref : refs) {
            String refName = ref.getName();
            if (refName.equals("refs/heads/" + branch)) {
                localBranchRef = Optional.of(ref);
            }
            if (refName.equals("refs/remotes/origin/" + branch)) {
                remoteBranchRef = Optional.of(ref);
            }
        }

        if (branch.equals("master")) {
            log.debug("merging origin/master");
            git.checkout().setName("master").call();
            git.merge().setFastForward(MergeCommand.FastForwardMode.FF_ONLY).include(remoteBranchRef.get())
                    .call();
            return;
        }

        /**
         * If branch found in local and is not master, delete it, create new local branch from remote.
         * If branch does not exists in remote, create new local branch based on master branch.
         */
        Ref ref;
        if (localBranchRef.isPresent()) {
            git.checkout().setName("master").setForce(true).call();
            git.branchDelete().setBranchNames(branch).call();
        }

        if (remoteBranchRef.isPresent()) {
            ref = git.branchCreate().setForce(true).setName(branch).setStartPoint("origin/" + branch)
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM).call();
        } else {
            ref = git.branchCreate().setForce(true).setName(branch).setStartPoint("origin/master")
                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM).call();
        }
        log.debug("checked out {}", ref);
        git.checkout().setName(branch).call();
        if (log.isDebugEnabled()) {
            log.debug("current branch is: {}", git.getRepository().getBranch());
        }
    } catch (IOException | GitAPIException e) {
        throw new RepoSyncException(e);
    }
}