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
I was inspired by edin-m's "Solution #2 (no git required)", but I didn't like the substring(5)
part which felt like a dangerous assumption. I feel my RegEx is much more tolerant to the variations allowed in git's loose requirements for that file.
The following demo shows that it works for both a checked out branch and a "detached HEAD".
$ cd /tmp
$ git init githash
Initialized empty Git repository in /private/tmp/githash/.git/
$ cd githash
$ cat > githash.js <<'EOF'
const fs = require('fs');
const git_hash = () => {
const rev = fs.readFileSync('.git/HEAD').toString().trim().split(/.*[: ]/).slice(-1)[0];
if (rev.indexOf('/') === -1) {
return rev;
} else {
return fs.readFileSync('.git/' + rev).toString().trim();
}
}
console.log(git_hash());
EOF
$ git add githash.js
$ git commit -m 'https://stackoverflow.com/a/56975550/117471'
[master (root-commit) 164b559] https://stackoverflow.com/a/56975550/117471
1 file changed, 14 insertions(+)
create mode 100644 githash.js
$ node githash.js
164b559e3b93eb4c42ff21b1e9cd9774d031bb38
$ cat .git/HEAD
ref: refs/heads/master
$ git checkout 164b559e3b93eb4c42ff21b1e9cd9774d031bb38
Note: checking out '164b559e3b93eb4c42ff21b1e9cd9774d031bb38'.
You are in 'detached HEAD' state.
$ cat .git/HEAD
164b559e3b93eb4c42ff21b1e9cd9774d031bb38
$ node githash.js
164b559e3b93eb4c42ff21b1e9cd9774d031bb38