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

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

Introduction

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

Prototype

public String getEntryPathString() 

Source Link

Document

Get path of the current entry, as a string.

Usage

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

License:Apache License

private byte[] contentFromTree(RevTree tree) {
    try {//from w w w.  j  av  a  2  s .co  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:de.codesourcery.gittimelapse.GitHelper.java

License:Apache License

protected void readFile(String path, PathFilter filter, RevCommit current, final ByteArrayOutputStream buffer)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {
    final String strippedPath = stripRepoBaseDir(path);
    final ITreeVisitor visitor = new ITreeVisitor() {

        @Override//from w  w  w.  j  a  v a 2 s .c  o  m
        public boolean visit(TreeWalk treeWalk) throws MissingObjectException, IOException {
            final CanonicalTreeParser parser = treeWalk.getTree(0, CanonicalTreeParser.class);
            while (!parser.eof()) {
                if (parser.getEntryPathString().equals(strippedPath)) {
                    ObjectLoader loader = repository.open(parser.getEntryObjectId());
                    buffer.write(loader.getBytes());
                }
                parser.next(1);
            }
            return true;
        }
    };
    visitCommitTree(path, filter, current, visitor);
}

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 w  w  w .j a v a2s . c  o  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.egit.core.internal.storage.TreeParserResourceVariant.java

License:Open Source License

/**
 * Constructs a resource variant corresponding to the current entry of the
 * given CanonicalTreeParser./*w w  w. jav  a  2  s .  c om*/
 *
 * @param repository
 *            Repository from which this CanonicalTreeParser was created.
 * @param treeParser
 *            A CanonicalTreeParser to retrieve information from. This will
 *            only read information about the current entry on which this
 *            parser is positioned and will not change its state.
 * @return The created variant.
 */
public static TreeParserResourceVariant create(Repository repository, CanonicalTreeParser treeParser) {
    final String path = treeParser.getEntryPathString();
    final boolean isContainer = FileMode.TREE.equals(treeParser.getEntryFileMode());
    final ObjectId objectId = treeParser.getEntryObjectId();
    final int rawMode = treeParser.getEntryRawMode();

    return new TreeParserResourceVariant(repository, path, isContainer, objectId, rawMode);
}

From source file:org.eclipse.emf.compare.egit.internal.storage.TreeParserResourceVariant.java

License:Open Source License

/**
 * Constructs a resource variant corresponding to the current entry of the given CanonicalTreeParser.
 *
 * @param repository/*from   w ww . j  a v a  2 s. com*/
 *            Repository from which this CanonicalTreeParser was created.
 * @param treeParser
 *            A CanonicalTreeParser to retrieve information from. This will only read information about
 *            the current entry on which this parser is positioned and will not change its state.
 * @param workspacePath
 *            The workspace-relative path of this resource.
 * @return The created variant.
 */
public static TreeParserResourceVariant create(Repository repository, CanonicalTreeParser treeParser,
        IPath workspacePath) {
    final String path = treeParser.getEntryPathString();
    final boolean isContainer = FileMode.TREE.equals(treeParser.getEntryFileMode());
    final ObjectId objectId = treeParser.getEntryObjectId();
    final int rawMode = treeParser.getEntryRawMode();

    return new TreeParserResourceVariant(repository, path, workspacePath, isContainer, objectId, rawMode);
}

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);// w  w w  .  ja va  2  s . c o  m
    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:org.uberfire.java.nio.fs.jgit.JGitSubdirectoryCloneTest.java

License:Apache License

private ObjectId findIdForPath(final Git origin, final RevCommit originMasterTip, final String searchPath)
        throws Exception {
    try (TreeWalk treeWalk = new TreeWalk(origin.getRepository())) {
        final int treeId = treeWalk.addTree(originMasterTip.getTree());
        treeWalk.setRecursive(false);/*from  w w  w  .  j av a  2 s . com*/
        final CanonicalTreeParser treeParser = treeWalk.getTree(treeId, CanonicalTreeParser.class);
        while (treeWalk.next()) {
            final String path = treeParser.getEntryPathString();
            if (path.equals(searchPath)) {
                return treeParser.getEntryObjectId();
            }
        }
    }

    throw new AssertionError(
            String.format("Could not find path [%s] in commit [%s].", searchPath, originMasterTip.name()));
}

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();
    }//from   w  w w .ja va2s  .  co  m
    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());/*from  w  w w . ja  v a 2s  .  c om*/
        while (!treeParser.eof()) {
            if (treeParser.getEntryPathString().equals(ENTRY_COMMIT_REF)) {
                return revWalk.parseCommit(treeParser.getEntryObjectId());
            }
            treeParser.next();
        }
    }
    return null;
}