### Development Setup Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md Commands to install the project in development mode and set up the development environment. ```bash make install-dev # or pip install -e .[dev] # Complete dev environment setup make dev-setup ``` -------------------------------- ### Running Examples Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md Command to run a basic example provided by the project. ```bash # Run basic example make run-example ``` -------------------------------- ### Install yaml2py Source: https://github.com/joneshong/yaml2py/blob/main/README.zh.md Instructions for installing the yaml2py package using pip or from source. ```bash pip install yaml2py ``` ```bash git clone https://github.com/joneshong/yaml2py.git cd yaml2py pip install . ``` -------------------------------- ### Database Configuration Example Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md A sample INI-style configuration block for database connection settings, including host, port, user, and sensitive credentials. ```ini [database] host = localhost port = 5432 name = myapp user = admin password = secret123 pool_size = 10 timeout = 30 ssl_mode = require ``` -------------------------------- ### Configuration Validation Example Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md Provides a Python class example for validating database configuration parameters, such as port numbers. ```python class ConfigValidator: @staticmethod def validate_database_config(db_config): if db_config.port < 1 or db_config.port > 65535: raise ValueError(f"Invalid port: {db_config.port}") return True ``` -------------------------------- ### Hot Reloading Example Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md Demonstrates how to implement hot reloading for configuration values, continuously monitoring for changes and reacting to them. ```python # Configuration automatically reloads when files change last_port = config.system.port while True: current_port = config.system.port if current_port != last_port: print(f"Port changed: {last_port} → {current_port}") last_port = current_port time.sleep(1) ``` -------------------------------- ### Example List config.yaml Source: https://github.com/joneshong/yaml2py/blob/main/README.zh.md YAML configuration demonstrating a list of endpoint objects. ```yaml endpoints: - path: /users method: GET auth_required: true - path: /login method: POST auth_required: false ``` -------------------------------- ### Basic Usage Command Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md Demonstrates the command-line execution for basic yaml2py usage, including specifying configuration and output directories. ```bash cd basic_usage/ yaml2py --config config.yaml --output ./generated python usage_example.py ``` -------------------------------- ### Basic Web Application Configuration Example Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md A simple YAML configuration example for a web application, including app name, version, debug mode, server host and port, and database connection URL. ```yaml # 簡單的 Web 應用程式配置 app: name: SimpleWebApp version: 1.0.0 debug: true server: host: 0.0.0.0 port: 8000 database: url: sqlite:///app.db ``` -------------------------------- ### Microservices Configuration Example Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md An example of a microservices architecture configuration in YAML, covering service details, discovery mechanisms (Consul), message queue settings (RabbitMQ), and API gateway parameters. ```yaml # 微服務架構配置 service: name: user-service version: 2.1.0 # 服務發現 discovery: consul: host: consul.service.consul port: 8500 # 訊息佇列 messaging: rabbitmq: host: ${RABBITMQ_HOST:localhost} port: ${RABBITMQ_PORT:5672} username: ${RABBITMQ_USER} password: ${RABBITMQ_PASS} # API 閘道 gateway: timeout: 30 retry_count: 3 circuit_breaker: threshold: 5 timeout: 60 ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Installs the necessary packages for development and testing of the yaml2py project. ```bash make install-dev ``` -------------------------------- ### Example config.yaml Source: https://github.com/joneshong/yaml2py/blob/main/README.zh.md A sample YAML configuration file demonstrating nested structures, lists, and various data types. ```yaml app: name: MyApplication version: 1.0.0 debug: true database: host: localhost port: 5432 username: admin password: secret123 options: pool_size: 10 timeout: 30 features: - name: feature_a enabled: true config: threshold: 0.8 - name: feature_b enabled: false config: threshold: 0.5 ``` -------------------------------- ### API Configuration Example Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md An INI-style configuration snippet for external API settings, including base URL, API key, timeouts, and circuit breaker settings. ```ini [api] base_url = https://api.example.com api_key = sk-1234567890abcdef timeout = 30 retries = 3 enable_circuit_breaker = true ``` -------------------------------- ### Security Settings Example Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md Shows a typical INI configuration block for security-related parameters like secret keys, JWT expiry, and rate limiting. ```ini [security] secret_key = super-secret-key jwt_expiry_hours = 24 session_timeout = 1800 enable_rate_limiting = true rate_limit_per_minute = 100 ``` -------------------------------- ### Basic Configuration Access Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md Shows how to access configuration values with type hints using the ConfigManager generated by yaml2py. ```python from generated.manager import ConfigManager config = ConfigManager() # Access with full type hints port = config.system.port # int debug = config.system.debug # bool timeout = config.system.timeout # float ``` -------------------------------- ### Multi-Environment Configuration Example Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Demonstrates how to manage configurations for different environments (development, production) using environment variables and conditional settings for features and logging. ```yaml # 使用環境變數切換配置 environment: ${ENV:development} # 開發環境預設值 database: host: ${DB_HOST:localhost} port: ${DB_PORT:5432} # 根據環境調整 features: debug_toolbar: ${ENABLE_DEBUG:true} profiling: ${ENABLE_PROFILING:false} # 日誌配置 logging: level: ${LOG_LEVEL:DEBUG} format: ${LOG_FORMAT:detailed} ``` -------------------------------- ### Advanced Usage Command Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md Illustrates the command-line execution for advanced yaml2py usage, showcasing complex configuration file processing. ```bash cd advanced_usage/ yaml2py --config config.yaml --output ./generated python advanced_example.py ``` -------------------------------- ### Example Nested config.yaml Source: https://github.com/joneshong/yaml2py/blob/main/README.zh.md YAML configuration showcasing deeper nesting for cache providers. ```yaml cache: enabled: true providers: redis: host: 127.0.0.1 port: 6379 memory: max_size: 1024 ``` -------------------------------- ### Install yaml2py Source: https://github.com/joneshong/yaml2py/blob/main/README.md Installs the yaml2py package using pip. This is the primary method for getting the tool. ```bash pip install yaml2py ``` -------------------------------- ### yaml2py Type Inference Examples Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md Demonstrates how yaml2py infers data types from string values in YAML configuration files. It covers conversion to integers, floats, booleans, and strings. ```python # yaml2py infers types from string values: # "123" → int # "12.34" → float # "true"/"false" → bool # "anything else" → str ``` -------------------------------- ### Type Safety Examples Source: https://github.com/joneshong/yaml2py/blob/main/README.zh.md Illustrates the type safety provided by yaml2py for different configuration values. ```python config.app.debug # bool config.database.port # int config.app.version # str config.features # List[FeatureSchema] ``` -------------------------------- ### Development: Project Structure Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Outlines the directory structure of the yaml2py project, detailing the organization of source code, templates, tests, examples, and documentation. ```bash yaml2py/ ├── yaml2py/ │ ├── __init__.py │ ├── cli.py # CLI 主程式 │ ├── env_loader.py # 環境變數處理 │ └── templates/ # 程式碼模板 │ ├── schema.py.tpl │ └── manager.py.tpl ├── tests/ # 測試套件 ├── examples/ # 範例配置 ├── docs/ # 文件 └── Makefile # 開發工具 ``` -------------------------------- ### Troubleshooting Import Errors with yaml2py Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md This snippet shows how to resolve import errors by ensuring files are generated and the Python path is correctly set. It involves running the yaml2py command and exporting the PYTHONPATH environment variable. ```bash # Make sure to generate files first yaml2py --config config.yaml --output ./generated # Check Python path export PYTHONPATH="${PYTHONPATH}:./generated" ``` -------------------------------- ### List Handling in Configuration Source: https://github.com/joneshong/yaml2py/blob/main/README.zh.md Example of iterating through a list of objects within the configuration. ```python for endpoint in config.api.endpoints: print(f"{endpoint.method} {endpoint.path}") ``` -------------------------------- ### Sensitive Data Handling Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md Demonstrates how yaml2py automatically masks sensitive data like passwords in output and how to retrieve the actual values. ```python # Automatic masking in logs/debug output props = config.database.return_properties(return_type='list') print(props) # password will be masked as "se****23" # Get actual values for use in code actual_password = config.database.password # "secret123" ``` -------------------------------- ### Using Generated Configuration in Python Source: https://github.com/joneshong/yaml2py/blob/main/README.zh.md Example of how to use the generated ConfigManager and access configuration values in Python code. ```python from src.config.manager import ConfigManager config = ConfigManager() print(config.app.name) print(config.app.debug) print(config.database.host) print(config.database.options.pool_size) for feature in config.features: print(f"{feature.name}: {feature.enabled}") print(config.database.password) config.database.print_all() ``` -------------------------------- ### List Handling Example in YAML Source: https://github.com/joneshong/yaml2py/blob/main/README.md Shows a YAML structure containing a list of server objects, demonstrating how yaml2py automatically generates typed classes for list items. ```yaml servers: - name: web-1 host: 10.0.0.1 port: 80 - name: web-2 host: 10.0.0.2 port: 80 ``` -------------------------------- ### Feature Flag Check Source: https://github.com/joneshong/yaml2py/blob/main/examples/README.md Illustrates a Python function to check if a specific feature is enabled based on the configuration, using dynamic attribute access. ```python def is_feature_enabled(config, feature_name: str) -> bool: return getattr(config.feature_flags, f"enable_{feature_name}", False) # Usage if is_feature_enabled(config, 'new_ui'): # Enable new UI features pass ``` -------------------------------- ### Example YAML Configuration File Source: https://github.com/joneshong/yaml2py/blob/main/README.md A sample YAML file demonstrating a nested structure with various data types including strings, booleans, integers, floats, lists of objects, and nested dictionaries. ```yaml system: mode: development debug: true port: 8080 timeout: 30.5 database: host: localhost port: 5432 name: myapp user: admin password: secret123 options: pool_size: 10 retry_attempts: 3 redis: host: 127.0.0.1 port: 6379 db: 0 features: - name: authentication enabled: true config: session_timeout: 3600 max_attempts: 5 - name: logging enabled: false config: level: info format: json ai_service: api_key: sk-1234567890abcdef model: gpt-4 endpoints: - path: /chat method: POST rate_limit: 100 - path: /completions method: POST rate_limit: 50 ``` -------------------------------- ### Accessing Configuration in Python Source: https://github.com/joneshong/yaml2py/blob/main/README.md Provides an example of how to use the generated configuration classes in Python code. It demonstrates accessing nested values, list items, and using the `print_all()` method for safe output. ```python from src.config.manager import ConfigManager # Get singleton instance config = ConfigManager() # Access with full type hints and autocomplete print(config.system.mode) # 'development' print(config.system.debug) # True (as boolean) print(config.database.port) # 5432 (as int) print(config.system.timeout) # 30.5 (as float) # Access nested structures print(config.database.options.pool_size) # 10 print(config.database.options.retry_attempts) # 3 # Access lists with type safety for feature in config.features: print(f"{feature.name}: {feature.enabled}") if feature.enabled: print(f" Timeout: {feature.config.session_timeout}") # Direct access returns actual values print(config.database.password) # 'secret123' print(config.ai_service.api_key) # 'sk-1234567890abcdef' # Use print_all() method to safely display config with masked sensitive data config.database.print_all() # Output: # DatabaseSchema: # ---------------------------------------- # host: localhost # port: 5432 # name: myapp # user: admin # password: se*****23 # Automatically masked! # ---------------------------------------- # Hot reloading - config updates automatically # Edit config.yaml and changes are reflected immediately! ``` -------------------------------- ### Nested Structure Example in YAML Source: https://github.com/joneshong/yaml2py/blob/main/README.md Illustrates a deeply nested YAML structure for application services, showcasing how yaml2py handles complex hierarchies. ```yaml app: name: MyApp services: cache: provider: redis settings: ttl: 3600 max_entries: 1000 queue: provider: rabbitmq settings: prefetch: 10 durable: true ``` -------------------------------- ### Type Consistency in YAML Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Highlights the importance of maintaining type consistency within YAML lists, showing an example of mixed types and the preferred approach with uniform types. ```yaml # ❌ 避免混合型別 ports: - 8080 - "9090" # 字串 - 3000 # ✅ 保持型別一致 ports: - 8080 - 9090 - 3000 ``` -------------------------------- ### Development: Setting Up Development Environment Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Provides instructions for setting up the development environment, including cloning the repository, creating a virtual environment, and activating it. ```bash # 克隆專案 git clone https://github.com/yourusername/yaml2py.git cd yaml2py # 建立虛擬環境 python -m venv venv source venv/bin/activate # Linux/Mac # 或 venv\Scripts\activate # Windows ``` -------------------------------- ### Building and Publishing Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md Commands for cleaning build artifacts, building distribution packages, checking them, uploading to TestPyPI and PyPI, and preparing for release. ```bash # Clean build artifacts make clean # Build distribution packages make build # Check distribution packages make check-dist # Upload to TestPyPI make upload-test # Upload to PyPI (requires proper credentials) make upload # Prepare for release (runs all checks) make prepare-release ``` -------------------------------- ### 生成配置類別 Source: https://github.com/joneshong/yaml2py/blob/main/examples/env_support/README.md 使用 yaml2py 命令根據 YAML 配置檔案生成 Python 配置類別。需要在 examples/env_support 目錄下執行。 ```bash # 在 examples/env_support 目錄下執行 cd examples/env_support yaml2py -c config_with_env.yaml -o generated_config ``` -------------------------------- ### Release Process Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Commands to manage the release process, including preparing the release, building distribution packages, and uploading to TestPyPI and PyPI. ```bash # Prepare for release make prepare-release # Build distribution packages make build # Upload to TestPyPI make upload-test # Upload to PyPI make upload ``` -------------------------------- ### config_with_env.yaml 範例 Source: https://github.com/joneshong/yaml2py/blob/main/examples/env_support/README.md 一個包含環境變數語法的 YAML 配置檔案範例,用於測試 yaml2py 的環境變數支援功能。 ```yaml database: host: localhost port: 5432 name: asr_hub user: postgres password: "${DB_PASSWORD}" logging: level: "${LOG_LEVEL:-INFO}" app: environment: "${ENVIRONMENT:-development}" debug_mode: false provider: openai_enabled: "${ENABLE_OPENAI:-false}" openai_api_base: "https://api.openai.com" # 測試未設定環境變數時的預設值 # 如果 DB_HOST 未設定,則使用 'localhost' db_host_with_default: "${DB_HOST:-localhost}" # 測試布林值和數字的自動轉換 retry_count: "${RETRY_COUNT:-3}" use_ssl: "${USE_SSL:-true}" ``` -------------------------------- ### 測試嚴格模式 - 啟用與禁用 Source: https://github.com/joneshong/yaml2py/blob/main/examples/env_support/README.md 演示如何啟用和禁用 yaml2py 的嚴格模式,以及在嚴格模式下缺少環境變數時的錯誤處理。 ```bash # 啟用嚴格模式 export YAML2PY_STRICT_ENV=true # 刪除必要的環境變數 unset DB_PASSWORD # 重新生成(應該會報錯) yaml2py -c config_with_env.yaml -o generated_config ``` -------------------------------- ### 使用 yaml2py 生成 Python 配置類別 Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 展示如何使用 yaml2py 命令列工具從 YAML 檔案生成 Python 配置類別,包括指定輸入和輸出路徑以及互動式模式。 ```bash # 指定輸入和輸出路徑yaml2py --config config.yaml --output ./src/config # 或使用簡短選項yaml2py -c config.yaml -o ./src/config # 互動式模式(自動偵測配置檔案)yaml2py ``` -------------------------------- ### 安裝 yaml2py (開發模式) Source: https://github.com/joneshong/yaml2py/blob/main/examples/env_support/README.md 在專案根目錄執行此命令以開發模式安裝 yaml2py 套件。 ```bash cd ../.. pip install -e . ``` -------------------------------- ### Package Initialization Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md The __init__.py file for the yaml2py package, responsible for package initialization and exporting version information. ```python # yaml2py/__init__.py # Package initialization # Exports version information # Currently empty (generation logic is in cli.py) ``` -------------------------------- ### Iterating Through Typed List Items in Python Source: https://github.com/joneshong/yaml2py/blob/main/README.md An example of iterating through a list of configuration objects generated by yaml2py, accessing properties of each item with type safety. ```python for server in config.servers: # server has full type hints print(f"{server.name}: {server.host}:{server.port}") ``` -------------------------------- ### CLI Help Source: https://github.com/joneshong/yaml2py/blob/main/README.zh.md Displays the help message for the yaml2py command-line interface. ```bash yaml2py --help ``` -------------------------------- ### Contribution Workflow Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Steps for contributing to the yaml2py project, following standard Git practices for forking, branching, committing, and creating pull requests. ```bash 1. Fork the project 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ``` -------------------------------- ### Project Entry Points and Version Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md Specifies the entry points for the CLI tool and the current version of the project. ```python # Entry points: `yaml2py` and `yml2py` (defined in pyproject.toml) # Version: 0.1.0 (semantic versioning) ``` -------------------------------- ### yaml2py 列表和物件陣列處理 Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 展示如何處理 YAML 中的列表和物件陣列,yaml2py 會為物件陣列自動生成型別化類別。 ```yaml servers: - name: web-1 host: 10.0.0.1 port: 80 region: us-east - name: web-2 host: 10.0.0.2 port: 80 region: us-west ``` -------------------------------- ### Configuration Type Safety (Python) Source: https://github.com/joneshong/yaml2py/blob/main/README.md Demonstrates the type safety of configurations managed by yaml2py. It shows examples of accessing typed attributes for system and database configurations, including boolean, integer, float, string, list, and custom schema types. ```python config.system.debug # bool config.database.port # int config.system.timeout # float config.database.name # str config.features # List[FeatureSchema] config.database.options # OptionsSchema ``` -------------------------------- ### Run Tests Source: https://github.com/joneshong/yaml2py/blob/main/README.zh.md Command to execute the test suite for the yaml2py project. ```bash python -m pytest tests/ ``` -------------------------------- ### Testing Commands Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md Commands for running all tests, specific test files, tests with coverage, and tests with markers. ```bash # Run all tests python -m pytest tests/ # Run specific test file python -m pytest tests/test_cli.py # Run tests with coverage make test-coverage # Run tests with specific marker python -m pytest -m "not slow" # Skip slow tests python -m pytest -m cli # Only CLI tests ``` -------------------------------- ### CLI Help and Options Source: https://github.com/joneshong/yaml2py/blob/main/README.md Displays the help message and available command-line options for the yaml2py tool. It details options for specifying configuration files and output directories. ```bash yaml2py --help Options: -c, --config PATH Path to YAML configuration file -o, --output PATH Output directory for generated files --help Show this message and exit ``` -------------------------------- ### YAML Configuration File Structure Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Illustrates a recommended structure for organizing YAML configuration files with clear grouping for application settings, environment-specific configurations, and external services. ```yaml # 使用清晰的分組 app: # 應用程式基本資訊 name: MyApp version: 1.0.0 # 環境相關配置 environment: name: production debug: false # 外部服務配置 services: database: # 主要配置 cache: # 快取配置 ``` -------------------------------- ### API Reference: ConfigManager Class Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Details the `ConfigManager` class, which handles configuration loading and management using a singleton pattern. It includes methods for initialization, reloading, and retrieving raw configuration data. ```APIDOC class ConfigManager: """配置管理器,使用單例模式""" def __init__(self, config_path: Optional[str] = None): """ 初始化配置管理器 參數: config_path: 配置檔案路徑(可選,預設自動偵測) """ def reload_config(self): """手動重新載入配置""" def get_raw_data(self) -> Dict[str, Any]: """獲取原始 YAML 資料""" ``` -------------------------------- ### Template System Details Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md Provides details about the template system used for code generation, including the placeholder syntax and the nature of the .tpl files. ```python # Template System: # - Uses string templates with `{{PLACEHOLDER}}` syntax # - Not Jinja2 despite the .tpl extension # - Templates include base class with utility methods ``` -------------------------------- ### Code Quality Checks Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md Commands for running linting checks, auto-formatting code, security checks, and the full CI pipeline. ```bash # Run all linting checks (flake8, mypy, isort) make lint # Auto-format code (black + isort) make format # Security checks make security-check # Full CI pipeline (format → lint → test → build) make ci ``` -------------------------------- ### File Format Support Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md Details the supported file extensions (.yaml, .yml) and the auto-discovery mechanism for configuration files in common locations. ```python # File Format Support: # - Supports both `.yaml` and `.yml` extensions # - Auto-discovers files in: config.yaml/yml, config/*.yaml/yml, settings.yaml/yml, app.yaml/yml ``` -------------------------------- ### yaml2py CLI Usage Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Provides basic command-line interface usage for the yaml2py tool, including options for specifying configuration and output paths. ```bash yaml2py [OPTIONS] # 選項 # --config (-c): YAML 配置檔案路徑 (預設: 自動偵測) # --output (-o): 輸出目錄路徑 (預設: 自動偵測) ``` -------------------------------- ### yaml2py 熱重載功能 Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 演示 yaml2py 的熱重載功能,配置檔案變更後無需重啟應用程式即可自動重新載入。 ```python # 初始配置 config = ConfigManager() print(config.app.debug) # False # 編輯 config.yaml,將 debug 改為 true # 不需要重啟程式! time.sleep(2) # 等待檔案系統事件 print(config.app.debug) # True - 自動更新! ``` -------------------------------- ### 設定和使用環境變數 Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 說明如何在終端機中設定環境變數以供 yaml2py 使用,以及如何啟用嚴格模式。 ```bash # 設定環境變數 export DB_HOST=prod-db.example.com export DB_PASSWORD=super_secret # 執行應用程式 python app.py # 啟用嚴格模式 export YAML2PY_STRICT_ENV=true # 現在缺少必要的環境變數會拋出錯誤 yaml2py -c config.yaml -o ./output ``` -------------------------------- ### yaml2py 敏感資料保護 Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 說明 yaml2py 如何自動偵測和遮罩敏感資料(如密碼、金鑰),並提供 `print_all()` 方法的使用範例。 ```python # 直接存取會返回真實值 real_password = config.database.password # "secret123" # 使用 print_all() 會自動遮罩 config.database.print_all() ``` -------------------------------- ### test_env_support.py 範例 Source: https://github.com/joneshong/yaml2py/blob/main/examples/env_support/README.md 一個 Python 腳本,用於測試 yaml2py 生成的配置類別,包括讀取環境變數和顯示配置資訊。 ```python import os import sys # 將專案根目錄添加到 Python 路徑 project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) sys.path.insert(0, project_root) from generated_config.schema import Config def main(): print("=== 環境變數配置測試 ===") config = Config() print(f"\n環境: {config.app.environment}") print(f"日誌級別: {config.logging.level}") print(f"調試模式: {config.app.debug_mode}") print("\n--- 資料庫配置 ---") print(f"主機: {config.database.host}") print(f"連接埠: {config.database.port}") print(f"資料庫名稱: {config.database.name}") print("\n--- 敏感資料 ---") print(f"密碼(實際值): {config.database.password}") print("\n--- 使用 print_all() 顯示所有配置(遮罩敏感資料)---") config.print_all() print("\n--- Provider 配置 ---") print(f"OpenAI 啟用: {config.provider.openai_enabled}") print(f"OpenAI API Base: {config.provider.openai_api_base}") print("\n--- 提示 ---") print("1. 環境變數在程式啟動時載入") print("2. 修改 YAML 檔案會觸發熱重載") print("3. 修改環境變數需要重啟程式才能生效") if __name__ == "__main__": main() ``` -------------------------------- ### 測試場景 1:使用預設值 Source: https://github.com/joneshong/yaml2py/blob/main/examples/env_support/README.md 在不設定任何環境變數的情況下執行測試,以驗證預設值的行為。 ```bash # 不設定任何環境變數 unset ENVIRONMENT LOG_LEVEL DB_PASSWORD OPENAI_API_KEY ./run_test.sh ``` -------------------------------- ### YAML 配置檔案範例 Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 一個包含應用程式、伺服器、資料庫和功能設定的範例 YAML 配置檔案。 ```yaml # 應用程式配置 app: name: MyAwesomeApp version: 1.0.0 debug: true # 伺服器設定 server: host: 0.0.0.0 port: 8080 workers: 4 timeout: 30.5 # 資料庫配置 database: engine: postgresql host: localhost port: 5432 name: myapp_db user: admin password: secret123 # 連接池設定 pool: size: 20 max_overflow: 10 timeout: 30 # 功能開關 features: - name: authentication enabled: true config: session_timeout: 3600 max_attempts: 3 - name: caching enabled: false config: backend: redis ttl: 300 ``` -------------------------------- ### 設定測試環境變數 Source: https://github.com/joneshong/yaml2py/blob/main/examples/env_support/README.md 設定必要的和可選的環境變數以供 yaml2py 使用。這包括資料庫密碼、API 金鑰以及日誌級別等。 ```bash # 必要的環境變數 export DB_PASSWORD="my_secret_password" export OPENAI_API_KEY="sk-test123456" # 可選的環境變數(有預設值) export ENVIRONMENT="production" export LOG_LEVEL="DEBUG" export ENABLE_OPENAI="true" ``` -------------------------------- ### 停用 yaml2py 熱重載 Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 說明如何在 CI 環境或特定情況下停用 yaml2py 的熱重載功能。 ```bash # 方法 1:設定環境變數 os.environ['CI'] = 'true' # 方法 2:修改程式碼(需要自訂) # ConfigManager 會自動偵測 CI 環境 ``` -------------------------------- ### yaml2py 巢狀結構處理範例 Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 展示如何定義和存取 YAML 中的深層巢狀結構,yaml2py 會自動生成對應的 Python 類別。 ```yaml services: api: endpoints: users: base_path: /api/v1/users methods: get: rate_limit: 1000 cache_ttl: 300 post: rate_limit: 100 requires_auth: true ``` -------------------------------- ### Code Quality Commands Source: https://github.com/joneshong/yaml2py/blob/main/README.zh.md Commands for maintaining code quality, including linting, formatting, and testing. ```bash make lint make format make test ``` -------------------------------- ### 執行測試腳本 Source: https://github.com/joneshong/yaml2py/blob/main/examples/env_support/README.md 執行 Python 測試腳本以驗證環境變數的載入和配置的正確性。 ```bash python test_env_support.py ``` -------------------------------- ### yaml2py 環境變數支援 Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 展示如何在 YAML 配置中使用環境變數,包括基本語法、帶預設值的變數以及嚴格模式。 ```yaml database: host: ${DB_HOST} # 必須設定的環境變數 port: ${DB_PORT:5432} # 帶預設值的環境變數 name: ${DB_NAME:myapp} user: ${DB_USER:postgres} password: ${DB_PASSWORD} # 敏感資料不應提供預設值 ``` -------------------------------- ### 測試場景 3:覆蓋所有預設值 Source: https://github.com/joneshong/yaml2py/blob/main/examples/env_support/README.md 設定所有相關環境變數以覆蓋預設值,測試自定義配置的行為。 ```bash export ENVIRONMENT="staging" export LOG_LEVEL="ERROR" export DB_HOST="remote-db.example.com" export DB_PORT="3306" ./run_test.sh ``` -------------------------------- ### Troubleshooting: Hot Reload Issues Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Discusses potential reasons for hot reload failures, such as execution in CI environments, file system limitations, or permission issues, and provides a solution for manual configuration reloading. ```python # 手動重新載入 config = ConfigManager() config.reload_config() ``` -------------------------------- ### Core CLI Interface Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md The main CLI interface for the yaml2py tool, built using the Click framework. It handles argument parsing, validation, and auto-discovery of YAML files. ```python # yaml2py/cli.py # Main CLI interface using Click framework # Commands: generate (default command) # Entry points: `yaml2py` and `yml2py` (both work) # Handles argument parsing and validation # Smart auto-discovery of YAML files in common locations ``` -------------------------------- ### 一鍵測試腳本 Source: https://github.com/joneshong/yaml2py/blob/main/examples/env_support/README.md 執行提供的 shell 腳本以自動化整個測試流程。 ```bash ./run_test.sh ``` -------------------------------- ### 安裝 yaml2py Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 提供使用 pip 或從原始碼安裝 yaml2py 的說明。 ```bash pip install yaml2py ``` ```bash git clone https://github.com/yourusername/yaml2py.git cd yaml2py pip install -e . ``` ```bash # 安裝開發相依套件 pip install -e .[dev] # 或使用 make make install-dev ``` -------------------------------- ### 在 Python 程式碼中使用生成的配置類別 Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md 演示如何在 Python 應用程式中導入並使用 yaml2py 生成的配置類別,包括存取巢狀屬性、列表和安全列印配置。 ```python from src.config import ConfigManager # 獲取單例實例 config = ConfigManager() # 使用型別安全的屬性存取 print(f"應用程式:{config.app.name} v{config.app.version}") print(f"偵錯模式:{config.app.debug}") # bool 型別 print(f"伺服器埠號:{config.server.port}") # int 型別 print(f"逾時設定:{config.server.timeout}") # float 型別 # 存取巢狀結構 print(f"資料庫:{config.database.engine}") print(f"連接池大小:{config.database.pool.size}") # 處理列表資料 for feature in config.features: if feature.enabled: print(f"已啟用功能:{feature.name}") print(f" Session 逾時:{feature.config.session_timeout}") # 安全地顯示配置(自動遮罩敏感資料) config.database.print_all() # 輸出: # DatabaseSchema: # ---------------------------------------- # engine: postgresql # host: localhost # port: 5432 # name: myapp_db # user: admin # password: se*****23 # 自動遮罩! # ---------------------------------------- ``` -------------------------------- ### Project Dependencies Source: https://github.com/joneshong/yaml2py/blob/main/CLAUDE.md Lists the required Python versions and external libraries for the yaml2py project. ```python # Python >=3.8 required # Dependencies: click>=8.0, watchdog>=2.1.6, pyyaml>=6.0 ``` -------------------------------- ### Troubleshooting: File Not Found Error Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Addresses the `FileNotFoundError` when yaml2py cannot locate the configuration file, providing solutions like specifying the path explicitly or placing the file in standard locations. ```bash # 明確指定路徑 yaml2py --config /path/to/config.yaml --output ./output # 或將配置放在標準位置 mkdir config mv myconfig.yaml config/config.yaml ``` -------------------------------- ### Code Quality Checks Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Commands for maintaining code quality, including linting, formatting, security checks, and running the full CI pipeline. ```bash # Run linting make lint # Auto formatting make format # Security check make security-check # Full CI process make ci ``` -------------------------------- ### Debugging: Validating YAML Syntax Source: https://github.com/joneshong/yaml2py/blob/main/docs/USER_GUIDE_zh-TW.md Shows how to use Python's `PyYAML` library to validate the syntax of a YAML configuration file. ```python import yaml yaml.safe_load(open('config.yaml')) ```