How can I retrieve the current Git commit version from within a Ruby on Rails app?
Want to display the Git version (or maybe the last 6 letters or so) to serve as an App version.
How can I retrieve the current Git commit version from within a Ruby on Rails app?
Want to display the Git version (or maybe the last 6 letters or so) to serve as an App version.
You can invoke the git
command from within your script:
commit = `git show --pretty=%H`
puts commit
Depending on your environment you may want to use the full path to the git binary, and possibly specify the GIT_DIR via an environment variable or --git-dir
.
Like @meagar said, use backticks to execute the shell command from within your app, but you may find these two commands more useful:
Full hash:
git rev-parse HEAD
First 7 characters of hash:
git rev-parse --short HEAD
commit = `git rev-parse HEAD`.chomp
to remove the trailing newline –
Iain puts `git rev-parse HEAD`
–
Kandicekandinsky You can invoke the git
command from within your script:
commit = `git show --pretty=%H`
puts commit
Depending on your environment you may want to use the full path to the git binary, and possibly specify the GIT_DIR via an environment variable or --git-dir
.
A more robust solution would be git show --pretty=%H -q
. The -q
flag quiets the output.
In order to remove the newline that is part of the output, you can use chomp. For example: system('git show --pretty=%H -q').chomp
The selected answer has the potential to actually return the diff when the commit is not a merge commit. Verified on git version 2.16.2.windows.1.
I presume that you want to include the app version in your HTML somewhere? The prerequisite is that you are deploying your repo with Capistrano in the default manner (you are uploading the repo, not sending up an archive file).
You can add some code to the Rails initializer as outlined here. That approach will get the SHA1 from the last commit, and make it available as an environment variable.
The other way to do it is have you Capistrano task generate a static file in the public directory with the commit SHA in it. You could include other info in this file that seems useful.
© 2022 - 2024 — McMap. All rights reserved.