Skip to main content
This cookbook shows how to automatically format code after Droid edits files, ensuring consistent code style across your project without manual intervention.

How it works

The hook:
  1. Triggers on file edits: Runs after Write or Edit tool calls
  2. Detects file type: Checks file extension to determine formatter
  3. Runs appropriate formatter: Executes prettier, black, gofmt, rustfmt, etc.
  4. Provides feedback: Reports formatting results to the user
  5. Handles errors gracefully: Continues even if formatting fails

Prerequisites

Install formatters for your language stack:

Basic setup

Single language project

For a JavaScript/TypeScript project, add this to your .factory/hooks.json:

Multi-language project

For projects with multiple languages, use a script to handle different file types. Create .factory/hooks/format.sh:
Make the script executable:
Add to .factory/hooks.json:

Advanced configurations

Format with custom config

Use project-specific prettier config:

Format with linting

Combine formatting with linting fixes. Create .factory/hooks/format-and-lint.sh:
Make the script executable:
Add to .factory/hooks.json:

Conditional formatting

Only format files in specific directories. Create .factory/hooks/format-src-only.sh:
Make the script executable:
Add to .factory/hooks.json:

Real-world examples

Example 1: React component formatting

Example 2: Python import sorting

Best practices

Formatters can sometimes introduce subtle bugs (e.g., changing string formats, line continuations). Always review changes before committing.
1

Start with read-only mode

Test your formatter configuration manually first:
2

Use consistent config files

Ensure formatter configs are committed:
3

Set appropriate timeouts

Large files may need more time:
4

Handle formatter errors gracefully

Don’t block Droid if formatting fails:
5

Consider Git hooks integration

Combine with pre-commit hooks for consistency:

Troubleshooting

Formatter not found

Problem: command not found error Solution: Install the formatter globally or use npx/project binaries:

Formatting breaks code

Problem: Formatter introduces syntax errors Solution: Add file validation after formatting:

Hook runs too slowly

Problem: Formatting takes too long Solution: Only format changed files, use faster formatters:

Conflicts with editor formatting

Problem: Editor and hook format differently Solution: Use the same config for both:

See also