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:io.fabric8.git.zkbridge.Bridge.java

License:Apache License

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

    boolean remoteAvailable = false;
    try {//from  w  w w  .jav a  2s  .  c o  m
        git.fetch().setCredentialsProvider(credentialsProvider).setRemote(remoteName).call();
        remoteAvailable = true;
    } catch (Exception e) {
        // Ignore fetch exceptions
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Unable to fetch master", e);
        } else if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Unable to fetch master: " + e.getClass().getName() + ": " + e.getMessage());
        }
    }

    // Handle versions in git and not in zookeeper
    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);
            }
        }
    }
    List<String> zkVersions = getChildren(zookeeper, ZkPath.CONFIG_VERSIONS.getPath());
    createDefault(zookeeper, "/fabric/configs/git", null);
    Properties versionsMetadata = loadProps(zookeeper, "/fabric/configs/git");

    boolean allDone = true;
    // Check no modifs in zookeeper
    String lastModified = Long.toString(lastModified(zookeeper, ZkPath.CONFIG_VERSIONS.getPath()));
    if (!lastModified.equals(versionsMetadata.get("zk-lastmodified"))) {
        allDone = false;
    }
    // Check the versions in zk and git are the same
    if (zkVersions.size() != gitVersions.size() || !zkVersions.containsAll(gitVersions)) {
        allDone = false;
    }
    // Check all local and remote branches exists
    if (gitVersions.size() != localBranches.size() || !localBranches.keySet().containsAll(gitVersions)) {
        allDone = false;
    }
    // If remote is available, check that all remote branches exist
    if (remoteAvailable && !remoteBranches.keySet().containsAll(gitVersions)) {
        allDone = false;
    }
    // Check git commmits
    if (allDone) {
        for (String version : zkVersions) {
            String zkCommit = versionsMetadata.get(version);
            String localCommit = localBranches.get(version).getObjectId().getName();
            String remoteCommit = remoteAvailable ? remoteBranches.get(version).getObjectId().getName() : null;
            if (!localCommit.equals(zkCommit) || remoteCommit != null && !localCommit.equals(remoteCommit)) {
                allDone = false;
                break;
            }
        }
    }
    if (allDone) {
        return;
    }

    // ZooKeeper -> Git changes
    for (String version : zkVersions) {
        String zkNode = ZkPath.CONFIG_VERSION.getPath(version);

        // Checkout updated version
        List<Ref> allBranches = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
        Ref local = null;
        Ref remote = null;
        Ref tmp = null;
        for (Ref ref : allBranches) {
            if (ref.getName().equals("refs/remotes/" + remoteName + "/" + version)) {
                remote = ref;
            } else if (ref.getName().equals("refs/heads/" + version)) {
                local = ref;
            } else if (ref.getName().equals("refs/heads/" + version + "-tmp")) {
                tmp = ref;
            }
        }
        if (local == null) {
            git.branchCreate().setName(version).call();
        }
        if (tmp == null) {
            git.branchCreate().setName(version + "-tmp").call();
        }
        git.clean().setCleanDirectories(true).call();
        git.checkout().setName("HEAD").setForce(true).call();
        git.checkout().setName(version).setForce(true).call();
        if (remoteAvailable && remote != null) {
            MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS).include(remote.getObjectId())
                    .call();
            // TODO: check merge conflicts
        }
        git.checkout().setName(version + "-tmp").setForce(true).call();
        String gitCommit = versionsMetadata.get(version);
        if (gitCommit != null) {
            try {
                git.reset().setMode(ResetCommand.ResetType.HARD).setRef(gitCommit).call();
            } catch (Exception e) {
                // Ignore, we did our best
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Unable to reset branch to commit", e);
                } else if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Unable to reset branch to commit " + gitCommit + ": " + e.getClass().getName()
                            + ": " + e.getMessage());
                }
            }
        }

        // Apply changes to git
        syncVersionFromZkToGit(git, zookeeper, zkNode);

        if (git.status().call().isClean()) {
            git.checkout().setName(version).setForce(true).call();
        } else {
            ObjectId rev = git.commit().setMessage("Merge zookeeper updates in version " + version).call()
                    .getId();
            git.checkout().setName(version).setForce(true).call();
            MergeResult result = git.merge().setStrategy(MergeStrategy.OURS).include(rev).call();
            // TODO: check merge conflicts
        }
        if (remoteAvailable) {
            git.push().setCredentialsProvider(credentialsProvider).setRefSpecs(new RefSpec(version)).call();
        }

        // Apply changes to zookeeper
        syncVersionFromGitToZk(git, zookeeper, zkNode);

        versionsMetadata.put(version, git.getRepository().getRef("HEAD").getObjectId().getName());
    }
    // Iterate through known git versions
    for (String version : gitVersions) {
        String state = versionsMetadata.get(version);
        if (zkVersions.contains(version)) {
            continue;
        }
        // The version is not known to zookeeper, so create it
        if (state == null) {
            if (localBranches.containsKey(version)) {
                if (remoteAvailable) {
                    git.push().setRefSpecs(new RefSpec(version)).call();
                }
            } else {
                git.branchCreate().setName(version).call();
                git.reset().setMode(ResetCommand.ResetType.HARD).setRef(remoteBranches.get(version).getName())
                        .call();
            }
            git.checkout().setName(version).setForce(true).call();
            // Sync zookeeper
            String zkNode = ZkPath.CONFIG_VERSION.getPath(version);
            create(zookeeper, zkNode);
            create(zookeeper, ZkPath.CONFIG_VERSIONS_PROFILES.getPath(version));
            create(zookeeper, ZkPath.CONFIG_VERSIONS_CONTAINERS.getPath(version));
            syncVersionFromGitToZk(git, zookeeper, zkNode);
            // Flag version as active
            versionsMetadata.put(version, git.getRepository().getRef("HEAD").getObjectId().getName());
        }
        // The version has been deleted from zookeeper so delete it in git
        else {
            git.checkout().setName("master").setForce(true).call();
            git.branchDelete().setBranchNames(version, version + "-tmp").setForce(true).call();
            git.push().setRefSpecs(new RefSpec(version + ":")).call();
            versionsMetadata.remove(version);
        }
    }
    versionsMetadata.put("zk-lastmodified",
            Long.toString(lastModified(zookeeper, ZkPath.CONFIG_VERSIONS.getPath())));
    setPropertiesAsMap(zookeeper, "/fabric/configs/git", versionsMetadata);
}

From source file:io.fabric8.itests.basic.git.GitUtils.java

License:Apache License

/**
 * Checks if a local branch exists./*  w  ww  .  ja  v  a2 s  .co m*/
 * @param git       The git object to use.
 * @param branch    The name of the local branch.
 * @return
 * @throws GitAPIException
 */
public static boolean localBranchExists(Git git, String branch) throws GitAPIException {
    List<Ref> list = git.branchList().call();
    String fullName = "refs/heads/" + branch;
    boolean exists = false;
    for (Ref ref : list) {
        String name = ref.getName();
        if (Objects.equal(name, fullName)) {
            exists = true;
        }
    }
    return exists;
}

From source file:io.fabric8.itests.basic.git.GitUtils.java

License:Apache License

/**
 * Checks if a remote branch exists./*from w  ww.  ja va2 s . c  o  m*/
 * @param git       The git object to use.
 * @param remote    The name of the remote repo to check.
 * @param branch    The name of the local branch.
 * @return
 * @throws GitAPIException
 */
public static boolean remoteBranchExists(Git git, String remote, String branch) throws GitAPIException {
    List<Ref> list = git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call();
    String fullName = "refs/remotes/" + remote + "/" + branch;
    boolean exists = false;
    for (Ref ref : list) {
        String name = ref.getName();
        if (Objects.equal(name, fullName)) {
            exists = true;
        }
    }
    return exists;
}

From source file:io.hawt.git.GitFacadeSupport.java

License:Apache License

protected List<String> doListBranches(Git git) throws GitAPIException {
    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);
        }//from w w w  .j a va 2  s  . c  o m
        if (name.length() > 0) {
            names.add(name);
        }
    }
    return new ArrayList<String>(names);
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

License:Apache License

private GitConfigStoreTest add(Git git, File root, File file, String directory)
        throws IOException, GitAPIException {
    if (!file.isFile()) {
        throw new RuntimeException("File not found " + file.getAbsolutePath());
    }/*from w  ww. j  a  v  a  2 s  . c  o  m*/

    if (!"master".equalsIgnoreCase(git.getRepository().getBranch())) {
        git.checkout().setCreateBranch(true).setName("master").call();
    }

    if (!branch.equalsIgnoreCase(git.getRepository().getBranch())) {
        boolean create = true;
        for (Ref ref : git.branchList().call()) {
            if (ref.getName().equals("refs/heads/" + branch)) {
                create = false;
            }
        }
        git.checkout().setCreateBranch(create).setName(branch).call();
    }

    String relative;
    if (directory != null) {
        relative = directory + File.separator + file.getName();
    } else {
        relative = file.getName();
    }

    File output = new File(root, relative);
    if (output.exists()) {
        output.delete();
    }
    if (!output.getParentFile().isDirectory()) {
        output.getParentFile().mkdirs();
    }

    FileUtils.copyFile(file, output);

    git.add().addFilepattern(relative).call();

    git.commit().setAuthor("clement", "clement@apache.org").setCommitter("clement", "clement@apache.org")
            .setMessage("Add " + relative).call();

    return this;
}

From source file:org.apache.maven.scm.provider.git.jgit.command.branch.JGitBranchCommand.java

License:Apache License

/**
 * gets a set of names of the available branches in the given repo
 * /*from  w  w w . ja va  2  s . c  o m*/
 * @param git the repo to list the branches for
 * @return set of short branch names
 * @throws GitAPIException
 */
public static Set<String> getShortLocalBranchNames(Git git) throws GitAPIException {
    Set<String> branches = new HashSet<String>();
    Iterator<Ref> iter = git.branchList().call().iterator();
    while (iter.hasNext()) {
        branches.add(Repository.shortenRefName(iter.next().getName()));
    }
    return branches;
}

From source file:org.eclipse.n4js.utils.git.GitUtils.java

License:Open Source License

private static boolean hasLocalBranch(Git git, final String branchName) throws GitAPIException {
    final Iterable<Ref> localBranchRefs = git.branchList().call();
    return from(localBranchRefs).anyMatch(ref -> ref.getName().endsWith(branchName));
}

From source file:org.eclipse.orion.server.git.jobs.ListBranchesJob.java

License:Open Source License

@Override
protected IStatus performJob() {
    try {//from w ww. ja  v  a  2s  .com
        File gitDir = GitUtils.getGitDir(path);
        Repository db = new FileRepository(gitDir);
        Git git = new Git(db);
        List<Ref> branchRefs = git.branchList().call();
        List<Branch> branches = new ArrayList<Branch>(branchRefs.size());
        for (Ref ref : branchRefs) {
            branches.add(new Branch(cloneLocation, db, ref));
        }
        Collections.sort(branches, Branch.COMPARATOR);
        JSONObject result = new JSONObject();
        JSONArray children = new JSONArray();
        int firstBranch = pageSize > 0 ? pageSize * (pageNo - 1) : 0;
        int lastBranch = pageSize > 0 ? firstBranch + pageSize - 1 : branches.size() - 1;
        lastBranch = lastBranch > branches.size() - 1 ? branches.size() - 1 : lastBranch;
        if (pageNo > 1 && baseLocation != null) {
            String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize;
            if (commitsSize > 0) {
                prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
            }
            result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev);
        }
        if (lastBranch < branches.size() - 1) {
            String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize;
            if (commitsSize > 0) {
                next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
            }
            result.put(ProtocolConstants.KEY_NEXT_LOCATION, next);
        }
        for (int i = firstBranch; i <= lastBranch; i++) {
            Branch branch = branches.get(i);
            if (commitsSize == 0) {
                children.put(branch.toJSON());
            } else {
                String branchName = branch.getName(true, false);
                ObjectId toObjectId = db.resolve(branchName);
                Ref toRefId = db.getRef(branchName);
                if (toObjectId == null) {
                    String msg = NLS.bind("No ref or commit found: {0}", branchName);
                    return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null);
                }
                toObjectId = getCommitObjectId(db, toObjectId);

                Log log = null;
                // single commit is requested and we already know it, no need for LogCommand 
                if (commitsSize == 1 && toObjectId instanceof RevCommit) {
                    log = new Log(cloneLocation, db, Collections.singleton((RevCommit) toObjectId), null, null,
                            toRefId);
                } else {
                    LogCommand lc = git.log();
                    // set the commit range
                    lc.add(toObjectId);
                    lc.setMaxCount(this.commitsSize);
                    Iterable<RevCommit> commits = lc.call();
                    log = new Log(cloneLocation, db, commits, null, null, toRefId);
                }
                log.setPaging(1, commitsSize);
                children.put(branch.toJSON(log.toJSON()));
            }
        }
        result.put(ProtocolConstants.KEY_CHILDREN, children);
        result.put(ProtocolConstants.KEY_TYPE, Branch.TYPE);
        return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
    } catch (Exception e) {
        String msg = NLS.bind("An error occured when listing branches for {0}", path);
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e);
    }
}

From source file:org.eclipse.orion.server.git.objects.Log.java

License:Open Source License

static Map<ObjectId, JSONArray> getCommitToBranchMap(URI cloneLocation, Repository db)
        throws GitAPIException, JSONException {
    HashMap<ObjectId, JSONArray> commitToBranch = new HashMap<ObjectId, JSONArray>();
    Git git = new Git(db);
    List<Ref> branchRefs = git.branchList().setListMode(ListMode.ALL).call();
    for (Ref branchRef : branchRefs) {
        ObjectId commitId = branchRef.getLeaf().getObjectId();
        JSONObject branch = new JSONObject();
        branch.put(ProtocolConstants.KEY_FULL_NAME, branchRef.getName());

        JSONArray branchesArray = commitToBranch.get(commitId);
        if (branchesArray != null) {
            branchesArray.put(branch);// www  .j a  v a  2  s. co m
        } else {
            branchesArray = new JSONArray();
            branchesArray.put(branch);
            commitToBranch.put(commitId, branchesArray);
        }
    }
    return commitToBranch;
}

From source file:org.eclipse.orion.server.git.servlets.GitBranchHandlerV1.java

License:Open Source License

private boolean handleGet(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException {
    // FIXME: what if there is a branch named "file"?
    Path p = new Path(path);
    if (p.segment(0).equals("file")) { //$NON-NLS-1$
        // branch list: expected path /git/branch/file/{path}
        File gitDir = GitUtils.getGitDir(p);
        Repository db = new FileRepository(gitDir);
        Git git = new Git(db);
        List<Ref> branches = git.branchList().call();
        JSONObject result = new JSONObject();
        JSONArray children = new JSONArray();
        for (Ref ref : branches) {
            JSONObject child = BranchToJSONConverter.toJSON(ref, db, getURI(request), 2);
            children.put(child);//ww w.  j av a 2  s . co m
        }
        result.put(ProtocolConstants.KEY_CHILDREN, children);
        OrionServlet.writeJSONResponse(request, response, result);
        return true;
    } else if (p.segment(1).equals("file")) { //$NON-NLS-1$
        // branch details: expected path /git/branch/{name}/file/{path}
        File gitDir = GitUtils.getGitDir(p.removeFirstSegments(1));
        Repository db = new FileRepository(gitDir);
        Git git = new Git(db);
        List<Ref> branches = git.branchList().call();
        JSONObject result = null;
        for (Ref ref : branches) {
            if (Repository.shortenRefName(ref.getName()).equals(p.segment(0))) {
                result = BranchToJSONConverter.toJSON(ref, db, getURI(request), 3);
                break;
            }
        }
        if (result == null) {
            String msg = NLS.bind("Branch {0} not found", p.segment(0)); //$NON-NLS-1$
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
        }
        OrionServlet.writeJSONResponse(request, response, result);
        return true;
    }

    return false;
}