javascript - 在package.json中执行precommit hook时如何获取文件路径?

标签 javascript node.js git npm

现在在package.json中我设置了"precommit": "lint node internal/scripts/precommit",我想获取所有提交的文件路径我的precommit.js,有什么办法解决这个问题吗?

最佳答案

从“Git pre-commit hook : changed/added files ”开始,实际的 Git 命令是:

git diff --cached --name-only --diff-filter=ACM -z | xargs -0 ...

您可以看到来自 templates/hooks--pre-commit.sample 的一种可能用法.
它实际上也用于 JavaScript Standard Style GitHub 存储库。

最后,请使用spawnSync ,如“Catching Fatal Errors with Node.js child_process

The best way to catch errors without letting your app brick is by using the process' spawn (or in this case spawnSync) method:

var childProcess = require('child_process');

var commitMessage = (function() {
    var spawn = childProcess.spawnSync('git', ['log', '--format=%B', '-n', '1']);
    var errorText = spawn.stderr.toString().trim();

    if (errorText) {
      console.log('Fatal error from `git log`.  You must have one commit before deploying.');
      throw new Error(errorText);
    }
    else {
      return spawn.stdout.toString().trim();
    }
})();

With this method you can check the stderr buffer first; if there's a String from it you know it errored out, if no error text then the process was clean!

根据您的钩子(Hook)情况调整此方法,并按照上面建议的命令更改其 Git 命令。

关于javascript - 在package.json中执行precommit hook时如何获取文件路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48136097/

相关文章:

javascript - 需要使用 JavaScript 统计 HTML 页面上的某些项目

javascript - Angular Material md-select ng-model 设置为未定义的规则

javascript - 如何使用正则表达式仅获取字符串中的数值?

node.js - Sequelize/NodeJS TINYINT 转换为缓冲区问题

merge 之间的 git rebase 导致完全不相关的文件发生冲突

javascript - href ="tel:"不适用于 ionic 3

json - 将字符串转换为具有相同名称的 JSON 对象(js 中的某种动态代码需要此)

node.js - 如何通过@types 为作用域/命名空间包安装 TypeScript 声明?

git - AWS CodeCommit - 可以克隆/pull 但不能推送 (SSH)

git - 使用一个 Remote pull 另一个 Remote 使用 Git