繁体   English   中英

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

[英]Use JGit TreeWalk to list files and folders

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

这是我到目前为止:

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

您需要将递归设置为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());
    }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM