c++rustgithookspre-commit-hookrustfmt

How can I auto-format Rust (and C++) code on commit automatically?


I would like to automatically format the code when I do commit using rustfmt the same way as I did it before for clang-format -i. I.e. format only the lines of code which has been updated in the commit without touching other code. How to do it?


Solution

  • It might be done using git pre-commit hook in the following way:

    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
                # check file extension
                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
    

    To make it work for clang-format you need to replace rustfmt with clang-format -i and do corresponding modifications in the check for file extension (cpp\h\hpp\etc).