11

我已经设法掌握了 jGit 文件的基础知识,包括连接到存储库以及添加、提交甚至循环文件的提交消息。

File gitDir = new File("/Users/myname/Sites/helloworld/.git");

RepositoryBuilder builder = new RepositoryBuilder();
Repository repository;
repository = builder.setGitDir(gitDir).readEnvironment()
        .findGitDir().build();

Git git = new Git(repository);
RevWalk walk = new RevWalk(repository);
RevCommit commit = null;

// Add all files
// AddCommand add = git.add();
// add.addFilepattern(".").call();

// Commit them
// CommitCommand commit = git.commit();
// commit.setMessage("Commiting from java").call();

Iterable<RevCommit> logs = git.log().call();
Iterator<RevCommit> i = logs.iterator();

while (i.hasNext()) {
    commit = walk.parseCommit( i.next() );
    System.out.println( commit.getFullMessage() );

}

我接下来要做的是能够获取单个文件的所有提交消息,然后能够将单个文件恢复到特定的参考/时间点。

4

4 回答 4

10

以下是如何根据所有父提交查找提交的更改

        var tree = new TreeWalk(repository)
        tree.addTree(commit.getTree)
        commit.getParents foreach {
            parent => tree.addTree(parent.getTree)
        }
        tree.setFilter(TreeFilter.ANY_DIFF)

(斯卡拉代码)

请注意, TreeFilter.ANY_DIFF 适用于单个 tree walker,并将返回根提交中可用的所有元素。

然后,您必须遍历树以查看您的文件是否在给定的增量中(这很容易)。

    while (tree.next)
            if (tree.getDepth == cleanPath.size) {
                // we are at the right level, do what you want
            } else {
                if (tree.isSubtree &&
                    name == cleanPath(tree.getDepth)) {
                    tree.enterSubtree
                }
            }
    }

(cleanPath是repo中的纯路径,用'/'分割)

现在将该代码包装到 RevWalk.next 循环中,您将获得提交和由提交更改的文件。

您可能希望使用与 ANY_DIFF 不同的过滤器,因为如果一棵树不同,则 ANY_DIFF 为真。在合并的情况下,与所有父树相比,blob 没有改变,这有点违反直觉。所以这里是 ALL_DIFF 的核心,它只会显示与所有父树不同的元素:

override def include(walker: TreeWalk): Boolean = {
    val n = walker.getTreeCount();
    if (n == 1) {
        return true;
    }
    val m = walker.getRawMode(0)
    var i = 1
    while (i < n) {
        if (walker.getRawMode(i) == m && walker.idEqual(i, 0)) {
            return false
        }
        i += 1
    }
    true
}

(scala 代码,源自 AnyDiffFilter)

于 2011-05-01T22:37:33.823 回答
8

所以我试图让 charlieboy 的解决方案发挥作用,而且大部分都成功了,但在以下情况下它失败了(也许自那篇帖子以来 jgit 发生了一些变化?)

添加文件A,提交为“提交1” 添加文件B,提交为“提交2”

getFileVersionDateList("fileA")

两者commit 1commit 2找到了,我只期望在哪里commit 1

我的解决方案如下:

List<Commit> commits = new ArrayList<Commit>();

RevWalk revWalk = new RevWalk(repository);
revWalk.setTreeFilter(
        AndTreeFilter.create(
                PathFilterGroup.createFromStrings(<relative path in question>),
                TreeFilter.ANY_DIFF)
);

RevCommit rootCommit = revWalk.parseCommit(repository.resolve(Constants.HEAD));
revWalk.sort(RevSort.COMMIT_TIME_DESC);
revWalk.markStart(rootCommit);

for (RevCommit revCommit : revWalk) {
    commits.add(new GitCommit(getRepository(), revCommit));
}

使用 LogCommand 更简单,看起来像这样:

List<Commit> commitsList = new ArrayList<Commit>();

Git git = new Git(repository);
LogCommand logCommand = git.log()
        .add(git.getRepository().resolve(Constants.HEAD))
        .addPath(<relative path in question>);

for (RevCommit revCommit : logCommand.call()) {
    commitsList.add(new GitCommit(this, revCommit));
}

显然,您还会根据需要检查提交日期等。

于 2012-08-25T00:12:38.660 回答
2

使用 git 查找特定文件历史的一般方法是遍历修订图(您正在执行此操作),并为每个修订图测试相关路径引用的对象(可以是 blob 或树查找整个子树的历史)。所以本质上充当了修订步行者对修订集输出的过滤器。

jgit 文档似乎......稀疏。但是您应该能够获得与每个 RevCommit 对应的 RevTree,并且如果有必要通过每个路径段依次向下遍历到终端对象 ID。

于 2011-01-24T00:13:29.450 回答
1

araqnid 是对的,这就是我获得日期列表的方式,每个日期都与包含相关文件的提交有关...

然后,您可以从特定提交中检索文件,因为您有文件名和提交日期,请参阅下面的两种方法....

注意:此代码在 .groovy 类中,因此您无疑必须针对 java 进行一些修改。

byte[] getAnyPreviousVersionFileBytes(String relativeFilePath, Date date) {

    byte[] bytes = null
    try {

        RevWalk revWalk = new RevWalk(repository)
        ObjectId headId = repository.resolve(Constants.HEAD);
        RevCommit root = revWalk.parseCommit(headId);

        revWalk.sort(RevSort.COMMIT_TIME_DESC);
        revWalk.markStart(root);

        for (RevCommit revCommit: revWalk) {

            // if date matches then walk the tree in this commit
            if (new Date(revCommit.commitTime * 1000L) == date) {

                TreeWalk treeWalk = TreeWalk.forPath(repository, relativeFilePath, revCommit.getTree())

                if (treeWalk != null) {
                    treeWalk.setRecursive(true)
                    CanonicalTreeParser canonicalTreeParser = treeWalk.getTree(0, CanonicalTreeParser)

                    while (!canonicalTreeParser.eof()) {

                        // if the filename matches, we have a match, so set teh byte array to return
                        if (canonicalTreeParser.getEntryPathString() == relativeFilePath) {
                            ObjectLoader objectLoader = repository.open(canonicalTreeParser.getEntryObjectId())
                            bytes = objectLoader.bytes
                        }
                        canonicalTreeParser.next(1)
                    }
                }
            }

        }

    }
    catch (Exception e) {
        throw new JgitException(e)
    }
    return bytes
}

List<Date> getFileVersionDateList(String relativeFilePath) {

    List<Date> versions = new LinkedList<Date>()
    try {

        RevWalk revWalk = new RevWalk(repository)
        ObjectId headId = repository.resolve(Constants.HEAD);
        RevCommit root = revWalk.parseCommit(headId);

        revWalk.sort(RevSort.COMMIT_TIME_DESC);
        revWalk.markStart(root);

        for (RevCommit revCommit: revWalk) {

            TreeWalk treeWalk = TreeWalk.forPath(repository, relativeFilePath, revCommit.getTree())

            if (treeWalk != null) {
                treeWalk.setRecursive(true)
                CanonicalTreeParser canonicalTreeParser = treeWalk.getTree(0, CanonicalTreeParser)

                while (!canonicalTreeParser.eof()) {
                    // if the filename matches, we have a match, so add the date of this commit to the list
                    if (canonicalTreeParser.getEntryPathString() == relativeFilePath) {
                        versions.add(new Date(revCommit.commitTime * 1000L))
                    }
                    canonicalTreeParser.next(1)
                }
            }
        }
    }
    catch (Exception e) {
        throw new JgitException(e)
    }

    return versions
}
于 2011-04-14T10:47:17.487 回答