编写以下脚本是为了在预提交挂钩上按键对 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。
谢谢!
感谢@adelriosantiago 的评论,我明白了。
readdirSync()而不是readdir(). 然后我能够(通过日志记录)验证脚本确实仅在编辑文件时才结束。不幸的是,这还不够 - 钩子仍然以未提交的文件结束。 && git add src/assets/translations钩子pre-commit。现在一切都按预期进行。
| 归档时间: |
|
| 查看次数: |
2125 次 |
| 最近记录: |