如何获取 Git 内部版本号并将其嵌入到文件中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6458883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 05:36:36  来源:igfitidea点击:

How can I get the Git build number and embed it in a file?

gitversionembed

提问by qodeninja

I want to introduce a versioning constant grabbed from the version in Git. I know how to do this -- in a very hackish way in svn --

我想介绍一个从 Git 版本中抓取的版本控制常量。我知道如何做到这一点——在 svn 中以一种非常黑客的方式——

any ideas on how to do this with Git?

关于如何用 Git 做到这一点的任何想法?

采纳答案by Niels Abildgaard

For me, git describe didn't initially give the hashtag. The following did, however:

对我来说, git describe 最初并没有给出主题标签。然而,以下做了:

git describe --all --long

This results in something of the by kubi described format. Supposing you would only want the last part (hashtag) something like the following would do (saving to version.txt file):

这导致了一些由 kubi 描述的格式。假设您只需要最后一部分(主题标签),如下所示(保存到 version.txt 文件):

git describe --all --long | tr "-" " " | awk '{ print  }' > version.txt

EDIT: As a friend pointed out to me this can actually be done using just cutinstead, if you so desire:

编辑:正如一位朋友向我指出的那样cut,如果您愿意,实际上可以使用 just来完成:

git describe --all --long | cut -d "-" -f 3 > version.txt

回答by kubi

Here's what I do:

这是我所做的:

As part of my build process I run the following script (paraphrased, since I'm not at Xcode right now)

作为构建过程的一部分,我运行以下脚本(解释为,因为我现在不在 Xcode 中)

git describe --all > version.txt

Inside my application I read the version number out of this file and display it to the user (when necessary). Make sure you add version.txtto your .gitignore. The benefit of doing it this way is that if you tag your releases git describewill just output the tag, otherwise it'll output the commit hash.

在我的应用程序中,我从该文件中读取版本号并将其显示给用户(必要时)。确保将version.txt添加到.gitignore。这样做的好处是,如果你标记你的发布git describe将只输出标签,否则它会输出提交哈希。

回答by Prosto Trader

To get Git revision in php, I use something like this (change your paths to .Git catalog)

为了在 php 中获得 Git 修订版,我使用了这样的东西(将您的路径更改为 .Git 目录)

public static function getGitRevision()
     {
         $rev = trim(file_get_contents(NT_Path::ROOT . "/.git/HEAD"));

         if (substr($rev, 0, 4) == 'ref:') {
             $ref =  end(explode('/', $rev));
             $rev = trim(file_get_contents(NT_Path::ROOT . "/.git/refs/heads/{$ref}"));
         }

         return $rev;
     }

回答by VonC

Note: it is interesting to see how Git itself computes its own build number.
That just evolved in Git 2.12 (Q1 2017)

注意:看看 Git 本身如何计算自己的内部版本号很有趣。
刚刚在 Git 2.12(2017 年第一季度)中演变

See commit a765974(04 Dec 2016) by Ramsay Jones (``).
Helped-by: Jeff King (peff).
(Merged by Junio C Hamano -- gitster--in commit 0a45050, 19 Dec 2016)

请参阅Ramsay Jones (``) 的提交 a765974(2016 年 12 月 4 日)
帮助者:杰夫·金 ( peff)
(由Junio C gitsterHamano合并-- --commit 0a45050,2016 年 12 月 19 日)

GIT-VERSION-GEN 

VN=$(git describe --match "v[0-9]*" HEAD 2>/dev/null) 
# instead of
VN=$(git describe --match "v[0-9]*" --abbrev=7 HEAD 2>/dev/null)

GIT-VERSION-GEN: do not force abbreviation length used by 'describe'

The default version name for a Git binary is computed by running "git describe" on the commit the binary is made out of, basing on a tag whose name matches "v[0-9]*", e.g. v2.11.0-rc2-2-g7f1dc9.

In the very early days, with 9b88fce ("Makefile: use git-describeto mark the git version.", 2005-12-27), we used "--abbrev=4" to get absolute minimum number of abbreviated commit object name.
This was later changed to match the default minimum of 7 with bf50515 ("Git 1.7.10.1", 2012-05-01).

These days, the "default minimum" scales automatically depending on the size of the repository, and there is no point in specifying a particular abbreviation length; all we wanted since Git 1.7.10.1 days was to get "something reasonable we would use by default".

GIT-VERSION-GEN: 不要强制使用 ' describe' 的缩写长度

Git 二进制文件的默认版本名称是通过git describe在生成二进制文件的提交上运行“ ”来计算的,基于名称与“ v[0-9]*”匹配的标签,例如v2.11.0-rc2-2-g7f1dc9

在很早的时候,使用9b88fce (" Makefile: use git-describeto mark the git version.", 2005-12-27),我们使用 " --abbrev=4" 来获得绝对最小数量的缩写提交对象名称。
后来更改为将默认最小值 7 与bf50515 ("Git 1.7.10.1", 2012-05-01)相匹配。

现在,“默认最小值”会根据存储库的大小自动缩放,并且没有必要指定特定的缩写长​​度;自 Git 1.7.10.1 天以来,我们想要的只是“我们默认使用的合理的东西”。

(That was introduced in Git 2.11: see the last part of "How much of a git sha is generallyconsidered necessary to uniquely identify a change in a given codebase?")

(这是在 Git 2.11 中引入的:请参阅“通常认为需要多少 git sha才能唯一标识给定代码库中的更改?”的最后一部分)

Just drop "--abbrev=<number>" from the invocation of "git describe" and let the command pick what it thinks is appropriate, taking the end user's configuration and the repository contents into account.

只需--abbrev=<number>从“ ”的调用中删除“ ”,git describe然后让命令选​​择它认为合适的内容,同时考虑最终用户的配置和存储库内容。

回答by Ashley Duncan

This is how I have done it. Note: Python code to get revision came from thispost.

我就是这样做的。注意:获得修订的 Python 代码来自这篇文章。

BuildInfo.hpp

构建信息文件

#ifndef BUILDINFO_HPP_
#define BUILDINFO_HPP_

struct BuildInfo
{
    static const char Name[];
    static const char GitRevision[];
};

#endif

(Auto Generated) BuildInfo.cpp

(自动生成)BuildInfo.cpp

#include "BuildInfo.hpp"

const char BuildInfo::Name[] = "MyAppNAme";
const char BuildInfo::GitRevision[] = "5e854351b342acff6a3481d9106076df379c449a";

GenerateBuildInfo.py. Python script to generate BuildInfo.cpp. Note that this could be easily adapted to get short or long revision numbers or other repository info. It could also be converted to generate C code rather than cpp so is compatible with both.

生成BuildInfo.py。生成 BuildInfo.cpp 的 Python 脚本。请注意,这可以很容易地进行调整以获取短或长的修订号或其他存储库信息。它也可以转换为生成 C 代码而不是 cpp,因此与两者兼容。

import sys
import os
import subprocess

#args: [0]: this script path [1]: Output file name [2]: Application name string

# Return the git revision as a string
def git_version():
    def _minimal_ext_cmd(cmd):
        # construct minimal environment
        env = {}
        for k in ['SYSTEMROOT', 'PATH']:
            v = os.environ.get(k)
            if v is not None:
                env[k] = v
        # LANGUAGE is used on win32
        env['LANGUAGE'] = 'C'
        env['LANG'] = 'C'
        env['LC_ALL'] = 'C'
        out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0]
        return out

    try:
        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
        GIT_REVISION = out.strip().decode('ascii')
    except OSError:
        GIT_REVISION = "Unknown"

    return GIT_REVISION

if len(sys.argv) < 2 :
    exit("No output file name argument provided")
elif len(sys.argv) >= 3 :
    name = sys.argv[2]
else :
    name = ""

revision = git_version()
if (revision == "Unknown") :
    exit("Cant get git revision")

with open(sys.argv[1], "w") as f :
    f.write('#include "BuildInfo.hpp"\r\n\r\n')
    f.write('const char BuildInfo::Name[] = "' + name + '";\r\n')
    f.write('const char BuildInfo::GitRevision[] = "' + revision + '";\r\n')
    f.close()

To use the build info

使用构建信息

#include "BuildInfo.hpp"
...
PrintRevision(BuildInfo::GitRevision);

To generate BuildInfo.cpp, in a post build step I call (from eclipse IDE in this case)

要生成 BuildInfo.cpp,在我调用的后期构建步骤中(在这种情况下来自 eclipse IDE)

python ${ProjDirPath}/build/GenerateBuildInfo.py ${ProjDirPath}/src/BuildInfo.cpp ${ProjName}

回答by SeanJA

Instead of putting it in a text file then getting the contents of it each time, this appears to work quite well:

不是把它放在一个文本文件中然后每次都获取它的内容,这似乎工作得很好:

sed -i.bak "s/$version = '.*';/$version = '`git rev-parse --short HEAD | tr -d '\n'`';/g" version.php

where version.php looks like this:

其中 version.php 看起来像这样:

<?php
$version = 'some version string';

and then just include the file in your script as you would a settings file.

然后就像将设置文件一样包含在脚本中。

You could also use git describe --all --longas your version string if you wanted to, I preferred the git-hash from git-ref-parse --short HEADfor my purposes.

git describe --all --long如果您愿意,您也可以将其用作版本字符串,git-ref-parse --short HEAD出于我的目的,我更喜欢 git-hash 。

Or as a constant which may be better:

或者作为一个可能更好的常数:

sed -i.bak "s/define('VERSION','.*');/define('VERSION','`git describe --all --long | cut -d "-" -f 3`');/g" version.php

and version.php:

和 version.php:

<?php
define('VERSION','some version string');