Last active
May 20, 2026 22:54
-
-
Save wagenet/d391419f009fbb61a190b6d129329fd1 to your computer and use it in GitHub Desktop.
Claude post-edit format hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "hooks": { | |
| "PostToolUse": [ | |
| { | |
| "matcher": "Edit|Write", | |
| "hooks": [ | |
| { | |
| "type": "command", | |
| "command": "~/.claude/hooks/format.sh", | |
| "timeout": 30 | |
| } | |
| ] | |
| } | |
| ], | |
| }, | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # PostToolUse hook: run prettier and/or oxfmt on edited files. | |
| # Each formatter runs independently based on its config being present. | |
| # Reports back to Claude only if the file was changed. | |
| export PATH="$HOME/.volta/bin:$PATH" | |
| FILE=$(jq -r '.tool_input.file_path // empty') | |
| [ -z "$FILE" ] && exit 0 | |
| [ -f "$FILE" ] || exit 0 | |
| find_package_root() { | |
| local dir | |
| dir=$(cd "$(dirname "$FILE")" && pwd) | |
| while [ "$dir" != "/" ]; do | |
| [ -f "$dir/package.json" ] && echo "$dir" && return 0 | |
| dir=$(dirname "$dir") | |
| done | |
| return 1 | |
| } | |
| ROOT=$(find_package_root) || exit 0 | |
| has_prettier_config() { | |
| for f in .prettierrc .prettierrc.json .prettierrc.yml .prettierrc.yaml .prettierrc.json5 \ | |
| .prettierrc.js .prettierrc.mjs .prettierrc.cjs \ | |
| prettier.config.js prettier.config.mjs prettier.config.cjs .prettierrc.toml; do | |
| [ -f "$ROOT/$f" ] && return 0 | |
| done | |
| jq -e '.prettier' "$ROOT/package.json" >/dev/null 2>&1 | |
| } | |
| BEFORE=$(shasum -a 256 "$FILE" 2>/dev/null) | |
| if [ -f "$ROOT/oxfmtrc.jsonc" ] || [ -f "$ROOT/oxfmt.config.ts" ]; then | |
| NODE_MAJOR=$(node --version 2>/dev/null | sed 's/v\([0-9]*\).*/\1/') | |
| [ "$NODE_MAJOR" = "20" ] && OXFMT_NODE_OPTIONS="--import @oxc-node/core/register" | |
| cd "$ROOT" && NODE_OPTIONS="$OXFMT_NODE_OPTIONS" pnpm exec oxfmt --write "$FILE" >/dev/null 2>&1 || true | |
| fi | |
| if has_prettier_config; then | |
| cd "$ROOT" && pnpm exec prettier --write "$FILE" >/dev/null 2>&1 || true | |
| fi | |
| AFTER=$(shasum -a 256 "$FILE" 2>/dev/null) | |
| if [ "$BEFORE" != "$AFTER" ]; then | |
| jq -n --arg f "$FILE" \ | |
| '{"hookSpecificOutput":{"hookEventName":"PostToolUse","additionalContext":"Formatter changed \($f) — re-read the file before continuing."}}' | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment