Husky 预提交挂钩在提交后完成

noa*_*myg 4 node.js husky

编写以下脚本是为了在预提交挂钩上按键对 JSON 文件进行排序:

 /*
 * Will reorder all files in given path.
 */

const sortJson = require("sort-json");
const fs = require("fs");
const chalk = require("chalk");

const log = console.log;
const translationsPath = process.argv.slice(2).join(" ");

function readFiles(dirname) {
  try {
    return fs.readdirSync(dirname);
  } catch (e) {
    log(chalk.red(`Failed reading files from path; ${e}`));
  }
}

log(
  chalk.bgGreen(
    `Running json sort pre-commit hook on path: ${translationsPath}`
  )
);

const files = readFiles(translationsPath);
files.forEach((file) => {
  log(chalk.yellow(`Sorting ${file}...`));
  try {
    sortJson.overwrite(`${translationsPath}\\${file}`);
    log(chalk.green(`Finished sorting ${file}`));
  } catch (e) {
    log(chalk.red(`Failed sorting file ${file}; ${e}`));
  }
});

log(
  chalk.bgGreen(
    `Finished sorting files`
  )
);
Run Code Online (Sandbox Code Playgroud)

我将脚本附加到我的预提交package.json挂钩中husky

  "scripts": {
    "sort-translations": "node ./scripts/husky/json-sort src/assets/translations",
    ...
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run sort-translations"
    }
  },
Run Code Online (Sandbox Code Playgroud)

结果是提交完成,然后脚本才完成创建的取消暂存更改。脚本本身与Finished sorting files最后打印的消息同步运行。

我的问题是,如何使其同步;先跑完node ./scripts/husky/json-sort src/assets/translations,然后git commit

谢谢!

noa*_*myg 7

感谢@adelriosantiago 的评论,我明白了。

  1. 首先,我开始使用readdirSync()而不是readdir(). 然后我能够(通过日志记录)验证脚本确实仅在编辑文件时才结束。不幸的是,这还不够 - 钩子仍然以未提交的文件结束。
  2. 此时我意识到 - 这与 hook 无关,而是与 git staging 有关!脚本会结束它,但修改后的更改仍处于未暂存状态,因此不会提交。所以我添加了 && git add src/assets/translations钩子pre-commit

现在一切都按预期进行。