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:org.flowerplatform.web.git.explorer.Ref_VirtualItemChildrenProvider.java

License:Open Source License

@Override
public Collection<Pair<Object, String>> getChildrenForNode(Object node, TreeNode treeNode,
        GenericTreeContext context) {//from   w w  w  . j  a  v a 2  s  .c om
    @SuppressWarnings("unchecked")
    Repository repository = ((Pair<Repository, String>) node).a;
    String nodeType = treeNode.getPathFragment().getType();

    Collection<Pair<Object, String>> result = new ArrayList<Pair<Object, String>>();
    try {
        Git git = new Git(repository);

        String childType = null;
        List<Ref> refs = new ArrayList<>();

        if (GitNodeType.NODE_TYPE_LOCAL_BRANCHES.equals(nodeType)) {
            refs = git.branchList().call();
            childType = GitNodeType.NODE_TYPE_LOCAL_BRANCH;
        } else if (GitNodeType.NODE_TYPE_REMOTE_BRANCHES.equals(nodeType)) {
            refs = git.branchList().setListMode(ListMode.REMOTE).call();
            childType = GitNodeType.NODE_TYPE_REMOTE_BRANCH;
        } else if (GitNodeType.NODE_TYPE_TAGS.equals(nodeType)) {
            refs = git.tagList().call();
            childType = GitNodeType.NODE_TYPE_TAG;
        }

        Pair<Object, String> child;

        for (Ref ref : refs) {
            child = new Pair<Object, String>(new RefNode(repository, ref), childType);
            result.add(child);
        }
    } catch (Exception e) {
        // TODO CC: log
        e.printStackTrace();
    }
    return result;
}

From source file:org.flowerplatform.web.git.explorer.Ref_VirtualItemChildrenProvider.java

License:Open Source License

@Override
public Boolean nodeHasChildren(Object node, TreeNode treeNode, GenericTreeContext context) {
    @SuppressWarnings("unchecked")
    Repository repository = ((Pair<Repository, String>) node).a;
    String nodeType = treeNode.getPathFragment().getType();

    try {/*www  .ja  v  a2s . c  om*/
        Git git = new Git(repository);
        if (GitNodeType.NODE_TYPE_LOCAL_BRANCHES.equals(nodeType)) {
            return git.branchList().call().size() > 0;
        } else if (GitNodeType.NODE_TYPE_REMOTE_BRANCHES.equals(nodeType)) {
            return true;
        } else if (GitNodeType.NODE_TYPE_TAGS.equals(nodeType)) {
            return git.tagList().call().size() > 0;
        }
    } catch (GitAPIException e) {
        // TODO CC: log
    }
    return false;
}

From source file:org.fusesource.fabric.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
 *///  w  w w .j  a  v a 2  s. c o m
protected void doPull(Git git, CredentialsProvider credentialsProvider) {
    assertValid();
    try {
        Repository repository = git.getRepository();
        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remote, "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 {
            git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remote).call();
        } catch (Exception e) {
            LOG.debug("Fetch failed. Ignoring");
            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/" + remote + "/")) {
                String name = ref.getName().substring(("refs/remotes/" + remote + "/").length());
                if (!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.endsWith("-tmp")) {
                    localBranches.put(name, ref);
                    gitVersions.add(name);
                }
            }
        }

        // Check git commmits
        for (String version : gitVersions) {
            // Delete unneeded local branches.
            //Check if any remote branches was found as a guard for unwanted deletions.
            if (!remoteBranches.containsKey(version) && !remoteBranches.isEmpty()) {
                //We never want to delete the master branch.
                if (!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();
                    }
                    hasChanged = true;
                }
            }
            // Create new local branches
            else if (!localBranches.containsKey(version)) {
                git.checkout().setCreateBranch(true).setName(version).setStartPoint(remote + "/" + 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 = 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?
                File profilesDirectory = getProfilesDirectory(git);
            }
            fireChangeNotifications();
        }
    } catch (Throwable e) {
        LOG.error("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git)
                + ". Reason: " + e, e);
    }
}

From source file:org.fusesource.fabric.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;/*from   w w w .  ja  va2  s  .c  o  m*/
        }
    }
    return localBranchExists;
}

From source file:org.impressivecode.depress.scm.git.GitOnlineLogParser.java

License:Open Source License

public static List<String> getBranches(final String path) throws IOException, GitAPIException {
    Git git = initializeGit(path);

    List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
    List<String> branches = new ArrayList<String>();
    for (Ref r : refs) {
        branches.add(r.getName().replace("refs/heads/", "").replace("refs/remotes/", ""));
    }//w ww. j  a  v a2 s .  c om

    return branches;
}

From source file:org.impressivecode.depress.scm.git.GitOnlineLogParser.java

License:Open Source License

private List<GitCommit> processRepo(final String path, final GitParserOptions gitParserOptions)
        throws IOException, NoHeadException, GitAPIException {
    Git git = initializeGit(path);
    List<GitCommit> analyzedCommits = new ArrayList<GitCommit>();

    LogCommand log = git.log();/*from   www. j a  v a2  s. c  om*/

    if (gitParserOptions.hasBranch()) {
        List<Ref> branches = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
        Ref branch = null;
        for (Ref b : branches) {
            if (b.getName().equals("refs/heads/" + gitParserOptions.getBranch())
                    || b.getName().equals("refs/remotes/" + gitParserOptions.getBranch())) {
                branch = b;
                break;
            }
        }
        if (branch == null) {
            throw new IOException("Specified branch was not found in git repository");
        }
        log.add(branch.getObjectId());
    }

    Iterable<RevCommit> loglines = log.call();
    Iterator<RevCommit> logIterator = loglines.iterator();
    while (logIterator.hasNext()) {
        RevCommit commit = logIterator.next();
        GitcommitProcessor proc = new GitcommitProcessor(gitParserOptions, git.getRepository());
        proc.setRevCommit(commit);
        proc.processCommitData();
        analyzedCommits.add(proc.getResult());
    }
    return analyzedCommits;
}

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

License:Open Source License

@Override
public List<Ref> getLocalBranches(final Git repo) throws GitAPIException {
    // returns only local branches by default
    return repo.branchList().call();
}

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

License:Open Source License

public static List<Ref> getLocalBranches(final Git repo) throws GitAPIException {
    // returns only local branches by default
    return repo.branchList().call();
}

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

License:Apache License

public static List<Ref> branchList(final Git git, final ListBranchCommand.ListMode listMode) {
    checkNotNull("git", git);
    try {//from w w  w . ja  va2s .  co  m
        return git.branchList().setListMode(listMode).call();
    } catch (GitAPIException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.modeshape.connector.git.GitFunction.java

License:Apache License

/**
 * Add the names of the branches as children of the current node.
 * //from w  ww.j a  v  a 2 s  .  co  m
 * @param git the Git object; may not be null
 * @param spec the call specification; may not be null
 * @param writer the document writer for the current node; may not be null
 * @throws GitAPIException if there is a problem accessing the Git repository
 */
protected void addBranchesAsChildren(Git git, CallSpecification spec, DocumentWriter writer)
        throws GitAPIException {
    Set<String> remoteBranchPrefixes = remoteBranchPrefixes();
    if (remoteBranchPrefixes.isEmpty()) {
        // Generate the child references to the LOCAL branches, which will be sorted by name ...
        ListBranchCommand command = git.branchList();
        List<Ref> branches = command.call();
        // Reverse the sort of the branch names, since they might be version numbers ...
        Collections.sort(branches, REVERSE_REF_COMPARATOR);
        for (Ref ref : branches) {
            String name = ref.getName();
            writer.addChild(spec.childId(name), name);
        }
        return;
    }
    // There is at least one REMOTE branch, so generate the child references to the REMOTE branches,
    // which will be sorted by name (by the command)...
    ListBranchCommand command = git.branchList();
    command.setListMode(ListMode.REMOTE);
    List<Ref> branches = command.call();
    // Reverse the sort of the branch names, since they might be version numbers ...
    Collections.sort(branches, REVERSE_REF_COMPARATOR);
    Set<String> uniqueNames = new HashSet<String>();
    for (Ref ref : branches) {
        String name = ref.getName();
        if (uniqueNames.contains(name))
            continue;
        // We only want the branch if it matches one of the listed remotes ...
        boolean skip = false;
        for (String remoteBranchPrefix : remoteBranchPrefixes) {
            if (name.startsWith(remoteBranchPrefix)) {
                // Remove the prefix ...
                name = name.replaceFirst(remoteBranchPrefix, "");
                break;
            }
            // Otherwise, it's a remote branch from a different remote that we don't want ...
            skip = true;
        }
        if (skip)
            continue;
        if (uniqueNames.add(name))
            writer.addChild(spec.childId(name), name);
    }
}