使用JGit TreeWalk列出文件和文件夹 [英] Use JGit TreeWalk to list files and folders

查看:619
本文介绍了使用JGit TreeWalk列出文件和文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JGit显示头版本的所有文件和文件夹的列表。我能够使用TreeWalk列出所有文件,但这不会列出文件夹。

I'd like to use JGit to display a list of all files and folders for the head revision. I'm able to list all files using TreeWalk, but this does not list folders.

以下是我到目前为止:

public class MainClass {

    public static void main(String[] args) throws IOException {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder
                .setGitDir(new File("C:\\temp\\git\\.git")).readEnvironment()
                .findGitDir().build();

        listRepositoryContents(repository);

        repository.close();
    }

    private static void listRepositoryContents(Repository repository) throws IOException {
        Ref head = repository.getRef("HEAD");

        // a RevWalk allows to walk over commits based on some filtering that is defined
        RevWalk walk = new RevWalk(repository);

        RevCommit commit = walk.parseCommit(head.getObjectId());
        RevTree tree = commit.getTree();
        System.out.println("Having tree: " + tree);

        // now use a TreeWalk to iterate over all files in the Tree recursively
        // you can set Filters to narrow down the results if needed
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(tree);
        treeWalk.setRecursive(true);
        while (treeWalk.next()) {
            System.out.println("found: " + treeWalk.getPathString());
        }
    }
}


推荐答案

Git不跟踪自己的目录。您只能从TreeWalk获取的路径字符串中派生非空目录名。

Git does not track directories of their own. You can only derive non-empty directory names from the path string you get from the TreeWalk.

请参阅 Git FAQ (搜索空目录)以获取详细说明和可能的解决方法。

See the Git FAQ (search for 'empty directory') for a detailed explanation and possible workarounds.

这篇关于使用JGit TreeWalk列出文件和文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆