gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 19:40:39 34 4
gpt4 key购买 nike

我想使用 JGit 显示 head 修订版的所有文件和文件夹的列表。我可以使用 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());
}
}
}

最佳答案

您需要将 recursive 设置为 false(参见 documentation )然后像这样走:

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

关于java - 使用 JGit TreeWalk 列出文件和文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19941597/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com