node.js - 当我提交时如何获取 git commit 消息?

标签 node.js git npm husky

提交时如何获取 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 将是未定义的。请帮忙,谢谢

最佳答案

您的方向是正确的,但这里发生的一些事情似乎不太对劲。

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

  2. 要读取当前提交消息,您不能使用git rev-listgit log,或者任何读回先前提交的内容。看一下 Husky,它似乎也没有将消息作为参数传递,大多数人建议通过 Husky 设置的环境变量来获取存储消息的文件路径,然后使用 FS 来获取存储消息的文件路径。阅读它(链接: 123 )。

根据上述观察,这里是一个更新的 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);

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.

关于node.js - 当我提交时如何获取 git commit 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58676356/

相关文章:

node.js - 如何防止express-ejs-layouts 包装我的其他页面?

git - SourceTree 非常慢,有很多存储库

jquery - 使用npm爬虫爬取Node.js错误

node.js - 如何使用具有不同/自定义模块名称的 npm 安装软件包

javascript - 在 Javascript 服务器/客户端中共享对象定义

node.js - 如何在查询中使用 $push 将数据插入子文档,而不是检索文档并将其保存回来

解决冲突后的Xcode 9.3 Git merge Issue

javascript - Laravel Mix 我无法访问我的 javascript 类

node.js - Node-Webkit:fs.readdirSync ("~")不起作用

multithreading - 如何以多线程或高效方式执行 "git pull"?