0

有谁知道如何使用 JGit API 来获取文件列表?我尝试找到类似的功能,例如git show在本地存储库上使用命令,例如

    git ls-tree -r --name-only 7feff221f86e040f0cd2e4227e9e1496fe16f376

我有一些这样的代码

    File gitDir = new File("/Users/xiansongzeng/NIOServer");
    Git git = Git.open(gitDir);
    Repository repo = git.getRepository();

    ObjectId lastCommitId = repo.resolve("7feff221f86e040f0cd2e4227e9e1496fe16f376");
    RevWalk revWalk = new RevWalk(repo);
    RevCommit commit = revWalk.parseCommit(lastCommitId);
    RevTree tree= commit.getTree();
    TreeWalk treeWalk = new TreeWalk(repo);
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);

    treeWalk.setFilter(PathFilter.create("src/main/java/nds/socket/server/Reader.java"));
    if(!treeWalk.next()){
        System.out.println("Not found.");
        return;
    }
    ObjectId objectId = treeWalk.getObjectId(0);

此代码针对本地存储库,用于RevWalk遍历最后一次提交的修订树。我发现这个示例PathFilter用于获取文件的引用,但不知道如何获取所有 Java 文件的列表。欢迎任何建议。

4

2 回答 2

1

建议使用树过滤器,PathSuffixFilter.create(".java")而不是测试从getPathString.

这样做的原因是getPathString必须解码路径(这是byte[]内部的),而PathSuffixFilter直接在byte[].

于 2013-07-15T15:20:09.847 回答
0

ls-tree is implemented in JGit: org.eclipse.jgit.pgm/src/org/eclipse/jgit/pgm/LsTree.java Usage is jgit ls-tree [-r|--recursive] <tree-ish> [-- paths...]

And cat-file is simple (credit goes to Shawn Pearce at git-dev@eclipse.org mailing list)

  int type;
  if (argv[0].equals("blob"))
    type = Constants.OBJ_BLOB;
  ...

  ObjectId id = ObjectId.fromString(argv[1]);
  ObjectLoader ldr = db.open(id, type);
  byte[] tmp = new byte[1024];
  InputStream in = ldr.openInputStream();
  int n;
  while ((n = in.read(tmp)) > 0)
    System.out.write(tmp, 0, n);
  in.close();
于 2015-11-29T20:03:15.847 回答