在jGit

时间:2017-02-01 14:26:58

标签: jgit

我有一个新克隆的存储库的SHA-1。我希望作者缩进这个SHA-1。

所以我需要使用RevWalk并迭代整个存储库?或者是否有findXX方法或其他代码可用于获取RevCommit或具有PersonIdent的其他对象?

我尝试了什么:

public void authorInfoOf(Repository repo, AnyObjectId head) {
    try {
        try (RevWalk walk = new RevWalk(repo)) {
            ObjectDatabase db = repo.getObjectDatabase();
            ObjectLoader k = repo.newObjectReader().open(head);
            ObjectReader s;
            // repo.newObjectReader().open(head);
            ObjectStream st = k.openStream();
            // RevWalk rw2 = new RevWalk(k);
            RevCommit commit = null;// walk.parseCommit(ref.getObjectId());

            PersonIdent authorIndent = commit.getAuthorIdent();
            System.out.println("\nCommit-Message: " + commit.getFullMessage() + " " + authorIndent.getEmailAddress());
        }
    } catch (Exception e) {
        System.out.println("Authir info of Anybject id Err " + e);
        e.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:2)

RevCommit表示Git存储库中的特定提交。使用RevWalk::parseCommit()获取特定对象ID / SHA-1的RevCommit

例如:

try( RevWalk walk = new RevWalk( repository ) ) {
  RevCommit commit = walk.parseCommit( ref.getObjectId() );
}

parseCommit返回给定ObjectId的匹配提交对象。

要将SHA-1(字符串)转换为ObjectId,请使用ObjectId::fromString()

ObjectId commitId = ObjectId.fromString( "ab434..." );

另请参阅:How to obtain the RevCommit or ObjectId from a SHA1 ID string with JGit?

在上面的示例中,Ref用于引用对象ID。 Ref表示对象id的命名引用,如分支,标记或HEAD等特殊引用。 Repository :: exactRef()可用于将字符串解析为Ref对象。

例如:

Ref headRef = repository.exactRef( "HEAD" );

答案 1 :(得分:0)

这对我有用:

public RevCommit getCommit(String idString, Repository repository, Git git){
    try{

        ObjectId o1 = repository.resolve(idString);
        if(o1 != null){
            try( RevWalk walk = new RevWalk( repository ) ) {
                  RevCommit commit = walk.parseCommit( o1 );
                  PersonIdent ai = commit.getAuthorIdent();
                  System.out.println("bbb >>" + ai.getEmailAddress() + "|" + ai.getTimeZone()  + "|" + ai.getWhen() + ", ref :" + idString);
                  return commit;
                }
        }else{
            System.err.println("Could not get commit with SHA :" + idString);
        }
    }catch (Exception e) {
        System.out.println("err :" + e);
        e.printStackTrace();
    }
    return null;
}