1

NOTE: trigger formatting by hook

 2 years ago
source link: https://dannypsnl.github.io/blog/2022/02/15/cs/format-hook/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

Install

Finally, we need to install the hook

ln -sf $(pwd)/.hooks/pre-commit $(pwd)/.git/hooks/pre-commit

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK