【问题标题】:How can I get git commit message when I commited?提交时如何获得 git commit 消息?
【发布时间】:2019-11-03 15:55:18
【问题描述】:

提交时如何获得 git commit 消息?我用的是哈士奇。

我已经尝试在准备提交消息时获取提交消息。

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 将是未定义的。请帮忙,谢谢

【问题讨论】:

    标签: node.js git npm husky


    【解决方案1】:

    您在正确的轨道上,但这里发生的一些事情似乎不对。

    1. 您的命令 (git rev-list --format=%s --max-count=1 HEAD) 将从 last 提交中获取消息,而不是当前正在进行的提交。如果您是第一次提交,这将是 undefined,如果您的最终目标是使用当前提交消息,则可能不是您想要使用的。

    2. 为了阅读当前提交信息,你不能使用git rev-listgit log,或者任何回读之前提交的东西。看一下 Husky,它似乎也没有将消息作为参数传递,并且大多数人建议通过 Husky 的集合environment variable 获取存储消息的文件路径,然后使用 FS 读取它(链接:@ 987654321@、23)。

    基于上述观察,这里是更新的tweet-git/index.js,应该使用当前的提交消息:

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

    请注意关于需要调整gitRootDir 的警告; Husky 提供的路径是相对于 git 初始化文件夹的根目录的,而不是绝对的,因此您当前的设置需要进行一些调整。这就是为什么大多数人将package.json 放在项目根级别的部分原因,然后在脚本中,不要使用cd scripts && node my-git-hook.js,他们只使用node scripts/my-git-hook.js

    【讨论】:

    • 它正在工作。我能抓住消息。谢谢你的数据。
    猜你喜欢
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多