git SHA 是否可以显示为电子设备软件版本的一部分

Can git SHA be displayed as part of a software version for an electronic device

我想使用和显示一个相当标准的语义版本控制 MM.mm.bb = (M)ajor.(m)inor.(b)uild,但理想情况下我想要一些计算机生成的东西,因为我不由于此设备的特殊性,我不想自动增加内部版本号。

我正在考虑尝试包含 git SHA,但当然在您形成提交之前不会输出 SHA。

是否possible/reasonable将 SHA 包含在软件构建版本中(例如:MM.mm.bb-f9a8e8)?

考虑到我不想自动增加内部版本号,也不想添加除 git 之外的额外 SHA 计算,有没有更好的方法来做到这一点?

正如我在评论中指出的那样,Linux 内核可以解决问题。主要部分是setlocalversion脚本,其中最核心的部分是(原脚本里面有详细的解释,下面只是关键部分)

    if test -z "$(git rev-parse --show-cdup 2>/dev/null)" &&
       head=$(git rev-parse --verify --short HEAD 2>/dev/null); then
            if [ -z "$(git describe --exact-match 2>/dev/null)" ]; then
                    printf '%s%s' -g $head
            fi

            if {
                    git --no-optional-locks status -uno --porcelain 2>/dev/null ||
                    git diff-index --name-only HEAD
            } | grep -qvE '^(.. )?scripts/package'; then
                    printf '%s' -dirty
            fi
    fi

现在我们的C文件module.c:

#include <stdio.h>

#include "version.h"

int main(int argc, char *argv[])
{
    printf("Our version is: %s\n", VERSION);
    return 0;
}

Makefile

VERSION = 0.1

version.h: FORCE
    @echo "$(VERSION)$(shell $(PWD)/setlocalversion $(PWD))"
    @echo "#define VERSION \"$(VERSION)$(shell $(PWD)/setlocalversion $(PWD))\"" > version.h


module.o: version.h

all: module
    @$(PWD)/module

clean:
    @rm module module.o version.h

FORCE:

.PHONY: FORCE

演出时间:

$ make all
0.1-gb6d5c80
cc    -c -o module.o module.c
cc   module.o   -o module
Our version is: 0.1-gb6d5c80