我如何从 jGit 获取 "typical" 提交日志?

How do I get a "typical" commit log back from jGit?

我知道 jGit 可以给我每个提交的“完整消息”(commit.getFullMessage()),但这只是用户写的。

如何像 运行 git log 一样吐出提交?

$ git log

commit 01432d24d68a95fd83b46cfa5e8edb474136cacd
Author: Samwise Gamgee <mayor@shire.gov>
Date:   Fri Sep 10 11:01:06 2021 -0600

    A dandy commit message

    More details about this infamously dandy commit message.

我找不到其他人对此的实现,所以我做了自己的(未优化的)实现。欢迎更多优化实施。

public class Commits {

    public static String getConventionalCommitMessage(RevCommit commit) {
        StringBuilder stringBuilder = new StringBuilder();

        // Prepare the pieces
        final String justTheAuthorNoTime = commit.getAuthorIdent().toExternalString().split(">")[0] + ">";
        final Instant commitInstant = Instant.ofEpochSecond(commit.getCommitTime());
        final ZoneId zoneId = commit.getAuthorIdent().getTimeZone().toZoneId();
        final ZonedDateTime authorDateTime = ZonedDateTime.ofInstant(commitInstant, zoneId);
        final String gitDateTimeFormatString = "EEE MMM dd HH:mm:ss yyyy Z";
        final String formattedDate = authorDateTime.format(DateTimeFormatter.ofPattern(gitDateTimeFormatString));
        final String tabbedCommitMessage =
                commit.getFullMessage()
                        .lines() // split it up by line
                        .map(s -> "\t" + s + "\n") // add a tab on each line
                        .collect(Collectors.joining()); // put it back together

        // Put pieces together
        stringBuilder
                .append("commit ").append(commit.getName()).append("\n")
                .append("Author:\t").append(justTheAuthorNoTime).append("\n")
                .append("Date:\t").append(formattedDate).append("\n\n")
                .append(tabbedCommitMessage);

        return stringBuilder.toString();
    }

}

它应该以或多或少的格式吐出字符串:

commit 01432d24d68a95fd83b46cfa5e8edb474136cacd
Author: Samwise Gamgee <mayor@shire.gov>
Date:   Fri Sep 10 11:01:06 2021 -0600

    A dandy commit message

    More details about this infamously dandy commit message.

搜索引擎的更多详细信息:

  • Git 的默认日志格式似乎是中等; format=medium
  • 使用 Git、运行 git log --pretty="format:%C(yellow)commit %H%n%C(white)Author: %an <%ae>%nDate: %ad%n%n%w(0,4,4)%B%n" 获取默认媒体格式
    • 感谢 René Link
  • Git 的中格式日期在 RFC-2822 format "with a few exceptions"