Skip to content

Backend Pre-commit Hooks

As part of our attempt to keep up code quality, we've setup ruff as a formatter and linter for our python code.

This run as part of our Github actions CI and should be running in our IDEs. However we want to make sure we're catching any issues before committing code to our git repository

We also want to catch any other errors such as committing to the main branch.

Creating the script

From inside out backend repo, let's start by opening the pre-commit file

bash
code .git/hooks/pre-commit

Enter the following script and save it.

bash
#!/usr/bin/env bash

source $(git rev-parse --show-toplevel)/.venv/bin/activate

# If any command fails, exit immediately with that command's exit status
set -eo pipefail


branch="$(git rev-parse --abbrev-ref HEAD)"

if [ "$branch" = "master" ] || [ "$branch" = "main" ]; then
  echo "You can't commit directly to master/main branch"
  exit 1
fi


CHANGED_FILES=$(git diff --name-only --cached --diff-filter=ACMR)
get_pattern_files() {
    pattern=$(echo "$*" | sed "s/ /\$\\\|/g")
    echo "$CHANGED_FILES" | { grep "$pattern$"  | grep -v migrations || true; }
}
PY_FILES=$(get_pattern_files .py)

if [[ -n "$PY_FILES" ]]
then
    which ruff
    ruff version
	
    ruff check --ignore F401  $PY_FILES
    ruff format --check $PY_FILES
fi

Last let's make it executable

bash
chmod +x .git/hooks/pre-commit

Now if you attempt to commit to main, or commit python files with errors, you should get a message preventing the commit.