如何以编程方式获取 Git 的版本?

How to get the version of Git programmatically?

How can I find out what version of git I'm running? 中所述,您可以通过

获取 git 版本
$ git version
git version 2.30.0

但看起来这是供人类而不是程序使用的。那是对的吗?如果有,是否有“管道”git version 命令可用于版本的数值比较?

管道?

git --version | awk '{print }'

我检查了源代码。有一条关于保持 git version 格式稳定的评论,因此可以安全地解析它。

void get_version_info(struct strbuf *buf, int show_build_options)
{
    /*
     * The format of this string should be kept stable for compatibility
     * with external projects that rely on the output of "git version".
     *
     * Always show the version, even if other options are given.
     */
    strbuf_addf(buf, "git version %s\n", git_version_string);
...