Example usage for org.eclipse.jgit.api ListBranchCommand call

List of usage examples for org.eclipse.jgit.api ListBranchCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api ListBranchCommand call.

Prototype

@Override
public List<Ref> call() throws GitAPIException 

Source Link

Usage

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. co  m*/
        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:net.morimekta.gittool.cmd.Branch.java

License:Apache License

private BranchInfo refreshBranchList(String selected) throws IOException, GitAPIException {
    branches.clear();/*from  w  w w.j  a  v a 2 s.co m*/

    ListBranchCommand bl = git.branchList();
    List<Ref> refs = bl.call();

    String current = repository.getFullBranch();
    BranchInfo selectedInfo = null;

    prompt = "Manage branches from <untracked>:";
    for (Ref ref : refs) {
        BranchInfo info = new BranchInfo();
        info.ref = ref;

        info.name = branchName(ref);
        if (ref.getName().equals(current)) {
            info.current = true;
            info.uncommitted = hasUncommitted();
            currentInfo = info;
        }
        if (selected == null) {
            if (ref.getName().equals(current)) {
                selectedInfo = info;
            }
        } else {
            if (info.name.equals(selected)) {
                selectedInfo = info;
            }
        }

        info.diffbase = gt.getDiffbase(info.name);
        info.remote = gt.getRemote(info.name);

        Ref currentRef = repository.getRef(gt.refName(info.name));
        Ref diffWithRef = repository.getRef(gt.refName(info.diffbase));

        ObjectId currentHead = currentRef.getObjectId();
        ObjectId diffWithHead = diffWithRef.getObjectId();

        List<RevCommit> localCommits = ImmutableList
                .copyOf(git.log().addRange(diffWithHead, currentHead).call());
        List<RevCommit> remoteCommits = ImmutableList
                .copyOf(git.log().addRange(currentHead, diffWithHead).call());

        info.commits = localCommits.size();
        info.missing = remoteCommits.size();

        longestBranchName = Math.max(longestBranchName, CharUtil.printableWidth(info.name));
        longestRemoteName = Math.max(longestRemoteName, CharUtil.printableWidth(info.diffbase));

        branches.add(info);
    }

    Comparator<BranchInfo> comparator = (l, r) -> {
        if (l.name.equals(gt.getDefaultBranch())) {
            return -1;
        }
        if (r.name.equals(gt.getDefaultBranch())) {
            return 1;
        }
        return l.name.compareTo(r.name);
    };
    branches.sort(comparator);
    return selectedInfo == null ? currentInfo : selectedInfo;
}

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

License:Apache License

/**
 * Execute command to list branches.//from w w  w .  ja v a2  s  . com
 */
@TaskAction
void branchList() {
    ListBranchCommand cmd = getGit().branchList();
    if (getBranchType() != null) {
        switch (getBranchType()) {
        case REMOTE:
            cmd.setListMode(ListBranchCommand.ListMode.REMOTE);
            break;
        case ALL:
            cmd.setListMode(ListBranchCommand.ListMode.ALL);
            break;
        case LOCAL:
            break; //use default
        default:
            throw new AssertionError("Illegal branch type: " + getBranchType());
        }
    }
    try {
        Repository repo = getGit().getRepository();
        branches = new ArrayList<Branch>();
        for (Ref ref : cmd.call()) {
            branches.add(GitUtil.refToBranch(repo, ref));
        }
        workingBranch = GitUtil.gitNameToBranch(repo, repo.getFullBranch());
    } catch (IOException e) {
        throw new GradleException("Problem listing branches", e);
    } catch (GitAPIException e) {
        throw new GradleException("Problem listing branches", e);
    }
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public List<Branch> branchList(BranchListRequest request) throws GitException {
    String listMode = request.getListMode();
    if (listMode != null && !BranchListRequest.LIST_ALL.equals(listMode)
            && !BranchListRequest.LIST_REMOTE.equals(listMode)) {
        throw new IllegalArgumentException(String.format(ERROR_UNSUPPORTED_LIST_MODE, listMode));
    }/*www. j  a v  a2s  .c om*/

    ListBranchCommand listBranchCommand = getGit().branchList();
    if (BranchListRequest.LIST_ALL.equals(listMode)) {
        listBranchCommand.setListMode(ListMode.ALL);
    } else if (BranchListRequest.LIST_REMOTE.equals(listMode)) {
        listBranchCommand.setListMode(ListMode.REMOTE);
    }
    List<Ref> refs;
    String currentRef;
    try {
        refs = listBranchCommand.call();
        String headBranch = getRepository().getBranch();
        Optional<Ref> currentTag = getGit().tagList().call().stream()
                .filter(tag -> tag.getObjectId().getName().equals(headBranch)).findFirst();
        if (currentTag.isPresent()) {
            currentRef = currentTag.get().getName();
        } else {
            currentRef = "refs/heads/" + headBranch;
        }

    } catch (GitAPIException | IOException exception) {
        throw new GitException(exception.getMessage(), exception);
    }
    List<Branch> branches = new ArrayList<>();
    for (Ref ref : refs) {
        String refName = ref.getName();
        boolean isCommitOrTag = Constants.HEAD.equals(refName);
        String branchName = isCommitOrTag ? currentRef : refName;
        String branchDisplayName;
        if (isCommitOrTag) {
            branchDisplayName = "(detached from " + Repository.shortenRefName(currentRef) + ")";
        } else {
            branchDisplayName = Repository.shortenRefName(refName);
        }
        Branch branch = newDto(Branch.class).withName(branchName)
                .withActive(isCommitOrTag || refName.equals(currentRef)).withDisplayName(branchDisplayName)
                .withRemote(refName.startsWith("refs/remotes"));
        branches.add(branch);
    }
    return branches;
}

From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java

License:Open Source License

private String getCheckoutBranch(Git git) throws IOException, GitAPIException {
    ListBranchCommand branchList = git.branchList();
    branchList.setListMode(ListMode.REMOTE);
    List<Ref> branches = branchList.call();

    String formatVersion = FORMAT_VERSION.substring(FORMAT_PREFIX.length());
    int version = Integer.parseInt(formatVersion);

    return getCheckoutBranch(branches, version);
}

From source file:org.enterprisedomain.classmaker.impl.ContributionImpl.java

License:Apache License

/**
 * <!-- begin-user-doc --> <!-- end-user-doc -->
 * /* w  w  w. j av a2  s .c  o  m*/
 * @generated NOT
 */
public String initialize(boolean commit) {
    @SuppressWarnings("unchecked")
    SCMOperator<Git> operator = (SCMOperator<Git>) getWorkspace().getSCMRegistry().get(getProjectName());
    setName(getProjectName());
    try {
        Git git = operator.getRepositorySCM();
        // if (git == null)
        // return "";
        String currentBranch = git.getRepository().getBranch();

        ListBranchCommand listBranches = git.branchList();
        List<Ref> branches = listBranches.call();
        Iterator<Ref> it = branches.iterator();
        Ref branch = null;
        long timestamp = -1;
        String commitId = "";
        do {
            Version version = null;
            if (it.hasNext()) {
                branch = it.next();
                String[] name = branch.getName().split("/"); //$NON-NLS-1$
                try {
                    version = operator.decodeVersion(name[name.length - 1]);
                    ReflogCommand reflog = git.reflog();
                    reflog.setRef(branch.getName().toString());
                    Collection<ReflogEntry> refs = reflog.call();
                    for (ReflogEntry ref : refs)
                        if (ref.getNewId().equals(branch.getObjectId())) {
                            timestamp = operator.decodeTimestamp(ref.getComment());
                            if (timestamp == -1)
                                timestamp = operator.decodeTimestamp(version.getQualifier());
                        }
                } catch (IllegalArgumentException e) {
                    continue;
                }
            }
            if (version != null && !getRevisions().containsKey(version)) {
                Revision newRevision = newBareRevision(version);
                newRevision.setTimestamp(timestamp);
                newRevision.setProject(this);
                doNewRevision(newRevision);
                commitId = newRevision.initialize(commit);
            }
        } while (it.hasNext());
        if (!getRevisions().isEmpty() && getVersion().equals(Version.emptyVersion))
            setVersion(ListUtil.getLast(getRevisions()).getKey());
        else if (!getVersion().equals(Version.emptyVersion))
            checkout(getVersion(), timestamp);
        if (currentBranch.equals(SCMOperator.MASTER_BRANCH))
            checkout(getVersion(), timestamp);
        getWorkspace().getResourceSet().eAdapters().add(resourceAdapter);
        addResourceChangeListener(getResourceReloadListener());
        return commitId;
    } catch (Exception e) {
        ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(e));
        return null;
    } finally {
        try {
            operator.ungetRepositorySCM();
        } catch (Exception e) {
            ClassMakerPlugin.getInstance().getLog().log(ClassMakerPlugin.createErrorStatus(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).
 * /* w  ww .j  a v a2s.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 w w . j a v  a 2 s  .  c  om*/
 * @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.fedoraproject.eclipse.packager.tests.FedoraPackagerGitCloneOperationTest.java

License:Open Source License

/**
 * Fedora Git clones create local branches. Test for that.
 * /*ww w .  j a  v a2  s  .  co m*/
 * @throws Exception
 */
@Test
public void canCloneFromFedoraGit() {
    final FedoraPackagerGitCloneOperation cloneOp = new FedoraPackagerGitCloneOperation();
    final String fedoraPackager = "eclipse-fedorapackager";
    Job cloneJob = new Job("Clone Me!") {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            try {
                git = cloneOp.setPackageName(fedoraPackager)
                        .setCloneURI(GitUtils.getFullGitURL(GitUtils.getAnonymousGitBaseUrl(), fedoraPackager))
                        .run(monitor);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (CoreException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            return null;
        }
    };
    cloneJob.schedule();
    try {
        cloneJob.join(); // wait for it to finish
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    assertNotNull(git);
    ListBranchCommand ls = git.branchList();
    // should have created a local branch called "f14"
    boolean f14Found = false;
    for (Ref ref : ls.call()) {
        if (Repository.shortenRefName(ref.getName()).equals("f14")) {
            f14Found = true;
            break;
        }
    }
    assertTrue(f14Found);
}

From source file:org.fedoraproject.eclipse.packager.tests.utils.git.GitTestProject.java

License:Open Source License

/**
 * Checkouts branch/* www. j  a  v a  2s  .  c o  m*/
 *
 * @param refName
 *            full name of branch
 * @throws CoreException
 * @throws InvalidRefNameException 
 * @throws RefNotFoundException 
 * @throws RefAlreadyExistsException 
 * @throws JGitInternalException 
 */
public void checkoutBranch(String branchName) throws JGitInternalException, RefAlreadyExistsException,
        RefNotFoundException, InvalidRefNameException, CoreException {
    boolean branchExists = false;
    ListBranchCommand lsBranchCmd = this.git.branchList();
    for (Ref branch : lsBranchCmd.call()) {
        if (Repository.shortenRefName(branch.getName()).equals(branchName)) {
            branchExists = true;
            break; // short circuit
        }
    }
    if (!branchExists) {
        System.err.println("Branch: '" + branchName + "' does not exist!");
        return;
    }
    CheckoutCommand checkoutCmd = this.git.checkout();
    checkoutCmd.setName(Constants.R_HEADS + branchName);
    checkoutCmd.call();
    // refresh after checkout
    project.refreshLocal(IResource.DEPTH_INFINITE, null);
}