使用 JGit fetch() 并检查更新的文件

Using JGit fetch() and check for updated files

使用 JGit,我检查了一个分支 (branch1)。一段时间后,我想 fetch() 并查看自上次获取以来哪些文件已更新(在源中)。

FetchResult fetchResult = m_git.fetch().setRefSpecs(new RefSpec("refs/heads/branch1")).call();

// For example:
fetchResult.getUpdatedFiles()

我该怎么做?

提取的粒度级别 API 是提交,而不是文件。因此,fetch 本身不会告诉您更新了哪些文件。

但是 FetchResult 包含有关获取操作结果的详细信息。

遍历 FetchResult::getTrackingRefUpdates 以查看所有已更新的引用(在您的示例中应该只是一个)。对于您感兴趣的每个更改的引用,TrackingRefUpdate 描述了相应引用的提取操作的结果。

首先查看 result 属性 以查看总体结果是否符合您的要求。对于常规 ref 更新,使用 getOldObjectIdgetNewObjectId 来区分新旧提交。

在这里查看如何与 JGit 进行比较:How to show changes between commits with JGit

我找到了适合我的东西。

大部分内容来自 jgit 食谱:https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ShowFileDiff.java#start-of-content

下面的 DiffEntry 集合显示了修改后的文件。 (仅供参考,这可以在合并之前完成)

fetch();

// todo: isn't there a critical section here? Only within the same repo maybe. We could prevent simultaneous use of the same racfid.
Ref fetchHead;
try {
    fetchHead = m_git.getRepository().findRef("FETCH_HEAD");

    //todo: show the diff bewteen fetch-head and the current head.
    // - get object id of fetch
    // - get oid of head

    ObjectId head = m_git.getRepository().resolve(Constants.HEAD);

    AbstractTreeIterator oldTreeParser = prepareTreeParser(m_git.getRepository(), fetchHead.getObjectId());
    AbstractTreeIterator newTreeParser = prepareTreeParser(m_git.getRepository(), head);

    List<DiffEntry> diff = m_git.diff().
        setOldTree(oldTreeParser).
        setNewTree(newTreeParser).
        // setPathFilter(PathFilter.create("README.md")).
        // to filter on Suffix use the following instead
        //setPathFilter(PathSuffixFilter.create(".java")).
        call();

    for (DiffEntry entry : diff) {
        System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
    }

}

private static AbstractTreeIterator prepareTreeParser(Repository repository, ObjectId objectId) throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    //noinspection Duplicates
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(objectId);
        RevTree tree = walk.parseTree(commit.getTree().getId());
        CanonicalTreeParser treeParser = new CanonicalTreeParser();
        try (ObjectReader reader = repository.newObjectReader()) {
            treeParser.reset(reader, tree.getId());
        }
        walk.dispose();
        return treeParser;
    }
}