Skip to content

Yapf formatting hook

JD edited this page Aug 6, 2020 · 1 revision

Create the file <repo root>/.git/hooks/pre-commit with the following contents:

#!/bin/sh
#
# This pre-commit hook checks if any versions of yapf
# are installed, and if so, uses the installed version to format
# the staged changes.

base=yapf
format=""

# Redirect output to stderr.
exec 1>&2
# check if yapf is installed
type "$base" >/dev/null 2>&1 && format="$base"

# no versions of clang-format are installed
if [ -z "$format" ]
then
    echo "$base is not installed. Pre-commit hook will not be executed."
    exit 0
fi

# Do everything from top - level
cd $(git rev-parse --show-toplevel)

if git rev-parse --verify HEAD >/dev/null 2>&1
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=e63c4a4eba0bf74ff0081d8bf11ee30cbb91ebac
fi

# do the formatting
for file in $(git diff-index --cached --name-only $against | grep -E '\.py$')
do
    if [ -e "$file" ]
    then
        echo "$format $file"
        "$format" -i "--style={based_on_style: google, indent_width: 2}" "$file"
    fi
done

Ensure it has execute privileges by executing

chmod +x pre-commit

Now when you commit code the commit hook installed above would run yapf on the new code updating your tree.

(myvenv) jehandad@jehandad-MS-7B09:~/Tuna$ git add -u
(myvenv) jehandad@jehandad-MS-7B09:~/Tuna$ git commit -m 'test'
yapf tuna/MachineManagementInterface.py
[ipmi 179aa27] test
 1 file changed, 1 deletion(-)

You can check the changed files by running git status:

(myvenv) jehandad@jehandad-MS-7B09:~/Tuna$ git status
On branch ipmi
Your branch is ahead of 'origin/ipmi' by 1 commit.
  (use "git push" to publish your local commits)
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   tuna/MachineManagementInterface.py

The violating file has been edited to conform to yapf.

We can update our commit to bring the file back to conformance:

(myvenv) jehandad@jehandad-MS-7B09:~/Tuna$ git add -u
(myvenv) jehandad@jehandad-MS-7B09:~/Tuna$ git commit --amend
yapf tuna/MachineManagementInterface.py
[ipmi 9787946] fix formatting
1 file changed, 5 insertions(+), 3 deletions(-)

Note that we did not push after the first commit and ammended the unformatted commit with the formatted code

Now we can push our code knowing that it would pass the formatting on Jenkins

git push
Clone this wiki locally