Java 使用 JGit TreeWalk 列出文件和文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19941597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:42:55  来源:igfitidea点击:

Use JGit TreeWalk to list files and folders

javajgit

提问by Gaurav Sharma

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.

我想使用 JGit 显示头部修订的所有文件和文件夹的列表。我可以使用 TreeWalk 列出所有文件,但这不会列出文件夹。

Here is what I have so far:

这是我到目前为止所拥有的:

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());
        }
    }
}

采纳答案by Rüdiger Herrmann

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 不跟踪它们自己的目录。您只能从从 TreeWalk 获得的路径字符串派生非空目录名称。

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

有关详细说明和可能的解决方法,请参阅Git 常见问题解答(搜索“空目录”)。

回答by robinst

You need to set recursive to false (see documentation) and then walk like this:

您需要将递归设置为 false(请参阅文档),然后像这样走:

TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tree);
treeWalk.setRecursive(false);
while (treeWalk.next()) {
    if (treeWalk.isSubtree()) {
        System.out.println("dir: " + treeWalk.getPathString());
        treeWalk.enterSubtree();
    } else {
        System.out.println("file: " + treeWalk.getPathString());
    }
}