Saving git log number of the current commit in MATLAB

I wanted to save the current git commit hash of the code that I am currently running. Ideally, something like:
git_hash_string = get_current_git_hash()
dips(git_hash_string)
and then have it written to some file or displayed to the matlab command line. Is that possible?

 Accepted Answer

To simply query using the git command via the OS:
[s,git_hash_string] = system('git rev-parse HEAD')
Not sure how this might play with Matlab's git stuff... I haven't touched that, but use git separately to manage several of my Matlab libraries. I assume the underlying git management is the same regardless of whether you initialized the repo in Matlab or outside of it.

5 Comments

do you know why the length of my output changes depending on the argument to sprintf?:
>> disp(sprintf('%s',git_hash_string))
530132b03bf6ba9c7b5902235ca6a40716384658
>> disp(sprintf('%d',git_hash_string))
53514849515098485198102549897579955985357485050515399975497524855495451565254535610
thnks for the help btw :)
In the second instance, you're printing the ASCII numbers corresponding to each character in the string. Note the difference between
sprintf('%d\n', 530132) % <-- printing an integer as integer
ans =
530132
and
sprintf('%d\n', '530132') % <-- printing a string as integer
ans =
53
51
48
49
51
50
Last question (I hope). If I want to get the git hash from a different repo and I know the path would work?
[s,git_hash_string] = system('/path/git rev-parse HEAD')
I'd use the -C flag (an option for many git commands, including git-rev-parse):
[s,r] = system('git -C path/to/repo rev-parse HEAD')
As of git 1.8.3.1 on Linux, this gives me "Unknown option: -C"
[s,r] = system('git --git-dir=/path/to/repo/.git rev-parse HEAD')
To make it work, I had to give it the path to the hidden directory ".git" in my repo.

Sign in to comment.

More Answers (1)

If you are wanting to get a build number then I find the following works well:
system("git describe --tags --first-parent --abbrev=7 --long --dirty --always")
This will return the most recent tag in the repo, followed by the commit hash. I then write this to a file and append with a timestamp. You can then read the value from the file to get a build ID for your toolbox or similar, which can be displayed with the output.
Build: 1.0-4-gb52160e 03-Mar-2023 12:58:39
Inspired by the following from Stack Overflow.

Categories

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!