Automatically format code after every file edit using hooks
This cookbook shows how to automatically format code after Droid edits files, ensuring consistent code style across your project without manual intervention.
For projects with multiple languages, use a script to handle different file types.Create .factory/hooks/format.sh:
Copy
Ask AI
#!/bin/bashset -e# Read the hook inputinput=$(cat)file_path=$(echo "$input" | jq -r '.tool_input.file_path')# Skip if file doesn't existif [ ! -f "$file_path" ]; then exit 0fi# Determine formatter based on file extensioncase "$file_path" in *.ts|*.tsx|*.js|*.jsx|*.json|*.css|*.scss|*.md|*.mdx) if command -v prettier &> /dev/null; then prettier --write "$file_path" 2>&1 echo "✓ Formatted with Prettier: $file_path" fi ;; *.py) if command -v black &> /dev/null; then black "$file_path" 2>&1 echo "✓ Formatted with Black: $file_path" fi if command -v isort &> /dev/null; then isort "$file_path" 2>&1 echo "✓ Sorted imports with isort: $file_path" fi ;; *.go) if command -v gofmt &> /dev/null; then gofmt -w "$file_path" 2>&1 echo "✓ Formatted with gofmt: $file_path" fi ;; *.rs) if command -v rustfmt &> /dev/null; then rustfmt "$file_path" 2>&1 echo "✓ Formatted with rustfmt: $file_path" fi ;; *.java) if command -v google-java-format &> /dev/null; then google-java-format -i "$file_path" 2>&1 echo "✓ Formatted with google-java-format: $file_path" fi ;; *) # No formatter for this file type exit 0 ;;esacexit 0
Combine formatting with linting fixes.Create .factory/hooks/format-and-lint.sh:
Copy
Ask AI
#!/bin/bashset -einput=$(cat)file_path=$(echo "$input" | jq -r '.tool_input.file_path')if [ ! -f "$file_path" ]; then exit 0ficase "$file_path" in *.ts|*.tsx|*.js|*.jsx) # Format with prettier if command -v prettier &> /dev/null; then prettier --write "$file_path" 2>&1 echo "✓ Formatted: $file_path" fi # Fix lint issues if command -v eslint &> /dev/null; then eslint --fix "$file_path" 2>&1 || true echo "✓ Linted: $file_path" fi ;; *.py) # Format with black if command -v black &> /dev/null; then black "$file_path" 2>&1 echo "✓ Formatted with Black: $file_path" fi # Sort imports if command -v isort &> /dev/null; then isort "$file_path" 2>&1 echo "✓ Sorted imports: $file_path" fi # Run flake8 for style issues if command -v flake8 &> /dev/null; then flake8 "$file_path" 2>&1 || true echo "✓ Checked with flake8: $file_path" fi ;;esacexit 0