From 9fa2fde3e5771a96a26c003ff947067ba918465f Mon Sep 17 00:00:00 2001 From: Klaas van Schelven Date: Tue, 29 Jul 2025 12:27:21 +0200 Subject: [PATCH] pre-commit: fail on trailing whitespace --- pre-commit | 16 ++++++++++++++++ tools/strip-trailing-whitespace.sh | 30 ++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100755 tools/strip-trailing-whitespace.sh diff --git a/pre-commit b/pre-commit index 28d3f83..af7b5d4 100755 --- a/pre-commit +++ b/pre-commit @@ -14,3 +14,19 @@ if [ "$should_run" = "yes" ]; then else echo "No relevant changes; skipping Tailwind build." fi + +# Check for trailing whitespace in staged files, fail if found + +git diff --cached --name-only --diff-filter=ACM | while IFS= read -r file; do + [ -f "$file" ] || continue + + case "$file" in + *.py|*.js|*.ts|*.sh|*.md|*.txt|*.html|*.css) + if grep -qE '[[:space:]]+$' "$file"; then + echo "Commit aborted due to trailing whitespace." + echo "Fix it manually or use tools/strip-trailing-whitespace.sh" + exit 1 + fi + ;; + esac +done diff --git a/tools/strip-trailing-whitespace.sh b/tools/strip-trailing-whitespace.sh new file mode 100755 index 0000000..c2a68d8 --- /dev/null +++ b/tools/strip-trailing-whitespace.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# +# Strip trailing whitespace from tracked files with specific extensions. +# Usage: ./tools/strip-trailing-whitespace.sh +# Works on macOS (BSD sed) or Linux (GNU sed), but not both at once. + +set -euo pipefail + +# Extensions to include +EXT_REGEX='\.(py|js|ts|sh|md|txt|html|css)$' + +# Detect sed flavor +if sed --version >/dev/null 2>&1; then + SED_CMD=(sed -i -e 's/[[:space:]]\+$//') +elif sed -i '' testfile 2>/dev/null; then + SED_CMD=(sed -i '' -e 's/[[:space:]]\+$//') +else + echo "Unsupported sed version. Must be GNU sed or BSD sed (macOS)." >&2 + exit 1 +fi + +git ls-files -z | while IFS= read -r -d '' file; do + [[ -f "$file" ]] || continue + [[ "$file" =~ $EXT_REGEX ]] || continue + + if grep -qE '[[:space:]]+$' "$file"; then + echo "Fixing: $file" + "${SED_CMD[@]}" "$file" + fi +done