简体   繁体   中英

Get a list of files in a revision with JGit

Does anyone know how to use JGit API to get a list of files? I try to find a similar function like using the git show command on a local repository such as

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

I have some code like that

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

This code targets at a local repository, uses RevWalk to walk the revision tree of the last commit. I find this example using PathFilter to get the reference of a file, but dunno how to get the list of all Java files. Any suggestion is welcome.

Using a tree filter like PathSuffixFilter.create(".java") is recommended over testing the path returned from getPathString .

The reason for this is that getPathString has to decode the path (which is a byte[] internally), while PathSuffixFilter works directly on the byte[] .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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