Working in languages like Elixir and Rust is fun for many reasons. But one of
my favorite features is the formatter. Elixir (after 1.4) comes with a
formatter which is well integrated with mix
and can be called using
mix format
. At first, the idea of a machine changing the code that I wrote
for my project didn’t sound very exciting to me. But working in a team
environment and being able to configure the formatter based on what best
practices a project follows, made it all worth it. Moreover, the ability to
run it (mix format --check-formatted
or cargo fmt --check
) as part of the
CI to see if any new code is formatted, was a great added bonus.
I like to add my formatter commits separately since I like to run analytics on
my code and like keeping my formatted commits separate. I found myself
following a “format” for the commit message for the formatter updates, which
always looked like: Format code (mix format)
. So, I wondered why not add a
post-commit
git hook that does that for me. So, below is the post-commit
hook that I use in my elixir and rust projects (rust uses cargo fmt
instead of
mix format
) to format the files that I changed in the previous commit in a
new commit message:
For Elixir
#!/bin/sh
mix format $(git diff-tree --no-commit-id --name-only -r HEAD)
if ! git diff-index --quiet HEAD --;then
git add $(git diff-tree --no-commit-id --name-only -r HEAD)
exec git commit -m"Format code (\`mix format\`)"
fi
For Rust
#!/bin/sh
cargo fmt $(git diff-tree --no-commit-id --name-only -r HEAD)
if ! git diff-index --quiet HEAD --;then
git add $(git diff-tree --no-commit-id --name-only -r HEAD)
exec git commit -m"Format code (\`cargo fmt\`)"
fi
Feel free to use them and improve on them. Happy Coding!