Java 使用JGit TreeWalk列出文件和文件夹
我想使用JGit显示头部修订的所有文件和文件夹的列表。我可以使用TreeWalk列出所有文件,但这不会列出文件夹 以下是我到目前为止的情况:Java 使用JGit TreeWalk列出文件和文件夹,java,jgit,Java,Jgit,我想使用JGit显示头部修订的所有文件和文件夹的列表。我可以使用TreeWalk列出所有文件,但这不会列出文件夹 以下是我到目前为止的情况: public class MainClass { public static void main(String[] args) throws IOException { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository r
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中获取的路径字符串派生非空目录名
有关详细说明和可能的解决方法,请参阅(搜索“空目录”)。您需要将recursive设置为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());
}
}
是的,我已经在一些项目中使用了它,树节点的底层FileMode属性也允许检测符号链接,另请参见jgit cookbook,它在一个准备运行的示例中显示了这一点。这部分有效。Rüdiger Herrmann说得对,空目录将不会被列出。看起来我需要在空目录中添加一个.gitcept文件,以便跟踪它们。可以找到更多关于此技巧的信息