EdR
EdR

Reputation: 533

Can git hooks add a version number to my code files?

I have a git question to which the answer might be "don't do it that way" but here goes: I want to have a little dialog box in my code (Matlab as it happens) which displays the current version. This is mostly for my benefit (as developer) to check what version the user is running for support. This is fairly standard and I have Matlab code to read the version from a text file and display it. The trick I want to achieve is to have Git automatically update version.txt on each commit.

The code I am using is a shell script in .git/hooks/pre-commit that essentially dumps the output of git describe to the file version.txt (with some formatting). I have tags for major and minor versions, and git describe essentially gives that info, plus the number of commits since the last tag.

The problem is that if I use the pre-commit hook, then version.txt points to the commit before the one that is committed, but if I use the post-commit hook, then version.txt is edited after the commit is made and only can be committed to a new commit, which edits version.txt again...

I could perhaps use a script in post-commit that adds version.txt and then does a git commit --amend --no-edit, but this seems a bit messy. I also don't know if the post-commit hook would be run on the amend, leading to an infinite loop.

The pre-commit hook can to edit the code files, and commit them, but doesn't know the commit description. Is there a way around this? Perhaps another hook that I haven't found? Could I make the post-commit hook run commit without causing an infinite loop, and if I could, is it a good idea?

Is there a better way of doing this?

Edit after comment: Note that my users do not have Git installed. They download a source code bundle from Gitlab and unzip to run the Matlab code. Hence any solution cannot run Git on the fly but must get the version ID (in whatever from) from Git and write it into a (committed) file somehow.

Upvotes: 16

Views: 10007

Answers (2)

Vincent
Vincent

Reputation: 54

Old post but I guess this can be useful.

There are two ways to fully automate the version number:

Upvotes: -1

EdR
EdR

Reputation: 533

I found the answer by reading this question though I couldn't find it by searching, so I intend leaving this question open for now. What I originally intended is logically impossible: You can't have the hash of the current commit in any committed file. The hash depends on the file contents, and in my approach the file contents depend on the hash, giving a circular dependency.

I will need to change my approach.

Update for anyone else trying to solve a similar problem:

I have created a bash script deploy.sh that automates the process of creating a tag and adding the (tag) version number to a file in the codebase.

Upvotes: 5

Related Questions