Get hash of most recent git commit in Node
Short solution, no external module needed (synchronous alternative to Edin's answer):
revision = require('child_process')
.execSync('git rev-parse HEAD')
.toString().trim()
and if you want to manually specify the root directory of the git project, use the second argument of execSync
to pass the cwd
option, like execSync('git rev-parse HEAD', {cwd: __dirname})
Solution #1 (git required, with callback):
require('child_process').exec('git rev-parse HEAD', function(err, stdout) {
console.log('Last commit hash on this branch is:', stdout);
});
Optionally, you can use execSync()
to avoid the callback.
Solution #2 (no git required):
- get contents of the file
.git/HEAD
- if the git repo is in the detached head state, the content will be the hash
- if the git repo is on some branch, the content will be something like: "refs: refs/heads/current-branch-name"
- get contents of
.git/refs/heads/current-branch-name
- handle all possible errors in this process
- to get the latest hash from the master branch directly, you can get the contents of the file:
.git/refs/heads/master
This can be coded with something like:
const rev = fs.readFileSync('.git/HEAD').toString().trim();
if (rev.indexOf(':') === -1) {
return rev;
} else {
return fs.readFileSync('.git/' + rev.substring(5)).toString().trim();
}