Example usage for org.eclipse.jgit.treewalk CanonicalTreeParser next

List of usage examples for org.eclipse.jgit.treewalk CanonicalTreeParser next

Introduction

In this page you can find the example usage for org.eclipse.jgit.treewalk CanonicalTreeParser next.

Prototype

public CanonicalTreeParser next() 

Source Link

Document

Get this iterator, or its parent, if the tree is at eof.

Usage

From source file:com.thoughtworks.go.service.ConfigRepository.java

License:Apache License

private byte[] contentFromTree(RevTree tree) {
    try {/*from  w  w  w .ja  va 2  s. c o  m*/
        final ObjectReader reader = gitRepo.newObjectReader();
        CanonicalTreeParser parser = new CanonicalTreeParser();
        parser.reset(reader, tree);

        String lastPath = null;
        while (true) {
            final String path = parser.getEntryPathString();
            parser = parser.next();
            if (path.equals(lastPath)) {
                break;
            }

            lastPath = path;

            if (path.equals(CRUISE_CONFIG_XML)) {
                final ObjectId id = parser.getEntryObjectId();
                final ObjectLoader loader = reader.open(id);
                return loader.getBytes();
            }
        }
        return null;
    } catch (IOException e) {
        LOGGER.error("Could not fetch content from the config repository found at path '{}'",
                workingDir.getAbsolutePath(), e);
        throw new RuntimeException("Error while fetching content from the config repository.", e);
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.commitInfo.CommitTreeProcessor.java

License:Apache License

@NotNull
private TreeResult processTree(@NotNull final AnyObjectId tree, @NotNull final String basePathPrefix,
        @Nullable final SubmodulesConfig baseConfig) throws IOException {
    final Map<String, AnyObjectId> pathToSubmoduleHash = new HashMap<String, AnyObjectId>();
    final Map<String, AnyObjectId> childTrees = new HashMap<String, AnyObjectId>();
    SubmodulesConfig submodules = baseConfig;

    final CanonicalTreeParser ps = new CanonicalTreeParser();
    ps.reset(myReader, tree);/*from   ww  w  . j a  v  a2s  .co m*/
    if (ps.eof())
        return EMPTY;

    for (; !ps.eof(); ps.next()) {
        final FileMode mode = ps.getEntryFileMode();
        if (mode == FileMode.GITLINK) {
            pathToSubmoduleHash.put(basePathPrefix + ps.getEntryPathString(), ps.getEntryObjectId());
        }

        if (mode == FileMode.TREE) {
            childTrees.put(basePathPrefix + ps.getEntryPathString(), ps.getEntryObjectId());
        }

        if (submodules == null && mode == FileMode.REGULAR_FILE
                && DOT_GIT_MODULES.equals(ps.getEntryPathString())) {
            submodules = myModules.forBlob(ps.getEntryObjectId());
        }
    }

    if (submodules == null)
        return EMPTY;
    for (Map.Entry<String, AnyObjectId> e : childTrees.entrySet()) {
        final String path = e.getKey();
        if (!submodules.containsSubmodule(path))
            continue;

        //TODO: may also cache parsed sub-strees as well
        final TreeResult sub = processTree(e.getValue(), path + "/", submodules);
        pathToSubmoduleHash.putAll(sub.getSubmoduleToPath());
    }

    return new TreeResult(pathToSubmoduleHash, submodules);
}

From source file:org.eclipse.orion.server.gerritfs.GerritListFile.java

License:Open Source License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    handleAuth(req);/*from   ww  w  .j av a2 s  .  c om*/
    resp.setCharacterEncoding("UTF-8");
    final PrintWriter out = resp.getWriter();
    try {
        String pathInfo = req.getPathInfo();
        Pattern pattern = Pattern.compile("/([^/]*)(?:/([^/]*)(?:/(.*))?)?");
        Matcher matcher = pattern.matcher(pathInfo);
        matcher.matches();
        String projectName = null;
        String refName = null;
        String filePath = null;
        if (matcher.groupCount() > 0) {
            projectName = matcher.group(1);
            refName = matcher.group(2);
            filePath = matcher.group(3);
            if (projectName == null || projectName.equals("")) {
                projectName = null;
            } else {
                projectName = java.net.URLDecoder.decode(projectName, "UTF-8");
            }
            if (refName == null || refName.equals("")) {
                refName = null;
            } else {
                refName = java.net.URLDecoder.decode(refName, "UTF-8");
            }
            if (filePath == null || filePath.equals("")) {
                filePath = null;
            } else {
                filePath = java.net.URLDecoder.decode(filePath, "UTF-8");
            }
        }
        if (projectName != null) {
            if (filePath == null)
                filePath = "";
            NameKey projName = NameKey.parse(projectName);

            ProjectControl control;
            try {
                control = projControlFactory.controlFor(projName);
                if (!control.isVisible()) {
                    log.debug("Project not visible!");
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                            "You need to be logged in to see private projects");
                    return;
                }
            } catch (NoSuchProjectException e1) {
            }
            Repository repo = repoManager.openRepository(projName);
            if (refName == null) {
                ArrayList<HashMap<String, Object>> contents = new ArrayList<HashMap<String, Object>>();
                List<Ref> call;
                try {
                    call = new Git(repo).branchList().call();
                    Git git = new Git(repo);
                    for (Ref ref : call) {
                        HashMap<String, Object> jsonObject = new HashMap<String, Object>();
                        jsonObject.put("name", ref.getName());
                        jsonObject.put("type", "ref");
                        jsonObject.put("size", "0");
                        jsonObject.put("path", "");
                        jsonObject.put("project", projectName);
                        jsonObject.put("ref", ref.getName());
                        lastCommit(git, null, ref.getObjectId(), jsonObject);
                        contents.add(jsonObject);
                    }
                    String response = JSONUtil.write(contents);
                    resp.setContentType("application/json");
                    resp.setHeader("Cache-Control", "no-cache");
                    resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\"");
                    log.debug(response);
                    out.write(response);
                } catch (GitAPIException e) {
                }
            } else {
                Ref head = repo.getRef(refName);
                if (head == null) {
                    ArrayList<HashMap<String, String>> contents = new ArrayList<HashMap<String, String>>();
                    String response = JSONUtil.write(contents);
                    resp.setContentType("application/json");
                    resp.setHeader("Cache-Control", "no-cache");
                    resp.setHeader("ETag", "W/\"" + response.length() + "-" + response.hashCode() + "\"");
                    log.debug(response);
                    out.write(response);
                    return;
                }
                RevWalk walk = new RevWalk(repo);
                // add try catch to catch failures
                Git git = new Git(repo);
                RevCommit commit = walk.parseCommit(head.getObjectId());
                RevTree tree = commit.getTree();
                TreeWalk treeWalk = new TreeWalk(repo);
                treeWalk.addTree(tree);
                treeWalk.setRecursive(false);
                if (!filePath.equals("")) {
                    PathFilter pathFilter = PathFilter.create(filePath);
                    treeWalk.setFilter(pathFilter);
                }
                if (!treeWalk.next()) {
                    CanonicalTreeParser canonicalTreeParser = treeWalk.getTree(0, CanonicalTreeParser.class);
                    ArrayList<HashMap<String, Object>> contents = new ArrayList<HashMap<String, Object>>();
                    if (canonicalTreeParser != null) {
                        while (!canonicalTreeParser.eof()) {
                            String path = canonicalTreeParser.getEntryPathString();
                            FileMode mode = canonicalTreeParser.getEntryFileMode();
                            listEntry(path, mode.equals(FileMode.TREE) ? "dir" : "file", "0", path, projectName,
                                    head.getName(), git, contents);
                            canonicalTreeParser.next();
                        }
                    }
                    String response = JSONUtil.write(contents);
                    resp.setContentType("application/json");
                    resp.setHeader("Cache-Control", "no-cache");
                    resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
                    log.debug(response);
                    out.write(response);
                } else {
                    // if (treeWalk.isSubtree()) {
                    // treeWalk.enterSubtree();
                    // }
                    ArrayList<HashMap<String, Object>> contents = new ArrayList<HashMap<String, Object>>();
                    do {
                        if (treeWalk.isSubtree()) {
                            String test = new String(treeWalk.getRawPath());
                            if (test.length() /*treeWalk.getPathLength()*/ > filePath.length()) {
                                listEntry(treeWalk.getNameString(), "dir", "0", treeWalk.getPathString(),
                                        projectName, head.getName(), git, contents);
                            }
                            if (test.length() /*treeWalk.getPathLength()*/ <= filePath.length()) {
                                treeWalk.enterSubtree();
                            }
                        } else {
                            ObjectId objId = treeWalk.getObjectId(0);
                            ObjectLoader loader = repo.open(objId);
                            long size = loader.getSize();
                            listEntry(treeWalk.getNameString(), "file", Long.toString(size),
                                    treeWalk.getPathString(), projectName, head.getName(), git, contents);
                        }
                    } while (treeWalk.next());
                    String response = JSONUtil.write(contents);
                    resp.setContentType("application/json");
                    resp.setHeader("Cache-Control", "no-cache");
                    resp.setHeader("ETag", "\"" + tree.getId().getName() + "\"");
                    log.debug(response);
                    out.write(response);
                }
                walk.release();
                treeWalk.release();
            }
        }
    } finally {
        out.close();
    }
}

From source file:playRepository.BareCommit.java

License:Apache License

private TreeFormatter rebuildExistingTreeWith(String fileName, ObjectId fileObjectId) throws IOException {
    TreeFormatter formatter = new TreeFormatter();
    CanonicalTreeParser treeParser = getCanonicalTreeParser(this.repository);

    boolean isInsertedInTree = false;
    while (!treeParser.eof()) {
        String entryName = new String(treeParser.getEntryPathBuffer(), 0, treeParser.getEntryPathLength(),
                Config.getCharset());//from w ww  .  j  a  v a  2  s . c  o  m
        String nameForComparison = entryName;

        if (treeParser.getEntryFileMode() == FileMode.TREE) {
            nameForComparison = entryName.concat("/"); //for tree ordering comparison
        }
        if (nameForComparison.compareTo(fileName) == 0 && isInsertedInTree == false) {
            formatter.append(fileName, FileMode.REGULAR_FILE, fileObjectId);
            isInsertedInTree = true;
        } else if (nameForComparison.compareTo(fileName) > 0 && isInsertedInTree == false) {
            formatter.append(fileName, FileMode.REGULAR_FILE, fileObjectId);
            formatter.append(entryName.getBytes(Config.getCharset()), treeParser.getEntryFileMode(),
                    treeParser.getEntryObjectId());
            isInsertedInTree = true;
        } else {
            formatter.append(entryName.getBytes(Config.getCharset()), treeParser.getEntryFileMode(),
                    treeParser.getEntryObjectId());
        }

        treeParser = treeParser.next();
    }
    if (!isInsertedInTree) {
        formatter.append(fileName, FileMode.REGULAR_FILE, fileObjectId);
    }
    return formatter;
}

From source file:svnserver.repository.git.GitRepository.java

License:GNU General Public License

@NotNull
public Iterable<GitTreeEntry> loadTree(@Nullable GitTreeEntry tree) throws IOException {
    final GitObject<ObjectId> treeId = getTreeObject(tree);
    // Loading tree.
    if (treeId == null) {
        return Collections.emptyList();
    }/* w ww  . j  av a2 s .com*/
    final List<GitTreeEntry> result = new ArrayList<>();
    final Repository repo = treeId.getRepo();
    final CanonicalTreeParser treeParser = new CanonicalTreeParser(GitRepository.emptyBytes,
            repo.newObjectReader(), treeId.getObject());
    while (!treeParser.eof()) {
        result.add(new GitTreeEntry(treeParser.getEntryFileMode(),
                new GitObject<>(repo, treeParser.getEntryObjectId()), treeParser.getEntryPathString()));
        treeParser.next();
    }
    return result;
}

From source file:svnserver.repository.git.LayoutHelper.java

License:GNU General Public License

@Nullable
public static RevCommit loadOriginalCommit(@NotNull ObjectReader reader, @Nullable ObjectId cacheCommit)
        throws IOException {
    final RevWalk revWalk = new RevWalk(reader);
    if (cacheCommit != null) {
        final RevCommit revCommit = revWalk.parseCommit(cacheCommit);
        revWalk.parseTree(revCommit.getTree());

        final CanonicalTreeParser treeParser = new CanonicalTreeParser(GitRepository.emptyBytes, reader,
                revCommit.getTree());/*  w w w. java2 s . c  o  m*/
        while (!treeParser.eof()) {
            if (treeParser.getEntryPathString().equals(ENTRY_COMMIT_REF)) {
                return revWalk.parseCommit(treeParser.getEntryObjectId());
            }
            treeParser.next();
        }
    }
    return null;
}