跳到正文
DEV Community· Mohamed Almearag·· 4 小時前AI 評分45

Locale Guard 的 pre-commit hook 曾放過有問題的提交

My pre-commit hook passed a broken commit

AI 導讀

Locale Guard 首個 pre-commit hook 檢查工作目錄中的檔案,未能發現未加入提交的翻譯缺漏,因而放過有問題的提交。現在 `--staged` 會讀取已暫存的檔案;此外,Locale Guard 也設有比較分支與 origin/main 的 pre-push hook,pull request 上的檢查則維持不變。

正文

Cover image for My pre-commit hook passed a broken commit

Mohamed Almearag

Locale Guard is my GitHub Action and CLI for translation files. It catches missing keys, broken placeholders, plural forms and untranslated text on pull requests, and since version 1.3.0 (npx locale-guard-cli) before each commit too. It's listed in the i18next docs and the awesome-i18n list.

The first version of its pre-commit hook let a broken commit through. Here's what went wrong and what I changed.

locale-guard-cli in a terminal: it lists the issues in the changed files and stops a commit from a Husky pre-commit hook

A pre-commit hook must check what the commit holds

My first hook ran the CLI on the files on disk. Then I tried this:

  1. Add a key to en.json and git add it.
  2. Translate it in ar.json, de.json and fr.json, but forget to git add them.
  3. Commit.

The hook passed. The files on disk were complete, so the check was happy. But the commit held only the English key, and the other languages were missing it.

A pre-commit hook has to read the staged files, not the working tree. Now --staged reads them from git: git ls-files --stage lists each staged file with the id of its content, and one git cat-file --batch process reads them all. With that, the same commit stops:

messages/ar.json
  2:3  error    Missing key Nav.deals  missing-keys

messages/de.json
  2:3  error    Missing key Nav.deals  missing-keys

messages/fr.json
  2:3  error    Missing key Nav.deals  missing-keys

✖ 3 new issues (3 errors) since the last commit
  2 existing issues are not shown. --all lists every issue.
husky - pre-commit script failed (code 1)

Hooks can be skipped with --no-verify, so there is also a pre-push hook that compares the branch with origin/main, and the check on the pull request stays on.

Try it

npx locale-guard-cli --all --files "locales/{locale}.json" --format vue-i18n

There are two demos you can clone and break, with Husky and Lefthook, and step-by-step guides.

If it reports something that isn't a bug, please open an issue.

I wrote this post with help from an AI assistant, and checked every detail against the code and the test runs.

來源:DEV Community · dev.to