Skip to content

16.2 Skills 配置選項

配置選項概述

Skills 提供了豐富的配置選項,允許使用者根據具體需求定製 Skills 的行為。本節將詳細介紹各種配置選項及其使用方法。

配置层级

1. 全局配置

1.1 配置文件位置

全局配置文件

文件位置

  • Linux/macOS: ~/.claude/config.yaml
  • Windows: %USERPROFILE%.claude\config.yaml
yaml
### 配置示例

    yaml


    # Claude Code 全局配置
    version: "1.0"

    skills:
      # 全局 Skill 设置
      default_timeout: 300
      max_retries: 3
      log_level: INFO

      # 默认参数
      defaults:
        code-review:
          strict: false
          include_security: true

        generate-tests:
          framework: pytest
          coverage_target: 80

#### 1.2 全局配置项

    yaml


    # 全局配置项详解
    skills:
      # 执行配置
      execution:
        timeout: 300              # 默认超时时间(秒)
        max_concurrent: 4         # 最大并发数
        retry_policy:
          max_attempts: 3         # 最大重试次数
          backoff: exponential    # 退避策略:linear, exponential
          initial_delay: 1        # 初始延迟(秒)

      # 缓存配置
      cache:
        enabled: true             # 是否启用缓存
        ttl: 3600                 # 缓存生存时间(秒)
        max_size: 1000            # 最大缓存条目数
        storage: memory           # 存储类型:memory, disk, redis

      # 日志配置
      logging:
        level: INFO               # 日志级别:DEBUG, INFO, WARNING, ERROR
        format: text              # 日志格式:text, json
        output: console           # 输出位置:console, file, both
        file_path: /tmp/claude-skills.log

      # 性能配置
      performance:
        enable_profiling: false   # 是否启用性能分析
        profile_interval: 60      # 性能分析间隔(秒)
        memory_limit: 1024        # 内存限制(MB)

      # 安全配置
      security:
        validate_inputs: true     # 是否验证输入
        sanitize_outputs: true    # 是否清理输出
        allow_network: false      # 是否允许网络访问

### 2\. 项目配置

#### 2.1 配置文件位置

    bash


    markdown

    ## 项目配置文件

    ### 文件位置
    - 项目根目录: .claude/project.yaml

    ### 配置示例
    ~~~yaml

    ```yaml

```yaml
    # 项目特定配置
    version: "1.0"

    project:
      name: "my-project"
      type: "web-application"
      language: "python"
      framework: "flask"

    skills:
      # 项目特定的 Skill 设置
      code-review:
        strict: true
        custom_rules:
          - no_print_statements
          - type_hints_required
        ignore_patterns:
          - "*/tests/*"
          - "*/migrations/*"
          - "*/vendor/*"

      generate-tests:
        framework: "pytest"
        coverage_target: 90
        test_dir: "tests"
        mock_external_calls: true

      format-code:
        style: "black"
        line_length: 88
        target_version: "py38"

    #### 2.2 项目配置项
yaml

# 项目配置项详解

project:

# 项目元数据

metadata: name: "my-project" description: "A web application" version: "1.0.0" author: "Team"

# 技术栈

tech_stack: language: "python" version: "3.9" frameworks: \- name: "flask" version: "2.3.0" \- name: "sqlalchemy" version: "2.0.0" libraries: \- name: "requests" version: "2.28.0" \- name: "numpy" version: "1.24.0"

# 代码规范

code_standards: style_guide: "PEP8" formatter: "black" linter: "pylint" max_line_length: 88 docstring_style: "google"

# 测试配置

testing: framework: "pytest" coverage_target: 80 test_dir: "tests" mock_external: true

# 文档配置

documentation: format: "markdown" include_api_docs: true include_examples: true output_dir: "docs"

skills:

# Skill 覆盖配置

overrides: code-review: enabled: true priority: high parameters: strict: true include_security: true include_performance: true

    bash


    generate-tests:
      enabled: true
      priority: medium
      parameters:
        framework: pytest
        coverage_target: 90
        generate_mocks: true

### 3\. 用户配置

#### 3.1 配置文件位置

## 用户配置文件

### 文件位置

  * Linux/macOS: ~/.claude/user.yaml
  * Windows: %USERPROFILE%.claude\user.yaml

### 配置示例

    bash


    `yaml

    # 用户特定配置
    version: "1.0"

    user:
    name: "John Doe"
    email: "john@example.com"

    preferences:
     # 编码偏好
    coding:
    language: "python"
    style: "PEP8"
    formatter: "black"
    indent_size: 4

     # 输出偏好
    output:
    format: "markdown"
    verbosity: "normal"
    include_code_blocks: true
    color_output: true

     # 交互偏好
    interaction:
    auto_confirm: false
    show_progress: true
    show_timing: true

     # 编辑器偏好
    editor:
    default: "vscode"
    line_numbers: true
    word_wrap: false

    skills:
     # 用户自定义的 Skill 设置
    aliases:
    cr: code-review
    gt: generate-tests
    fc: format-code

    favorites:
     - code-review
     - generate-tests
     - refactor-code

    ```> >

```yaml
#### 3.2 用户配置项

# 用户配置项详解

user:

# 用户信息

profile: name: "John Doe" email: "[john@example.com](mailto:john@example.com)" timezone: "UTC+8" language: "zh-CN" preferences:

# 交互偏好

interaction: auto_confirm: false # 自动确认 show_progress: true # 显示进度 show_timing: true # 显示耗时 show_details: false # 显示详细信息 prompt_style: "compact" # 提示样式:compact, verbose

# 输出偏好

output: format: "markdown" # 输出格式:markdown, json, html verbosity: "normal" # 详细程度:quiet, normal, verbose include_code_blocks: true # 包含代码块 include_line_numbers: false # 包含行号 color_output: true # 彩色输出 max_lines: 1000 # 最大输出行数

# 编辑器偏好

editor: default: "vscode" # 默认编辑器 open_in_new_tab: true # 在新标签页打开 focus_after_open: true # 打开后聚焦 line_numbers: true # 显示行号 word_wrap: false # 自动换行

# 通知偏好

notifications: enabled: true # 启用通知 on_completion: true # 完成时通知 on_error: true # 错误时通知 sound: false # 播放声音 skills:

# Skill 别名

aliases: cr: code-review gt: generate-tests fc: format-code ref: refactor-code doc: generate-docs

# 常用 Skills

favorites:


  * code-review
  * generate-tests
  * format-code
  * refactor-code

# Skill 默认参数

defaults: code-review: strict: false include_security: true generate-tests: framework: pytest coverage_target: 80 format-code: style: black line_length: 88

    bash


    ### 4. Skill 特定配置
    #### 4.1 代码审查配置

yaml

yaml
# code-review Skill 配置

skills: code-review: # 基本设置 enabled: true priority: high

    bash


    # 审查标准
    standards:
      # 代码质量
      quality:
        check_complexity: true
        max_complexity: 10
        check_duplication: true
        max_duplication: 5

      # 安全性
      security:
        enabled: true
        check_sql_injection: true
        check_xss: true
        check_hardcoded_secrets: true
        check_insecure_deserialization: true

      # 性能
      performance:
        enabled: true
        check_n_plus_one: true
        check_memory_leaks: true
        check_inefficient_loops: true

      # 最佳实践
      best_practices:
        enabled: true
        check_error_handling: true
        check_logging: true
        check_documentation: true
        check_type_hints: true

    # 严格程度
    strictness: "medium"  # low, medium, high, strict

    # 忽略规则
    ignore_rules:
      - "line-too-long"
      - "too-many-arguments"

    # 忽略模式
    ignore_patterns:
      - "*/tests/*"
      - "*/migrations/*"
      - "*/vendor/*"
      - "*/node_modules/*"

    # 输出格式
    output:
      format: "markdown"
      include_code_snippets: true
      include_fix_suggestions: true
      group_by_severity: true

    # 自定义规则
    custom_rules:
      - name: "no_print_statements"
        severity: "warning"
        message: "Avoid using print statements"
        pattern: "print\\("

      - name: "type_hints_required"
        severity: "error"
        message: "Function must have type hints"
        check_function: has_type_hints

#### 4.2 测试生成配置

# generate-tests Skill 配置

skills: generate-tests:

# 基本设置

enabled: true priority: medium

# 测试框架

framework: "pytest" # pytest, unittest, jest, mocha

# 测试类型

test_types:


  * unit_tests
  * integration_tests
  * edge_cases

# 覆盖率目标

coverage: enabled: true target: 80 minimum: 60

# 测试生成策略

generation: strategy: "comprehensive" # basic, comprehensive, exhaustive include_positive_tests: true include_negative_tests: true include_edge_cases: true include_boundary_tests: true

# Mock 配置

mocking: enabled: true mock_external_calls: true mock_database: true mock_network: true use_realistic_mocks: true

# 测试数据

test_data: generate_fixtures: true use_realistic_data: true include_edge_cases: true

# 输出配置

output: test_dir: "tests" file_naming: "test_{module}.py" include_docstrings: true include_comments: true

# 断言配置

assertions: use_strict_assertions: true include_error_messages: true check_return_values: true check_exceptions: true

    bash


    #### 4.3 代码格式化配置

yaml

yaml
# format-code Skill 配置

skills: format-code: # 基本设置 enabled: true priority: low

    bash


    # 格式化工具
    formatter: "black"  # black, autopep8, yapf, prettier

    # 格式化规则
    rules:
      line_length: 88
      indent_size: 4
      indent_style: "space"
      quote_style: "double"
      trailing_comma: true
      spaces_around_operators: true

    # 目标版本
    target_version: "py38"

    # 排除文件
    exclude:
      - "*/tests/*"
      - "*/migrations/*"
      - "*/vendor/*"

    # 自动修复
    auto_fix: true
    fix_imports: true
    sort_imports: true

    # 输出配置
    output:
      in_place: true
      create_backup: true
      show_diff: true

## 配置优先级

### 优先级规则

## 配置优先级(从高到低)

### 1\. 命令行参数

    bash


    `bash

    claude --skill code-review --strict --file src/main.py

    ```### 2. 環境變數

bash

export CLAUDE_SKILL_CODE_REVIEW_STRICT=true

3. 项目配置

bash


````yaml
yaml
    # ~/.claude/config.yaml
    skills:
    code-review:
    strict: false

    ```### 6. 預設配置

yaml

内置默认值

strict: false

配置合并

bash


python

class ConfigManager:
    def __init__(self):
        self.configs = {
            "default": self.load_default_config(),
            "global": self.load_global_config(),
            "user": self.load_user_config(),
            "project": self.load_project_config()
        }

    def get_config(self, skill_name, key):
        # 按优先级查找配置
        for config_type in ["project", "user", "global", "default"]:
            config = self.configs[config_type]
            if skill_name in config.get("skills", {}):
                skill_config = config["skills"][skill_name]
                if key in skill_config:
                    return skill_config[key]
        return None

    def merge_configs(self, skill_name):
        # 合并所有配置
        merged = {}
        for config_type in ["default", "global", "user", "project"]:
            config = self.configs[config_type]
            if skill_name in config.get("skills", {}):
                merged = self.deep_merge(merged, config["skills"][skill_name])
        return merged

    def deep_merge(self, dict1, dict2):
        result = dict1.copy()
        for key, value in dict2.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = self.deep_merge(result[key], value)
            else:
                result[key] = value
        return result

## 动态配置

### 1. 环境变量

## 环境变量配置
### 命名规则
- 前缀: CLAUDE_SKILL_
- 格式: CLAUDE_SKILL_{SKILL_NAME}_{KEY}
- 示例: CLAUDE_SKILL_CODE_REVIEW_STRICT
### 使用示例
~~~`bash
`bash

# 设置代码审查严格模式
export CLAUDE_SKILL_CODE_REVIEW_STRICT=true

# 设置测试生成覆盖率目标
export CLAUDE_SKILL_GENERATE_TESTS_COVERAGE_TARGET=90

# 设置格式化工具
export CLAUDE_SKILL_FORMAT_CODE_FORMATTER=black

```> >
python
### 2\. 运行时配置

class RuntimeConfig: def **init**(self): self.config = {} def set(self, key, value): self.config[key] = value def get(self, key, default=None): return self.config.get(key, default) def update(self, updates): self.config.update(updates) def clear(self): self.config.clear()

# 使用示例

runtime_config = RuntimeConfig() runtime_config.set("code_review.strict", True) runtime_config.set("generate_tests.coverage_target", 90)

    bash


    ### 3. 条件配置

yaml

python
# 条件配置示例

skills: code-review: # 根据环境配置 environments: development: strict: false include_performance: false testing: strict: true include_performance: true production: strict: true include_performance: true include_security: true

    bash


    # 根据文件类型配置
    file_types:
      python:
        check_type_hints: true
        check_docstrings: true
      javascript:
        check_eslint: true
        check_typescript: true
      html:
        check_accessibility: true
        check_seo: true

## 配置验证

### 1\. 配置验证

class ConfigValidator: def **init**(self): self.schemas = self.load_schemas() def validate(self, skill_name, config): schema = self.schemas.get(skill_name) if not schema: return True errors = [] for key, value in config.items(): if key not in schema: errors.append(f"Unknown configuration key: {key}") continue key_schema = schema[key] if not self.validate_value(value, key_schema): errors.append(f"Invalid value for {key}: {value}") return len(errors) == 0, errors def validate_value(self, value, schema): value_type = schema.get("type") if value_type == "boolean": return isinstance(value, bool) elif value_type == "integer": return isinstance(value, int) elif value_type == "string": return isinstance(value, str) elif value_type == "enum": return value in schema.get("values", []) return True def load_schemas(self): return { "code-review": { "strict": {"type": "boolean"}, "include_security": {"type": "boolean"}, "include_performance": {"type": "boolean"}, "strictness": {"type": "enum", "values": ["low", "medium", "high", "strict"]} }, "generate-tests": { "framework": {"type": "enum", "values": ["pytest", "unittest", "jest", "mocha"]}, "coverage_target": {"type": "integer"}, "mock_external_calls": {"type": "boolean"} } }

    bash


    ### 2. 配置迁移

python

python
class ConfigMigrator: def **init**(self): self.migrations = { "1.0": self.migrate_1_0_to_1_1, "1.1": self.migrate_1_1_to_1_2 }

    bash


    def migrate(self, config, from_version, to_version):
        current_version = from_version
        while current_version != to_version:
            if current_version in self.migrations:
                config = self.migrations[current_version](config)
                current_version = self.increment_version(current_version)
            else:
                break
        return config

    def migrate_1_0_to_1_1(self, config):
        # 迁移逻辑
        if "skills" in config:
            for skill_name, skill_config in config["skills"].items():
                if "strict" in skill_config:
                    skill_config["strictness"] = "high" if skill_config["strict"] else "low"
        return config

    def increment_version(self, version):
        major, minor = version.split(".")
        return f"{major}.{int(minor) + 1}"

    bash


    ## 总结

    Skills 的配置选项提供了灵活的定制能力,通过合理的配置可以显著提高 Skills 的适用性和效率。理解配置层级、优先级和验证机制有助于更好地管理和使用 Skills。

    在下一节中,我们将探讨 Skills 的生命周期管理,了解 Skills 的创建、更新、删除等操作。

基于 MIT 许可发布 | 永久导航