导入
Hooks 和高级工作流自动化
学习如何使用 Claude Code 的钩子来拦截工具操作、实施防护措施,并自动化自定义工作流。
...
Claude Code 中的 Hooks 菜单
1{ 2 "hooks": { 3 "EventName": [ 4 { 5 "matcher": "ToolPattern", 6 "hooks": [ 7 { 8 "type": "command", 9 "command": "your-command-here" 10 } 11 ] 12 } 13 ] 14 } 15}
1{ 2 "hooks": { 3 "PreToolUse": [ 4 { 5 "matcher": "Read", 6 "hooks": [ 7 { 8 "type": "command", 9 "command": "python3 /home/hooks/check_read.py" 10 } 11 ] 12 } 13 ] 14 } 15}
PreToolUse 钩子
1{ 2 "hook_event_name": "PreToolUse", 3 "tool_name": "Read", 4 "tool_input": { 5 "file_path": "/project/secrets/api_keys.json" 6 } 7}
Terminal
1import sys 2import json 3 4# 从 stdin 读取 JSON 输入 5data = json.load(sys.stdin) 6 7# 从工具输入中提取文件路径 8file_path = data.get("tool_input", {}).get("file_path", "") 9 10# 如果路径包含 "/secrets/",则阻止访问 11if "/secrets/" in file_path: 12 sys.stderr.write("Error: 不允许访问密钥文件。\n") 13 sys.exit(2) # 阻止工具执行 14else: 15 sys.exit(0) # 允许执行
1{ 2 "hooks": { 3 "PreToolUse": [ 4 { 5 "matcher": "Read", 6 "hooks": [ 7 { 8 "type": "command", 9 "command": "python3 ~/.claude/hooks/block_secrets.py" 10 } 11 ] 12 } 13 ] 14 } 15}
1#!/usr/bin/env bash 2 3# 从 stdin 读取 JSON 输入 4read_json=$(cat) 5 6# 从 JSON 中提取文件路径 7file_path=$(printf "%s" "$read_json" | jq -r ".tool_input.file_path") 8 9# 根据文件扩展名决定操作 10case "$file_path" in 11 *.js|*.ts) 12 echo "使用 Prettier 自动格式化 $file_path..." 1>&2 13 npx prettier --write "$file_path" 14 ;; 15 *) 16 # 对其他文件类型不执行任何操作 17 ;; 18esac
1{ 2 "hooks": { 3 "PostToolUse": [ 4 { 5 "matcher": "Edit|Write|MultiEdit", 6 "hooks": [ 7 { 8 "type": "command", 9 "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/format_after_edits.sh" 10 } 11 ] 12 } 13 ] 14 } 15}