在 makefile 变量中捕获 git 分支名称

Fab*_*ian 1 git awk makefile

我正在编写一个 Makefile 并希望在要传递到 --define 的变量中捕获当前分支名称。由于脚本有时但并不总是在 travis 上运行,因此 git 存储库可能处于分离状态。

我可以在命令行上提取分支名称,但不幸的是没有将它捕获到变量中。似乎 print $$2 在 Makefile 环境中不起作用。

我目前的线路是:

BRANCH := $(shell git for-each-ref --format='%(objectname) %(refname:short)' refs/heads | awk "/^$$(git rev-parse HEAD)/ {print $$2}")
Run Code Online (Sandbox Code Playgroud)

我得到

dfd943a57015dbd2129ca7b7033c4e1749f18974 BRANCH_NAME 
Run Code Online (Sandbox Code Playgroud)

而不仅仅是

 BRANCH_NAME
Run Code Online (Sandbox Code Playgroud)

Bit*_*Dog 8

接受的答案在可靠地提取分支名称时存在问题(哈希没问题)。如果当前 HEAD 提交是多个分支的当前头部,那么 BRANCH 的值将是“branch1 branch2”,这将在您的 Makefile 中产生意外结果。

只需使用:

BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
HASH := $(shell git rev-parse HEAD)
Run Code Online (Sandbox Code Playgroud)