Hook

Hook that formats code after each edit

Every time Claude edits or creates a file, the hook runs the formatter that fits its extension (Prettier, Ruff, gofmt), so code stays formatted without asking in the prompt.

Tested with Claude Code 2.1.329

.claude/hooks/format-file.sh
#!/bin/bash
# Formats the file Claude just wrote. Reads the hook input (JSON) on stdin.
file=$(jq -r '.tool_input.file_path // empty')
[ -z "$file" ] || [ ! -f "$file" ] && exit 0

run() { command -v "$1" >/dev/null 2>&1 && "$@" >/dev/null 2>&1; }

case "$file" in
  *.ts|*.tsx|*.js|*.jsx|*.json|*.css|*.md) run npx --no-install prettier --write "$file" ;;
  *.py) run ruff format "$file" ;;
  *.go) run gofmt -w "$file" ;;
  *.swift) run swift-format --in-place "$file" ;;
esac
exit 0  # never block: a formatting problem must not stop Claude's work
.claude/settings.json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-file.sh"
          }
        ]
      }
    ]
  }
}

Notes

  • Needs jq and the formatters you use. Extensions whose formatter is missing are skipped.
  • Run `chmod +x .claude/hooks/format-file.sh` once.
  • If `.claude/settings.json` already has a `hooks` key, merge the `PostToolUse` entry instead of replacing the file.

Related lessons

Type to search the reference, templates and lessons.