UP | HOME

NOTE: trigger formatting by hook

With git hook, we can do automation for some common task, this article record how to use pre-commit to auto format changed files. The followig example is for JS project.

package.json

{
  ...
  "scripts": {
    "format": "prettier --ignore-unknown --write",
    ...
  }
  ...
}

.hooks/pre-commit

#!/bin/sh
FILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0

# Prettify all selected files
echo "$FILES" | xargs pnpm format

# Add back the modified/prettified files to staging
echo "$FILES" | xargs git add

exit 0

Another example for elixir

#!/bin/sh
FILES=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g')
[ -z "$FILES" ] && exit 0

echo "$FILES" | xargs mix format

echo "$FILES" | xargs git add

exit 0

1. Install

Finally, we need to install the hook

ln -sf $(pwd)/.hooks/pre-commit $(pwd)/.git/hooks/pre-commit
Date: 2022-02-15 Tue 00:00
Author: Lîm Tsú-thuàn