Skip to content

Instantly share code, notes, and snippets.

@Njengah
Last active July 10, 2025 14:42
Show Gist options
  • Save Njengah/ae3efe6aa2cff1110646e6f8d8d9e3aa to your computer and use it in GitHub Desktop.
Save Njengah/ae3efe6aa2cff1110646e6f8d8d9e3aa to your computer and use it in GitHub Desktop.
Claude Code Hooks Examples
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "~/scripts/doc-generator.sh"
}
]
}
]
}
}
#!/bin/bash
# Read JSON input
input=$(cat)
file_path=$(echo "$input" | jq -r '.tool_input.file_path // empty')
tool_name=$(echo "$input" | jq -r '.tool_name // empty')
# Only process API files
if [[ "$file_path" =~ \.(py|js|ts)$ ]] && [[ "$file_path" =~ (api|service|controller) ]]; then
# Generate documentation
doc_file="${file_path%.*}.md"
echo "Generating documentation for $file_path..."
# Use a documentation tool (example with a Python script)
if [[ "$file_path" =~ \.py$ ]]; then
python3 ~/scripts/py-to-docs.py "$file_path" > "$doc_file"
elif [[ "$file_path" =~ \.(js|ts)$ ]]; then
npx jsdoc2md "$file_path" > "$doc_file"
fi
# Return success with feedback
cat << EOF
{
"suppressOutput": false,
"continue": true
}
EOF
echo "Documentation generated: $doc_file" >&2
fi
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "command",
"command": "python3 ~/scripts/eslint-validator.py"
}
]
}
]
}
}
#!/usr/bin/env python3
import json
import sys
import subprocess
import os
def main():
try:
# Read hook input
input_data = json.load(sys.stdin)
tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})
file_path = tool_input.get("file_path", "")
# Only process JavaScript/TypeScript files
if not file_path.endswith(('.js', '.jsx', '.ts', '.tsx')):
sys.exit(0) # Success, but do nothing
# Check if file exists and run ESLint
if os.path.exists(file_path):
result = subprocess.run(
['npx', 'eslint', file_path, '--format', 'json'],
capture_output=True,
text=True
)
if result.returncode != 0:
# Parse ESLint output
try:
lint_results = json.loads(result.stdout)
if lint_results and lint_results[0].get('messages'):
errors = [msg for msg in lint_results[0]['messages']
if msg['severity'] == 2]
if errors:
error_summary = f"ESLint found {len(errors)} error(s) in {file_path}:\n"
for error in errors[:3]: # Show first 3 errors
error_summary += f" Line {error['line']}: {error['message']}\n"
print(error_summary, file=sys.stderr)
sys.exit(2) # Block the operation
except json.JSONDecodeError:
pass
sys.exit(0) # Success
except Exception as e:
print(f"Hook error: {e}", file=sys.stderr)
sys.exit(1) # Non-blocking error
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment