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

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

Introduction

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

Prototype

public ListBranchCommand branchList() 

Source Link

Document

Return a command object used to list branches

Usage

From source file:com.tasktop.c2c.server.scm.service.GitServiceBean.java

License:Open Source License

/**
 * @param repo/*  ww  w .j  a  va  2  s . c o  m*/
 * @param git
 */
private void setBranchesAndTags(ScmRepository repo, Git git) {
    repo.setBranches(new ArrayList<String>());
    try {
        for (Ref ref : git.branchList().call()) {
            String refName = ref.getName();
            if (refName.startsWith(Constants.R_HEADS)) {
                refName = refName.substring(Constants.R_HEADS.length());
            }
            repo.getBranches().add(refName);
        }
    } catch (GitAPIException e) {
        throw new JGitInternalException(e.getMessage(), e);
    }

    RevWalk revWalk = new RevWalk(git.getRepository());
    Map<String, Ref> refList;
    repo.setTags(new ArrayList<String>());
    try {
        refList = git.getRepository().getRefDatabase().getRefs(Constants.R_TAGS);
        for (Ref ref : refList.values()) {
            repo.getTags().add(ref.getName().substring(Constants.R_TAGS.length()));
        }
    } catch (IOException e) {
        throw new JGitInternalException(e.getMessage(), e);
    } finally {
        revWalk.release();
    }
    Collections.sort(repo.getTags());

}

From source file:de.sjka.jenkins.view.branches.BranchOverviewAction.java

License:Open Source License

@SuppressWarnings("rawtypes")
public List<BranchState> getBranches() {
    // read remote branches from the repository
    Map<String, String> branches = new HashMap<String, String>();
    Map<String, String> messages = new HashMap<String, String>();
    try {//from www.j av a  2s  . c  om
        if (target.getScm() instanceof GitSCM) {
            GitSCM gitSCM = (GitSCM) target.getScm();
            String location = target.getLastBuild().getWorkspace().getRemote() + gitSCM.getRelativeTargetDir();
            Git git = Git.open(new File(location));
            for (Ref ref : git.branchList().setListMode(ListMode.REMOTE).call()) {
                String name = ref.getName();
                if (name.endsWith("/HEAD")) {
                    continue;
                }
                if (name.startsWith("refs/remotes/")) {
                    name = name.replace("refs/remotes/", "");
                }
                branches.put(name, ref.getObjectId().getName());
                System.out.println(name);
                messages.put(name, git.log().add(ref.getObjectId()).call().iterator().next().getShortMessage());
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GitAPIException e) {
        throw new RuntimeException(e);
    }

    // read commits from the build history
    Map<String, AbstractBuild> builds = new HashMap<String, AbstractBuild>();
    for (AbstractBuild build : target.getBuilds()) {
        for (Entry<String, Build> entry : ((Actionable) build).getAction(BuildData.class)
                .getBuildsByBranchName().entrySet()) {
            String sha1 = entry.getValue().getRevision().getSha1String();
            int number = entry.getValue().getBuildNumber();
            if (number == build.getNumber() && builds.get(sha1) == null) {
                builds.put(sha1, build);
                break;
            }
        }
    }

    // create model
    Map<String, BranchState> ret = new HashMap<String, BranchState>();
    for (Entry<String, String> branch : branches.entrySet()) {
        AbstractBuild build = builds.get(branch.getValue());
        BranchState state = new BranchState(branch.getKey(), branch.getValue(), messages.get(branch.getKey()),
                build);
        ret.put(branch.getKey(), state);
    }

    return new ArrayList<BranchState>(ret.values());
}

From source file:es.logongas.openshift.ant.impl.OpenShiftUtil.java

License:Apache License

private boolean existsBranch(String repositoryPath, String branchName) {
    try {//from   w w  w  . jav a2 s . com
        Git git = Git.open(new File(repositoryPath));

        ListBranchCommand listBranchCommand = git.branchList();
        listBranchCommand.setListMode(ListBranchCommand.ListMode.ALL);
        List<Ref> refs = listBranchCommand.call();
        for (Ref ref : refs) {
            if (ref.getName().equals(branchName)) {
                return true;
            }
        }

        return false;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } catch (GitAPIException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:io.fabric8.collector.git.GitBuildConfigProcessor.java

License:Apache License

protected ObjectId getBranchObjectId(Git git, String branch) {
    Ref branchRef = null;//from   www  . j  a v  a2s .co m
    try {
        String branchRevName = "refs/heads/" + branch;
        List<Ref> branches = git.branchList().call();
        for (Ref ref : branches) {
            String revName = ref.getName();
            if (Objects.equals(branchRevName, revName)) {
                branchRef = ref;
                break;
            }
        }
    } catch (GitAPIException e) {
        LOG.warn("Failed to find branches " + e, e);
    }

    ObjectId branchObjectId = null;
    if (branchRef != null) {
        branchObjectId = branchRef.getObjectId();
    }
    return branchObjectId;
}

From source file:io.fabric8.forge.rest.git.RepositoryResource.java

License:Apache License

protected List<String> doListBranches(Git git) throws Exception {
    SortedSet<String> names = new TreeSet<String>();
    List<Ref> call = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
    for (Ref ref : call) {
        String name = ref.getName();
        int idx = name.lastIndexOf('/');
        if (idx >= 0) {
            name = name.substring(idx + 1);
        }//  w ww  .  j  av a  2s.  co  m
        if (name.length() > 0) {
            names.add(name);
        }
    }
    return new ArrayList<String>(names);
}

From source file:io.fabric8.forge.rest.git.RepositoryResource.java

License:Apache License

protected ObjectId getBranchObjectId(Git git) {
    Ref branchRef = null;//w ww. j  av a  2  s  .c  om
    try {
        String branchRevName = "refs/heads/" + branch;
        List<Ref> branches = git.branchList().call();
        for (Ref ref : branches) {
            String revName = ref.getName();
            if (Objects.equals(branchRevName, revName)) {
                branchRef = ref;
                break;
            }
        }
    } catch (GitAPIException e) {
        LOG.warn("Failed to find branches " + e, e);
    }

    ObjectId branchObjectId = null;
    if (branchRef != null) {
        branchObjectId = branchRef.getObjectId();
    }
    return branchObjectId;
}

From source file:io.fabric8.forge.rest.git.RepositoryResource.java

License:Apache License

protected boolean localBranchExists(Git git, String branch) throws GitAPIException {
    List<Ref> list = git.branchList().call();
    String fullName = "refs/heads/" + branch;
    boolean localBranchExists = false;
    for (Ref ref : list) {
        String name = ref.getName();
        if (Objects.equals(name, fullName)) {
            localBranchExists = true;/*  w  ww. ja  va2s .  c o  m*/
        }
    }
    return localBranchExists;
}

From source file:io.fabric8.git.internal.GitDataStore.java

License:Apache License

/**
 * Performs a pull so the git repo is pretty much up to date before we start performing operations on it.
 *
 * @param git                 The {@link Git} instance to use.
 * @param credentialsProvider The {@link CredentialsProvider} to use.
 * @param doDeleteBranches    Flag that determines if local branches that don't exist in remote should get deleted.
 *///from ww  w.  j a v  a 2 s. co  m
protected void doPull(Git git, CredentialsProvider credentialsProvider, boolean doDeleteBranches) {
    assertValid();
    try {
        Repository repository = git.getRepository();
        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remoteRef.get(), "url");
        if (Strings.isNullOrBlank(url)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No remote repository defined for the git repository at "
                        + GitHelpers.getRootGitDirectory(git) + " so not doing a pull");
            }
            return;
        }
        /*
        String branch = repository.getBranch();
        String mergeUrl = config.getString("branch", branch, "merge");
        if (Strings.isNullOrBlank(mergeUrl)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No merge spec for branch." + branch + ".merge in the git repository at "
                    + GitHelpers.getRootGitDirectory(git) + " so not doing a pull");
        }
        return;
        }
        */
        if (LOG.isDebugEnabled()) {
            LOG.debug("Performing a fetch in git repository " + GitHelpers.getRootGitDirectory(git)
                    + " on remote URL: " + url);
        }

        boolean hasChanged = false;
        try {
            FetchResult result = git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider)
                    .setRemote(remoteRef.get()).call();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Git fetch result: {}", result.getMessages());
            }
            lastFetchWarning = null;
        } catch (Exception ex) {
            String fetchWarning = ex.getMessage();
            if (!fetchWarning.equals(lastFetchWarning)) {
                LOG.warn("Fetch failed because of: " + fetchWarning);
                LOG.debug("Fetch failed - the error will be ignored", ex);
                lastFetchWarning = fetchWarning;
            }
            return;
        }

        // Get local and remote branches
        Map<String, Ref> localBranches = new HashMap<String, Ref>();
        Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
        Set<String> gitVersions = new HashSet<String>();
        for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
            if (ref.getName().startsWith("refs/remotes/" + remoteRef.get() + "/")) {
                String name = ref.getName().substring(("refs/remotes/" + remoteRef.get() + "/").length());
                remoteBranches.put(name, ref);
                gitVersions.add(name);
            } else if (ref.getName().startsWith("refs/heads/")) {
                String name = ref.getName().substring(("refs/heads/").length());
                localBranches.put(name, ref);
                gitVersions.add(name);
            }
        }

        // Check git commits
        for (String version : gitVersions) {
            // Delete unneeded local branches.
            //Check if any remote branches was found as a guard for unwanted deletions.
            if (remoteBranches.isEmpty()) {
                //Do nothing
            } else if (!remoteBranches.containsKey(version)) {
                //We never want to delete the master branch.
                if (doDeleteBranches && !version.equals(MASTER_BRANCH)) {
                    try {
                        git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true)
                                .call();
                    } catch (CannotDeleteCurrentBranchException ex) {
                        git.checkout().setName(MASTER_BRANCH).setForce(true).call();
                        git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true)
                                .call();
                    }
                    removeVersion(version);
                    hasChanged = true;
                }
            }
            // Create new local branches
            else if (!localBranches.containsKey(version)) {
                addVersion(version);
                git.checkout().setCreateBranch(true).setName(version)
                        .setStartPoint(remoteRef.get() + "/" + version)
                        .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setForce(true).call();
                hasChanged = true;
            } else {
                String localCommit = localBranches.get(version).getObjectId().getName();
                String remoteCommit = remoteBranches.get(version).getObjectId().getName();
                if (!localCommit.equals(remoteCommit)) {
                    git.clean().setCleanDirectories(true).call();
                    git.checkout().setName("HEAD").setForce(true).call();
                    git.checkout().setName(version).setForce(true).call();
                    MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS)
                            .include(remoteBranches.get(version).getObjectId()).call();
                    if (result.getMergeStatus() != MergeResult.MergeStatus.ALREADY_UP_TO_DATE
                            && hasChanged(git, localCommit, remoteCommit)) {
                        hasChanged = true;
                    }
                    // TODO: handle conflicts
                }
            }
        }
        if (hasChanged) {
            LOG.debug("Changed after pull!");
            if (credentialsProvider != null) {
                // TODO lets test if the profiles directory is present after checking out version 1.0?
                getProfilesDirectory(git);
            }
            fireChangeNotifications();
        }
    } catch (Throwable ex) {
        LOG.debug("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git), ex);
        LOG.warn("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git) + " due "
                + ex.getMessage() + ". This exception is ignored.");
    }
}

From source file:io.fabric8.git.internal.GitHelpers.java

License:Apache License

public static boolean localBranchExists(Git git, String branch) throws GitAPIException {
    List<Ref> list = git.branchList().call();
    String fullName = "refs/heads/" + branch;
    boolean localBranchExists = false;
    for (Ref ref : list) {
        String name = ref.getName();
        if (equals(name, fullName)) {
            localBranchExists = true;/*w ww.j ava  2  s .  c  o m*/
            break;
        }
    }
    return localBranchExists;
}

From source file:io.fabric8.git.zkbridge.Bridge.java

License:Apache License

private void updateLocal(Git git, CuratorFramework zookeeper, CredentialsProvider credentialsProvider)
        throws Exception {
    String remoteName = "origin";

    try {/* w  w  w .  j  a  v  a2  s .  co m*/
        git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remoteName).call();
    } catch (Exception e) {
        // Ignore fetch exceptions
        return;
    }

    // Get local and remote branches
    Map<String, Ref> localBranches = new HashMap<String, Ref>();
    Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
    Set<String> gitVersions = new HashSet<String>();
    for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
        if (ref.getName().startsWith("refs/remotes/" + remoteName + "/")) {
            String name = ref.getName().substring(("refs/remotes/" + remoteName + "/").length());
            if (!"master".equals(name) && !name.endsWith("-tmp")) {
                remoteBranches.put(name, ref);
                gitVersions.add(name);
            }
        } else if (ref.getName().startsWith("refs/heads/")) {
            String name = ref.getName().substring(("refs/heads/").length());
            if (!name.equals("master") && !name.endsWith("-tmp")) {
                localBranches.put(name, ref);
                gitVersions.add(name);
            }
        }
    }

    // Check git commmits
    for (String version : gitVersions) {
        // Delete unneeded local branches
        if (!remoteBranches.containsKey(version)) {
            git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true).call();
        }
        // Create new local branches
        else if (!localBranches.containsKey(version)) {
            git.branchCreate().setName(version).call();
            git.reset().setMode(ResetCommand.ResetType.HARD).setRef(remoteBranches.get(version).getName())
                    .call();
        } else {
            String localCommit = localBranches.get(version).getObjectId().getName();
            String remoteCommit = remoteBranches.get(version).getObjectId().getName();
            if (!localCommit.equals(remoteCommit)) {
                git.clean().setCleanDirectories(true).call();
                git.checkout().setName("HEAD").setForce(true).call();
                git.checkout().setName(version).setForce(true).call();
                MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS)
                        .include(remoteBranches.get(version).getObjectId()).call();
                // TODO: handle conflicts
            }
        }
    }
}