Search code examples
node.jsgitnpmhusky

How can I get git commit message when I commited?


How can I get git commit message when I commit? I use husky.

I already tried to get commit message when it's prepare-commit-msg.

pacakgejson

{
  ...
  "version": "0.1.0",
  "private": true,
  ...
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "prepare-commit-msg": "cd ../tweet-git && node index.js"
    }
  },
  ...
}

tweet-git/index.js

require('child_process').exec('git rev-list --format=%s --max-count=1 HEAD', function(err, stdout) {
    const stdoutArray = stdout.split('\n')
    let commitMessage = `【tweet-git】\nプロジェクト: 「project」にcommitしました\n`
    commitMessage += stdoutArray[1]
    console.log('commitMessage', commitMessage);
});

stdout will be undefined. Please help, Thank you


Solution

  • You are on the right track, but there are a couple things going on here that seem off.

    1. Your command (git rev-list --format=%s --max-count=1 HEAD) would get the message from the last commit made, not the one currently in progress. This would be undefined if you are making your first commit, and is probably not what you want to be using if your eventual goal is to use the current commit message.

    2. In order to read the current commit message, you can't use git rev-list or git log, or anything that reads back prior commits. Taking a look at Husky, it looks like it doesn't pass the message along as an argument either, and most people recommend grabbing the filepath of the stored message through Husky's set environment variable and then using FS to read it (links: 1, 2, 3).

    Based on the above observations, here is an updated tweet-git/index.js that should use the current commit message:

    const fs = require('fs');
    const path = require('path');
    
    // Tweak this to match the root of your git repo,
    // below code assumes that git root is one dir above `/tweet-git`
    const gitRootDir = __dirname + '/../';
    
    const messageFile = path.normalize(gitRootDir + '/' + process.env.HUSKY_GIT_PARAMS.split(' ')[0]);
    let commitMessage = `【tweet-git】\nプロジェクト: 「project」にcommitしました\n`
    commitMessage += fs.readFileSync(messageFile, {encoding: 'utf-8'});
    console.log('commitMessage', commitMessage);
    

    Please note the warning about needing to tweak gitRootDir; the path that Husky provides is relative to the root of the git initialized folder, and not absolute, so your current setup would require some tweaking. This is part of why most people put package.json at the project root level, and then in scripts, don't use cd scripts && node my-git-hook.js, they just use node scripts/my-git-hook.js.