I'd like to get the id/hash of the most recent commit on the current branch in NodeJS.
In NodeJS, I'd like to get the most recent id/hash, with respect to git and commits thereof.
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):
.git/HEAD
.git/refs/heads/current-branch-name
.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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With