Skip to content

6.3 Settings 设置与 Hooks 钩子

什么是 Settings?

Settings(设置)是 Claude Code 的配置选项,用于控制权限、超时、模型选择、状态栏显示等行为。每个 Setting 都是一个 JSON 文件,定义特定的配置项。

什么是 Hooks?

Hooks(钩子)是开发工作流的自动化触发器,可以在特定事件发生时自动执行命令。例如,在文件编辑后自动格式化、在工具调用前创建备份等。

Settings 文件结构

权限设置

json
{
  "description": "设置描述",
  "permissions": {
    "allow": [
      "Read(**/*)",
      "Glob",
      "Grep"
    ],
    "deny": [
      "Edit",
      "Write",
      "Bash"
    ]
  }
}

状态栏设置

json
{
  "description": "状态栏描述",
  "statusLine": {
    "type": "command",
    "command": "bash -c 'echo \"状态信息\"'"
  }
}

Hooks 文件结构

json
{
  "description": "钩子描述",
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "your-command-here"
          }
        ]
      }
    ],
    "PostToolUse": [...],
    "Stop": [...],
    "SubagentStop": [...]
  }
}

Hook 事件类型

事件触发时机
PreToolUse工具调用前
PostToolUse工具调用后
StopClaude Code 停止工作时
SubagentStop子代理完成任务时

Matcher(匹配器)

Matcher 用于指定哪些工具触发钩子:

Matcher匹配工具
Edit文件编辑
Write文件写入
Read文件读取
BashShell 命令

安装 Settings 和 Hooks

bash
# 安装权限设置
npx claude-code-templates@latest --setting permissions/read-only-mode --yes

# 安装状态栏
npx claude-code-templates@latest --setting statusline/git-flow-status --yes

# 安装钩子
npx claude-code-templates@latest --hook automation/discord-notifications --yes
npx claude-code-templates@latest --hook post-tool/format-javascript-files --yes

安装后的目录结构:

.claude/
├── settings.json
└── hooks.json

Settings 分类

1. 权限设置 (permissions)

设置描述
read-only-mode只读模式,禁止修改文件
allow-git-operations允许 Git 操作
allow-npm-commands允许 npm 命令
deny-sensitive-files禁止访问敏感文件
development-mode开发模式,完整权限

2. 状态栏 (statusline)

设置描述
time-statusline显示时间和模型信息
git-flow-status显示 Git Flow 分支状态
colorful-statusline彩色状态栏
context-monitor上下文使用监控

3. 模型设置 (model)

设置描述
opus-default默认使用 Opus 模型
sonnet-default默认使用 Sonnet 模型
haiku-default默认使用 Haiku 模型

4. MCP 设置 (mcp)

设置描述
mcp-timeoutsMCP 服务超时配置
mcp-retryMCP 重试策略

Hooks 分类

1. 自动化 (automation)

钩子描述
discord-notificationsDiscord 通知
slack-notificationsSlack 通知
telegram-notificationsTelegram 通知
vercel-auto-deployVercel 自动部署

2. Git 工作流 (git-workflow)

钩子描述
auto-git-add自动添加到暂存区
smart-commit智能提交

3. 开发工具 (development-tools)

钩子描述
lint-on-save保存时运行 Lint
file-backup文件备份
smart-formatting智能格式化

4. Pre-Tool(工具前置)

钩子描述
backup-before-edit编辑前备份
notify-before-bash执行命令前通知

5. Post-Tool(工具后置)

钩子描述
format-javascript-files格式化 JS/TS 文件
format-python-files格式化 Python 文件
git-add-changes自动 Git Add
run-tests-after-changes修改后运行测试

6. 安全 (security)

钩子描述
file-protection文件保护
security-scanner安全扫描

7. 性能 (performance)

钩子描述
performance-monitor性能监控
performance-budget-guard性能预算守卫

经典示例

只读模式

json
{
  "description": "Restrict Claude to read-only operations for code
    review and analysis. Safe for exploring unfamiliar codebases.",
  "permissions": {
    "allow": [
      "Read(**/*)",
      "Glob",
      "Grep",
      "LS"
    ],
    "deny": [
      "Edit",
      "Write",
      "MultiEdit",
      "Bash",
      "WebFetch"
    ]
  }
}

Git Flow 状态栏

json
{
  "description": "Display comprehensive Git Flow status with
    branch type, sync status, and change indicators.",
  "statusLine": {
    "type": "command",
    "command": "bash -c 'BRANCH=$(git branch --show-current);
      ICON=\"📁\";
      if [[ $BRANCH == feature/* ]]; then ICON=\"🌿\"; fi;
      if [[ $BRANCH == release/* ]]; then ICON=\"🚀\"; fi;
      if [[ $BRANCH == hotfix/* ]]; then ICON=\"🔥\"; fi;
      echo \"$ICON $BRANCH\"'"
  }
}

时间状态栏

json
{
  "description": "Status line with timestamp showing model,
    directory, and current time.",
  "statusLine": {
    "type": "command",
    "command": "bash -c 'input=$(cat);
      MODEL=$(echo \"$input\" | jq -r \".model.display_name\");
      DIR=$(echo \"$input\" | jq -r \".workspace.current_dir\");
      TIME=$(date \"+%H:%M\");
      echo \"[$MODEL] 📁 ${DIR##*/} | 🕐 $TIME\"'"
  }
}

Discord 通知钩子

json
{
  "description": "Send Discord notifications when Claude Code
    finishes working. Requires DISCORD_WEBHOOK_URL env variable.",
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "if [[ -n \"$DISCORD_WEBHOOK_URL\" ]]; then
              MESSAGE='{\"content\":\"🤖 Claude Code finished\"}';
              curl -s -X POST \"$DISCORD_WEBHOOK_URL\"
                -H \"Content-Type: application/json\"
                -d \"$MESSAGE\";
            fi"
          }
        ]
      }
    ]
  }
}

编辑前备份钩子

json
{
  "description": "Create automatic backup of files before any
    Edit operation for safety.",
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "if [[ -f \"$CLAUDE_TOOL_FILE_PATH\" ]]; then
              cp \"$CLAUDE_TOOL_FILE_PATH\"
                \"$CLAUDE_TOOL_FILE_PATH.backup.$(date +%s)\";
            fi"
          }
        ]
      }
    ]
  }
}

JavaScript 格式化钩子

json
{
  "description": "Automatically format JavaScript/TypeScript files
    after any Edit operation using prettier.",
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "if [[ \"$CLAUDE_TOOL_FILE_PATH\" =~
                \\.(js|ts|jsx|tsx)$ ]]; then
              npx prettier --write \"$CLAUDE_TOOL_FILE_PATH\";
            fi"
          }
        ]
      }
    ]
  }
}

智能提交钩子

json
{
  "description": "Intelligent git commit creation with automatic
    message generation and validation.",
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "if git rev-parse --git-dir >/dev/null 2>&1;
              then git add \"$CLAUDE_TOOL_FILE_PATH\";
              LINES=$(git diff --cached --numstat | awk '{print $1+$2}');
              if [[ $LINES -gt 0 ]]; then
                FILENAME=$(basename \"$CLAUDE_TOOL_FILE_PATH\");
                git commit -m \"Update $FILENAME\";
              fi;
            fi"
          }
        ]
      }
    ]
  }
}

创建自定义配置

自定义权限设置

bash
# 创建设置目录
mkdir -p .claude

创建 .claude/settings.json

json
{
  "permissions": {
    "allow": [
      "Read(**/*)",
      "Edit(**/*.ts)",
      "Write(**/*.ts)",
      "Bash(npm:*)",
      "Bash(git:*)"
    ],
    "deny": [
      "Edit(**/*.env*)",
      "Write(**/*.env*)",
      "Bash(rm -rf:*)"
    ]
  }
}

自定义钩子

创建 .claude/hooks.json

json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "echo 'File edited: $CLAUDE_TOOL_FILE_PATH'"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Claude Code session ended'"
          }
        ]
      }
    ]
  }
}

完整示例:安全开发环境

bash
#!/bin/bash
# 安全开发环境配置

# 1. 安装权限设置
npx claude-code-templates@latest \
  --setting permissions/deny-sensitive-files \
  --setting permissions/allow-git-operations \
  --yes

# 2. 安装状态栏
npx claude-code-templates@latest \
  --setting statusline/git-flow-status \
  --setting statusline/time-statusline \
  --yes

# 3. 安装安全钩子
npx claude-code-templates@latest \
  --hook security/file-protection \
  --hook security/security-scanner \
  --hook pre-tool/backup-before-edit \
  --yes

# 4. 安装开发钩子
npx claude-code-templates@latest \
  --hook post-tool/format-javascript-files \
  --hook development-tools/lint-on-save \
  --yes

# 5. 安装通知钩子(可选)
npx claude-code-templates@latest \
  --hook automation/slack-notifications \
  --yes

echo "安全开发环境配置完成!"
echo ""
echo "已配置:"
echo "  - 敏感文件保护"
echo "  - 编辑前自动备份"
echo "  - 代码自动格式化"
echo "  - 保存时 Lint 检查"
echo "  - 安全扫描"
echo "  - 工作完成通知"

环境变量

一些钩子需要配置环境变量:

bash
# Discord 通知
export DISCORD_WEBHOOK_URL="https://discord.com/api/webhooks/..."

# Slack 通知
export SLACK_WEBHOOK_URL="https://hooks.slack.com/services/..."

# Telegram 通知
export TELEGRAM_BOT_TOKEN="your-bot-token"
export TELEGRAM_CHAT_ID="your-chat-id"

最佳实践

  1. 权限最小化:只授予必要的权限
  2. 备份策略:在重要操作前创建备份
  3. 自动化格式化:保持代码风格一致
  4. 实时监控:使用状态栏监控关键信息
  5. 事件通知:重要操作完成后发送通知

下一步

基于 MIT 许可证发布。内容版权归作者所有。