diff --git a/git/hooks/pre-commit b/git/hooks/pre-commit index d51b82f..e927870 100755 --- a/git/hooks/pre-commit +++ b/git/hooks/pre-commit @@ -1,17 +1,13 @@ #!/bin/sh -# Pre-commit hook to check for trailing whitespace and missing newline at EOF - -# Exit on first error -set -e +# Pre-commit hook that automatically fixes trailing whitespace and missing newline at EOF +# This hook only fixes issues and never blocks commits # Color codes for output -RED='\033[0;31m' GREEN='\033[0;32m' +YELLOW='\033[0;33m' NC='\033[0m' # No Color -errors_found=0 - # Get list of staged files staged_files=$(git diff --cached --name-only --diff-filter=ACM) @@ -19,47 +15,44 @@ if [ -z "$staged_files" ]; then exit 0 fi -# Check for trailing whitespace -echo "Checking for trailing whitespace..." -for file in $staged_files; do - if [ -f "$file" ]; then - # Check if file has trailing whitespace - if grep -q '[[:space:]]$' "$file"; then - echo "${RED}✗${NC} Trailing whitespace found in: $file" - # Show lines with trailing whitespace - grep -n '[[:space:]]$' "$file" | while IFS=: read -r line_num line_content; do - echo " Line $line_num: '${line_content}'" - done - errors_found=1 - fi - fi -done +files_fixed=0 -# Check for missing newline at end of file -echo "Checking for newline at end of files..." +# Process each staged file for file in $staged_files; do if [ -f "$file" ]; then - # Check if file ends with a newline - if [ -n "$(tail -c 1 "$file")" ]; then - echo "${RED}✗${NC} Missing newline at end of file: $file" - errors_found=1 + # Skip binary files + if file -b --mime "$file" 2>/dev/null | grep -q "text"; then + file_modified=0 + + # Remove trailing whitespace + if grep -q '[[:space:]]$' "$file" 2>/dev/null; then + echo "${YELLOW}→${NC} Removing trailing whitespace from: $file" + sed -i 's/[[:space:]]*$//' "$file" 2>/dev/null || true + file_modified=1 + fi + + # Add newline at end of file if missing + if [ -n "$(tail -c 1 "$file" 2>/dev/null)" ]; then + echo "${YELLOW}→${NC} Adding newline at end of: $file" + echo >> "$file" 2>/dev/null || true + file_modified=1 + fi + + # Re-stage the file if it was modified + if [ $file_modified -eq 1 ]; then + git add "$file" 2>/dev/null || true + files_fixed=$((files_fixed + 1)) + fi fi fi done # Report results -if [ $errors_found -eq 0 ]; then - echo "${GREEN}✓${NC} All checks passed!" - exit 0 +if [ $files_fixed -gt 0 ]; then + echo "${GREEN}✓${NC} Fixed $files_fixed file(s) - changes have been staged" else - echo "" - echo "${RED}Pre-commit checks failed!${NC}" - echo "Please fix the issues above and try again." - echo "" - echo "To fix trailing whitespace, you can use:" - echo " sed -i 's/[[:space:]]*$//' " - echo "" - echo "To add missing newline at EOF, you can use:" - echo " echo >> " - exit 1 + echo "${GREEN}✓${NC} No fixes needed - all files are clean" fi + +# Always exit successfully to never block commits +exit 0