feat: add Prettier formatting hook for file edits

This commit is contained in:
yaoweiprc
2026-07-09 08:59:24 +08:00
parent a81ac68c39
commit 500bb9f44f
2 changed files with 50 additions and 0 deletions

View File

@@ -0,0 +1,36 @@
#!/usr/bin/env node
// PostToolUse hook (Write|Edit): formats the touched file with the repo's local Prettier.
const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
let raw = '';
try {
raw = fs.readFileSync(0, 'utf8');
} catch {
process.exit(0);
}
let input;
try {
input = JSON.parse(raw);
} catch {
process.exit(0);
}
const filePath = input.tool_response?.filePath || input.tool_input?.file_path;
if (!filePath || !fs.existsSync(filePath)) {
process.exit(0);
}
const repoRoot = path.join(__dirname, '..', '..');
const prettierCli = path.join(repoRoot, 'node_modules', 'prettier', 'bin', 'prettier.cjs');
try {
execFileSync(process.execPath, [prettierCli, '--ignore-unknown', '--write', filePath], {
cwd: repoRoot,
stdio: 'ignore',
});
} catch {
// Ignore formatting failures (e.g. syntax errors) so the hook never blocks the agent.
}

View File

@@ -5,5 +5,19 @@
"Edit(packages/insomnia/bin/yarn-standalone.js)",
"Write(packages/insomnia/bin/yarn-standalone.js)"
]
},
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "node .claude/hooks/prettier-format.js",
"timeout": 30
}
]
}
]
}
}