From f3a26e1675b64927002fd342228e64de8d43e0fa Mon Sep 17 00:00:00 2001 From: Tate Date: Thu, 19 Sep 2024 07:30:39 -0600 Subject: [PATCH] Add rust lint and format hooks (#4) --- .pre-commit-hooks.yaml | 17 +++++++++++++++++ pre-commit-hooks/rust-fmt.sh | 23 +++++++++++++++++++++++ pre-commit-hooks/rust-lint.sh | 26 ++++++++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100755 pre-commit-hooks/rust-fmt.sh create mode 100755 pre-commit-hooks/rust-lint.sh diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 7a55b58..afb849f 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -1,3 +1,4 @@ +# golang - id: go-lint name: lint golang files description: ensures golang code meets the configured lint criteria. @@ -12,6 +13,22 @@ language: script stages: [pre-push, manual] pass_filenames: false +# rust +- id: rust-lint + name: lint rust files + description: ensures rust code meets the configured lint criteria. + entry: pre-commit-hooks/rust-lint.sh + language: script + pass_filenames: false + stages: [pre-commit, pre-push, manual] +- id: rust-fmt + name: format rust files + description: ensures rust code is formatted as the project expects. + entry: pre-commit-hooks/rust-fmt.sh + language: script + pass_filenames: false + stages: [pre-commit, pre-push, manual] +# typos - id: detect-typos name: Check for typos description: Check the code for any typos diff --git a/pre-commit-hooks/rust-fmt.sh b/pre-commit-hooks/rust-fmt.sh new file mode 100755 index 0000000..a848185 --- /dev/null +++ b/pre-commit-hooks/rust-fmt.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +# Exit immediately if a command exits with a non-zero status +set -e + +# Function to format rust code +run_cargo_fmt() { + echo "Executing 'cargo fmt'" + cargo fmt +} + +run_cargo_fmt + +# Utilize pre-commit's stash functionality to get a diff +output=$(git diff --stat) + +if [ -z "$output" ]; then + echo "No changes in any files." +else + echo "files that weren't formatted:" + echo "$output" | awk -F '|' '/\|/ { print $1 }' + exit 1 +fi diff --git a/pre-commit-hooks/rust-lint.sh b/pre-commit-hooks/rust-lint.sh new file mode 100755 index 0000000..e0b9340 --- /dev/null +++ b/pre-commit-hooks/rust-lint.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash + +# Exit immediately if a command exits with a non-zero status. +set -e + +# Function to run linters on the rust project +run_linter() { + echo "Executing clippy" + + # Run the linter and capture the exit status + set +e + cargo clippy -- -D warnings + local linting_result=$? + set -e + + # Check the linter result and provide feedback + if [[ $linting_result -ne 0 ]]; then + echo -e "\e[31mNOK!\e[0m" + echo "Run 'cargo clippy -- -D warnings' and fix the issues" + exit 1 + else + echo -e "\e[32mOK!\e[0m" + fi +} + +run_linter