使用git进行提交时设置版本号的最佳实践

我想自动将版本号设置为我的程序,这样它们与git标签一致.怎么做到这一点?这样做的建议方法是什么?

以下高度复杂的python脚本打印其版本号.每次提交时我应该如何自动更新该版本号?

# application.py
hardcoded_version_number = "0"
print("v"+hardcoded_version_number)

每次提交后,应更新版本号.

发布0.1 /初始提交:

hardcoded_version_number = "0.1"
print("v"+hardcoded_version_number)

特色1:

hardcoded_version_number = "0.1-1-gf5ffa14" # or something like this
print("v"+hardcoded_version_number)

发布0.2:

hardcoded_version_number = "0.2"
print("v"+hardcoded_version_number)

等等…

我目前的另一个问题是我正在使用的GUI元素在运行时期间无法从任何外部源读取版本号.所以我只有选择硬编码.

最佳答案 在为这些版本生成名称方面,我认为您正走在正确的轨道上.
git describe生成完全符合您要求的形式的字符串:

The command finds the most recent tag that is reachable from a commit. If the tag points to the commit, then only the tag is shown. Otherwise, it suffixes the tag name with the number of additional commits on top of the tagged object and the abbreviated object name of the most recent commit.

如果要从代码中访问此版本字符串,您基本上有两个选项:

>在构建阶段使用git describe提取它.在这种情况下,您可能希望将其写入未跟踪的临时文件,然后可以在运行时将其读入您的程序.我用过这种方法,效果很好.
>使用.gitattributes filter涂抹并清洁文件.我自己从未使用过这个,但实际上这是一种可以从存储库中的相同文件自动修改工作副本中的文件的方法.

为什么这些必要?好吧,Git不会让你自己写一个提交的哈希.提交哈希是基于许多事物计算的,包括文件内容,提交消息,时间戳和父哈希.当您知道哈希是什么时,它引用的提交被有效锁定.修改其内容或提交消息以包含其散列会使旧散列无效.

有关更多讨论,请参见this question.

点赞