Skip to content

Instantly share code, notes, and snippets.

@madole
Last active April 14, 2025 00:12
Show Gist options
  • Save madole/d00005e683ed7f6ba55a6f71a4c46f80 to your computer and use it in GitHub Desktop.
Save madole/d00005e683ed7f6ba55a6f71a4c46f80 to your computer and use it in GitHub Desktop.
Prettier pre-commit hook
#!/bin/sh
#
# This is a git hook script to run Prettier before committing.
# It will reformat your code according to your Prettier configuration.
#
# To install this hook:
# 1. Make sure you have Prettier installed in your project: `npm install --save-dev prettier`
# 2. Make sure you have a Prettier configuration file (e.g., .prettierrc.js, .prettierrc.json, etc.)
# 3. Create a file named "pre-commit" (without any extension) in the .git/hooks directory of your repository.
# 4. Make the "pre-commit" file executable: `chmod +x .git/hooks/pre-commit`
#
# This script will automatically format your staged files before you commit them.
# If Prettier fails, the commit will be aborted, and you'll need to fix the formatting issues.
# Get the list of staged files
staged_files=$(git diff --cached --name-only)
# If there are no staged files, exit successfully.
if [ -z "$staged_files" ]; then
echo "No staged files to format."
exit 0
fi
# Function to check if a file is a candidate for prettier.
is_formattable() {
case "$1" in
*.js|*.jsx|*.ts|*.tsx|*.mjs|*.cjs|*.html|*.vue|*.svelte|*.css|*.scss|*.less)
return 0 # File is formattable
;;
*)
return 1 # File is not formattable
;;
esac
}
# Array to store files that Prettier can format
prettier_files=()
# Loop through the staged files and add the formattable ones to the array
while IFS= read -r file; do
if is_formattable "$file"; then
prettier_files+=("$file")
fi
done <<< "$staged_files"
# If there are no files for prettier, exit.
if [ ${#prettier_files[@]} -eq 0 ]; then
echo "No formattable files to process."
exit 0
fi
# Log that prettier is about to run.
echo "Running prettier on staged files..."
# Format the staged files using Prettier. Use --write to modify the files in place.
# Pass the files directly to Prettier. This handles spaces and special characters correctly.
npx prettier --write "${prettier_files[@]}"
# Check the exit code of Prettier.
if [ $? -ne 0 ]; then
echo "Prettier failed. Please fix the formatting issues and try committing again."
exit 1
fi
# Add the formatted files back to the staging area. This is crucial!
echo "Adding formatted files to staging area..."
git add "${prettier_files[@]}"
echo "Prettier formatting complete."
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment