DEV Community

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

Posted on AI-assisted

My pre-commit hook passed a broken commit

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)