gofmt is one of the things I loved about using Golang.)
Of course, having to manually run
Save the following as
.pre-commit.sh in your repo:
git diff — name-only HEAD | grep ".*\.js" | xargs prettier — write
Now run the following commands:
$ chmod +x .pre-commit.sh
$ ln -s -f ../../pre.-commit.sh .git/hooks/pre-commit
$ git add .pre-commit.sh; git commit -m "Add pre-commmit.sh"
Ta-da. That’s all you need.
How does it work?
We created a shell script (named
.pre-commit.sh ) and made it executable using
chmod . Then we created a link to it at
.git/hooks/pre-commit, which is where git looks to find a pre-commit hook. As the name suggests, pre-commit hooks are run before each commit. We then committed the script to our git repo. (I like keeping track of my git hooks in the same repo.)
The script itself does three things:
git diff name-only HEADto find the file names for both staged and unstaged files which have changes
- Filters those filenames for those which end in
- Pipes those files as arguments to
prettier, and uses the
--writeflag to instruct
prettierto re-write those files
And while you’re at it, go thank jlongster for writing such a nice tool.