2

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?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
Kirill Lykov
  • 1,293
  • 2
  • 22
  • 39

1 Answers1

4

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).

Kirill Lykov
  • 1,293
  • 2
  • 22
  • 39
  • the only question missing is if it is possible to do both rustfmt and clippy – Kirill Lykov Feb 22 '22 at 18:27
  • I am wonder what is the value of using folder `.githooks` instead of the standard folder with hooks `.git/hooks`. Putting the above script into `.git/hooks/pre-commit` and fixing permissions works well. – k_rus Dec 12 '22 at 11:13
  • I think no value, just another way of doing the same – Kirill Lykov Dec 13 '22 at 14:56