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

时间:2011-06-23 18:28:22

标签: git version embed

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

关于如何使用Git执行此操作的任何想法?

6 个答案:

答案 0 :(得分:7)

这就是我的所作所为:

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

git describe --all > version.txt

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

答案 1 :(得分:7)

对我来说,git describe最初没有给出标签。然而,以下情况确实如此:

git describe --all --long

这导致了kubi所描述的格式。假设你只想要像下面这样的最后一部分(hashtag)(保存到version.txt文件):

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

编辑:正如朋友向我指出的那样,如果您愿意的话,实际上只需使用cut即可:

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

答案 2 :(得分:3)

要在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;
     }

答案 3 :(得分:3)

注意:看看Git本身如何计算自己的内部版本号很有意思 这只是在Git 2.12(2017年第一季度)中发展而来

commit a765974Ramsay Jones (``)(2016年12月4日) 帮助:Jeff King (peff)
Junio C Hamano -- gitster --合并于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:不要强制使用' describe'

使用的缩写长度      

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

     

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

     

这些天,"默认最低"自动缩放取决于   存储库的大小,指定一个没有意义   特别缩写长度;自Git 1.7.10.1以来我们想要的一切   我们将在默认情况下使用合理的东西"。

(这是在Git 2.11中引入的:见&#34的最后一部分; How much of a git sha is generally considered necessary to uniquely identify a change in a given codebase?")

  

放弃&#34; --abbrev=<number>&#34;通过调用&#34; git describe&#34;   让命令选择它认为合适的东西,拿走   最终用户的配置和存储库内容。

答案 4 :(得分:0)

不是将其放在文本文件中,而是每次都获取它的内容,这似乎很有效:

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

其中version.php如下所示:

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

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

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

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

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

和version.php:

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

答案 5 :(得分:0)

这就是我的做法。注意:要获得修订的Python代码来自this帖子。

BuildInfo.hpp

#ifndef BUILDINFO_HPP_
#define BUILDINFO_HPP_

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

#endif

(自动生成)BuildInfo.cpp

#include "BuildInfo.hpp"

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

GenerateBuildInfo.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()

要使用构建信息

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

要生成BuildInfo.cpp,请在构建后的步骤中调用(在本例中是从Eclipse IDE调用)

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