DEV Community

Mehak Fatima
Mehak Fatima

Posted on

How to get Last git Commit in Js file

Pre-Requisite:

  • How to use git.
  • Purpose of git.

Motivation:

  • You can collect following values inside the js file.
  • What is the subject of latest git commit.
  • what is the branch of latest git commit.
  • what is the hash of latest git commit and so on.
{
  "shortHash": "d2346fa",
  "hash": "d2346faac31de5e954ef5f6baf31babcd3e899f2",
  "subject": "initial commit",
  "sanitizedSubject": "initial-commit",
  "body": "this is the body of the commit message",
  "authoredOn": "1437988060",
  "committedOn": "1437988060",
  "author": {
    "name": "Ozan Seymen",
    "email": "oseymen@gmail.com"
  },
  "committer": {
    "name": "Ozan Seymen",
    "email": "oseymen@gmail.com"
  },
  "notes": "commit notes",
  "branch": "master",
  "tags": ['R1', 'R2']
}


Enter fullscreen mode Exit fullscreen mode

Step:

  • Node provide us Library for this purpose npm i git-last-commit.
  • Create a file Git.js and add this function here.
const git = require("git-last-commit");
function getGitCommit() {
  return new Promise((res, rej) => {
    git.getLastCommit((err, commit) => {
      if (err) {
        return rej(err);
      } else {
        return res(commit);
      }
    });
  });
}
module.exports = {
  lastGitCommit: getGitCommit,
};

Enter fullscreen mode Exit fullscreen mode
  • This function will return the Value of latest git commit, Call this function in other files like this.
const axios = require('axios');
const {lastGitCommit} = require('./Git');
const gitCommit = [];
const gitInfo = async () => {
  const response = await lastGitCommit();
  // console response and check if anything else you need.
  gitCommit.push(response);
  return response;
};
gitInfo();

Enter fullscreen mode Exit fullscreen mode
  • Now just extract the values from gitCommit.
  • const hash= gitCommit[0].subject.

Top comments (0)