Skip to content

Instantly share code, notes, and snippets.

@KirillLykov
Last active February 22, 2022 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KirillLykov/80c63d29df601c0fc25a6475d4b84b98 to your computer and use it in GitHub Desktop.
Save KirillLykov/80c63d29df601c0fc25a6475d4b84b98 to your computer and use it in GitHub Desktop.
How to set up pre-commit hook

It works for rust and for C++. The difference is that for rust you need to specify rustfmt and for C++ clang-format -i.

  1. Add file pre-commit to the folder .githooks in your repo with the following text:
#!/bin/bash

exe=$(which rustfmt)

if [ -n "$exe" ]
then
    # field separator to the new line
    IFS=$'\n'

    for line in $(git status -s)
    do
        # if added or modified
        if [[ $line == A* || $line == M* ]]
        then
            if [[ $line == *.rs ]]
            then
                # format file
                rustfmt $(pwd)/${line:3}
                # add changes
                git add $(pwd)/${line:3}
            fi
        fi
    done

else
    echo "rustfmt was not found"
fi
  1. Run in your repo folder:
chmod +x .githooks/pre-commit
git config core.hooksPath .githooks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment