JGit 底层 API 使用文档

JGit 的 API 有两种基本的层次:底层命令和高层命令。

概念

从用户指南的概念一节中可以看到, JGit 的基本概念如下:

  • Repository 仓库, 存储用于管理源码的所有 objects 和 refs
  • Git Objects 泛指 Git 对象, 在 Git object model 中, 所有对象都用 SHA-1 来表示. 在 JGit 中, 用 AnyObjectIdObjectId 类表示. 从仓库中解析某个对象, 简单传入对应的版本即可.
    ObjectId head = repository.resolve("HEAD");
    在 Git object model 中, 包含以下四种对象:
    • blob 用于保存文件数据
    • commit 指向某一棵 tree, 对应 RevCommit
    • tree 可以看作文件夹, 它指向其他的 tree 和 blob, 对应 RevTree
    • tag 标记某一次 commit, 通常用于标记特殊版本, 对应 RevTag
  • Ref 引用, 唯一对象标识符, 对某一个 git 对象 (blob, tree, commit, tag) 的引用
    Ref HEAD = repository.getRef("refs/heads/master");
  • RevWalk 该类用于从 commit 的关系图 (graph) 中遍历 commit.
    RevWalk walk = new RevWalk(repository);
  • RevCommit 表示一个 git 的 commit 对象
    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(objectIdOfCommit);
  • RevTree 表示一个 git 的 tree 对象, 遍历一棵 tree, 用 TreeWalk, 类似于 RevWalk
    RevWalk walk = new RevWalk(repository);
    RevTree tree = walk.parseTree(objectIdOfTree);
  • RevTag 表示一个 git 的 tag 对象
    RevWalk walk = new RevWalk(repository);
    RevTag tag = walk.parseTag(objectIdOfTag);

代码片段

创建裸仓库

Repository repository = FileRepositoryBuilder.create(gitDir);
repository.create(true);

可以通过 RevWalk 读取仓库日志。

  • revWalk.parseCommit 可读取一条commit
  • 遍历 revWalk,可读取所有日志
try (RevWalk walk = new RevWalk(repository)) {
    commit = walk.parseCommit(commitId);
    walk.dispose();
}

branch 最新提交记录

commitId = repository.resolve(branch);

TreeWalk 遍历

tw.addTree(commit.getTree());
tw.setFilter(PathFilter.create(path));
tw.setRecursive(false);

ObjectLoader

ObjectLoader ldr = tw.getObjectReader().open(objectId);
ObjectLoader ldr = repository.open(objectId, Constants.OBJ_BLOB);

参考文献