Reputation: 633
I want to automatically set version number to my program in such way they are consistent with git tags. How this could be done? And what is the suggested way of doing this?
The following highly sophisticated python script prints its version number. How should I automatically update that version number each time I commit something?
# application.py
hardcoded_version_number = "0"
print("v"+hardcoded_version_number)
After each commit version number should be updated.
release 0.1 / initial commit:
hardcoded_version_number = "0.1"
print("v"+hardcoded_version_number)
feature 1:
hardcoded_version_number = "0.1-1-gf5ffa14" # or something like this
print("v"+hardcoded_version_number)
release 0.2:
hardcoded_version_number = "0.2"
print("v"+hardcoded_version_number)
etc...
Another problem I have currently is that GUI element I'm using can't read version number from any external sources during runtime. So only option I have is to hardcode it.
Upvotes: 4
Views: 2243
Reputation: 137058
In terms of generating names for these versions I think you're on the right track. git describe
generates strings of exactly the form you're looking for:
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.
If you want to access this version string from your code you've essentially got two options:
Extract it using git describe
during a build phase. In this case you'll probably want to write it to an untracked temporary file, which can then be read into your program at run time. I've used this method, and it works well.
Use a .gitattributes
filter to smudge and clean the file. I've never used this myself, but essentially this is a way that files in your working copy can be automatically modified from the same files in your repository.
Why are these necessary? Well Git doesn't let you write a commit's hash to itself. A commit hash is computed based on a number of things, including file content, commit message, timestamp, and parent hashes. By the time you know what the hash is, the commit it references is effectively locked. Modifying its content or commit message to include its hash invalidates the old hash.
See this question for more discussion.
Upvotes: 2