Shell
#!/bin/bash
# PostToolUse Formatter Hook
# Automatically formats code after Write/Edit operations
# Inspired by Boris Cherny's Claude Code workflow
# Get the file path from the tool output
# For Write/Edit tools, the file path is passed as first argument
FILE_PATH="$1"
# Exit if no file path or file doesn't exist
[[ -z "$FILE_PATH" ]] && exit 0
[[ ! -f "$FILE_PATH" ]] && exit 0
# Get file extension
EXT="${FILE_PATH##*.}"
# Define formattable extensions
FORMATTABLE_EXTS="ts tsx js jsx json css scss md html vue svelte"
# Check if this extension should be formatted
should_format() {
for ext in $FORMATTABLE_EXTS; do
[[ "$EXT" == "$ext" ]] && return 0
done
return 1
}
# Exit if not a formattable file
should_format || exit 0
# Find project root (look for package.json or .git)
find_project_root() {
local dir="$(dirname "$FILE_PATH")"
while [[ "$dir" != "/" ]]; do
[[ -f "$dir/package.json" ]] && echo "$dir" && return
[[ -d "$dir/.git" ]] && echo "$dir" && return
dir="$(dirname "$dir")"
done
echo ""
}
PROJECT_ROOT=$(find_project_root)
# If no project root found, skip formatting
[[ -z "$PROJECT_ROOT" ]] && exit 0
cd "$PROJECT_ROOT"
# Try formatters in order of preference
# 1. Biome (fastest)
if [[ -f "biome.json" ]] || [[ -f "biome.jsonc" ]]; then
npx biome format --write "$FILE_PATH" 2>/dev/null
exit 0
fi
# 2. Prettier (most common)
if [[ -f ".prettierrc" ]] || [[ -f ".prettierrc.json" ]] || [[ -f "prettier.config.js" ]] || [[ -f ".prettierrc.js" ]]; then
npx prettier --write "$FILE_PATH" 2>/dev/null
exit 0
fi
# 3. Check package.json for prettier
if grep -q '"prettier"' package.json 2>/dev/null; then
npx prettier --write "$FILE_PATH" 2>/dev/null
exit 0
fi
# 4. ESLint with --fix for JS/TS files (if no prettier)
if [[ "$EXT" =~ ^(ts|tsx|js|jsx)$ ]]; then
if [[ -f ".eslintrc" ]] || [[ -f ".eslintrc.json" ]] || [[ -f ".eslintrc.js" ]] || [[ -f "eslint.config.js" ]]; then
npx eslint --fix "$FILE_PATH" 2>/dev/null
exit 0
fi
fi
# No formatter found - that's okay, just exit cleanly
exit 0