Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get hash of most recent git commit in Node

Tags:

git

node.js

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.

like image 246
Noah Avatar asked Dec 29 '15 20:12

Noah


2 Answers

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})

like image 54
antoine129 Avatar answered Sep 19 '22 10:09

antoine129


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(); } 
like image 30
edin-m Avatar answered Sep 21 '22 10:09

edin-m