From 47dd1fdcfd43e0b14d1e6b7a1a07578193be3131 Mon Sep 17 00:00:00 2001 From: cezmunsta Date: Wed, 25 Sep 2024 10:27:11 +0100 Subject: [PATCH] Added support for Ruff --- helpers/python/functions.bash | 62 +++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/helpers/python/functions.bash b/helpers/python/functions.bash index ba25c4f..897e7cd 100644 --- a/helpers/python/functions.bash +++ b/helpers/python/functions.bash @@ -14,16 +14,22 @@ function python_bypass_enabled { } function check_python { - local pylint= - pylint="$(command -v pylint 2>&1)" - if test -x "${pylint}"; then - python_bypass_enabled || check_python_files "${pylint}" + local linter= + + case "${GIT_PYTHON_LINTER:-ruff}" in + pylint|ruff) linter="$(command -v "${GIT_PYTHON_LINTER}" 2>&1)" ;; + *) echo "Unsupported linter: ${GIT_PYTHON_LINTER}"; exit 2 + esac + + if test -x "$(which "${linter}")"; then + python_bypass_enabled || check_python_files_"$(basename "${linter}")" "${linter}" else - printf "** WARNING ** Unable to execute pylint: %s\n" "${pylint}" + printf "** WARNING ** Unable to execute linter: %s\n" "${linter}" fi + } -function check_python_files { +function check_python_files_pylint { local -i lint_issues=0 local -a errors=() @@ -67,3 +73,47 @@ function check_python_files { printf " OK\n\n" fi } + +function check_python_files_ruff { + local -i lint_issues=0 + local -a errors=() + + # shellcheck disable=SC2155 + local py_version="$(env python --version)" + local ruff="${1}" + local ruffrc="${HOOKS_DIR}/etc/python/.ruff.toml" + local rufflog="lint.log" + local ruffargs="" + + if [[ "${GIT_PYTHON_LINT_CONFIG:-undefined}" != "undefined" ]] && [[ -f "${GIT_PYTHON_LINT_CONFIG}" ]]; then + ruffrc="${GIT_PYTHON_LINT_CONFIG}" + fi + + printf "\nPython version: %s" "${py_version}" + printf "\nValidating Python with %s check --config=%s %s:\n\n" \ + "${ruff}" "${ruffrc}" "${ruffargs}" + + for file in $(get_python_files); do + if [[ "${file:(-2)}" != "py" ]]; then + printf " - ignoring file: %s\n" "${file}" + continue + fi + + ("${ruff}" check --config="${ruffrc}" ${ruffargs} "${file}" >"${rufflog}" 2>&1) + + if test $? -ne 0 ; then + errors[${lint_issues}]="$(printf " - fix lint issues: %s\n\n%s\n" "${file}" "$(grep -E '^[RCWEF]:' "${rufflog}" | sed 's/^/ /g')")" + lint_issues=$((lint_issues + 1)) + fi + done + + if test ${lint_issues} -gt 0; then + for error in "${errors[@]}"; do + printf "%s\n" "${error}" + done + printf "\nPlease fix lint issues before committing\n\n" + exit 2 + else + printf " OK\n\n" + fi +}