diff --git a/docs/js/web-generator-strings/zh.json b/docs/js/web-generator-strings/zh.json index 53b82552..64af868d 100644 --- a/docs/js/web-generator-strings/zh.json +++ b/docs/js/web-generator-strings/zh.json @@ -14,7 +14,7 @@ "installation_link": "安装指南", "error_details": "技术详情", "field_name": "项目名称", - "field_name_help": "可使用字母、数字、下划线和连字符,同时也是 zip 内的文件夹名称。", + "field_name_help": "可使用字母、数字、下划线和连字符。它也是 zip 文件中的文件夹名称。", "name_empty": "请输入项目名称。", "name_characters": "只能使用字母、数字、下划线(_)和连字符(-),不能包含空格。", "name_digit": "名称不能以数字开头。", @@ -24,7 +24,7 @@ "field_level_help": "从小处开始:每提高一个级别,项目就多一层结构。", "field_database": "数据库", "customise_summary": "自定义功能和项目详情", - "customise_help": "保持折叠时,项目使用该级别的默认设置,相当于在命令行中对自定义提问回答“否”。", + "customise_help": "保持折叠时,项目使用该级别的默认设置,相当于在命令行中对是否自定义的提问回答“No”。", "features_legend": "功能", "deployment_legend": "部署", "project_legend": "项目详情", @@ -56,7 +56,7 @@ "generate": "生成并下载", "generating": "正在生成…", "generate_wait": "Python 加载完成后才能生成。", - "generate_fix": "请修正标记的字段,然后生成项目。", + "generate_fix": "请先修正已标记的字段,再生成项目。", "generated": "已下载 {filename}({count} 个文件)。", "download_again": "再次下载", "result_heading": "项目已就绪", diff --git a/docs/zh/contributing/code-guidelines.md b/docs/zh/contributing/code-guidelines.md deleted file mode 100644 index 2a90636d..00000000 --- a/docs/zh/contributing/code-guidelines.md +++ /dev/null @@ -1,748 +0,0 @@ -# 代码规范 - -为参与 FastAPI-fastkit 贡献而准备的完整编码标准与最佳实践。 - -## 总览 - -这些规范用于保证 FastAPI-fastkit 项目在代码质量、一致性与可维护性上的水准。遵循这些标准,可以让代码库更易于阅读、维护与扩展。 - -## Python 代码风格 - -### PEP 8 一致性 - -遵循 [PEP 8](https://www.python.org/dev/peps/pep-0008/),并按以下具体约定: - -- **行宽**:88 字符(Black 默认) -- **缩进**:4 空格(不要使用 tab) -- **末尾逗号**:多行结构必须保留末尾逗号 -- **字符串引号**:优先使用双引号 - -### 代码格式化 - -我们使用 **Black** 进行自动格式化: - -```python -# Good ✅ -def create_project( - name: str, - template: str, - options: Dict[str, Any], -) -> ProjectResult: - """Create a new FastAPI project.""" - return ProjectResult(name=name, template=template) - -# Bad ❌ -def create_project(name: str, template: str, options: Dict[str,Any])->ProjectResult: - """Create a new FastAPI project.""" - return ProjectResult(name=name,template=template) -``` - -### Import 组织 - -使用 **isort** 组织 import: - -```python -# Standard library imports -import os -import sys -from pathlib import Path -from typing import Dict, List, Optional, Union - -# Third-party imports -import click -import pydantic -from fastapi import FastAPI - -# Local imports -from fastapi_fastkit.commands import BaseCommand -from fastapi_fastkit.utils import validation -from fastapi_fastkit.templates.manager import TemplateManager -``` - -## 类型注解 - -### 必备的类型注解 - -所有公共函数与方法必须带有类型注解: - -```python -# Good ✅ -def validate_project_name(name: str) -> bool: - """Validate project name format.""" - return name.isidentifier() and not name.startswith('_') - -def create_files( - files: List[Path], - template_data: Dict[str, Any] -) -> List[Path]: - """Create files from template data.""" - created_files = [] - for file_path in files: - # Implementation... - created_files.append(file_path) - return created_files - -# Bad ❌ -def validate_project_name(name): - return name.isidentifier() and not name.startswith('_') -``` - -### 复杂类型注解 - -对复杂结构使用合适的类型注解: - -```python -from typing import Dict, List, Optional, Union, Tuple, Any -from pathlib import Path - -# Type aliases for complex types -ProjectConfig = Dict[str, Union[str, bool, List[str]]] -FileMapping = Dict[Path, str] -ValidationResult = Tuple[bool, Optional[str]] - -def process_template( - template_path: Path, - config: ProjectConfig, - output_dir: Optional[Path] = None, -) -> ValidationResult: - """Process template with configuration.""" - # Implementation... - return True, None -``` - -## 命名约定 - -### 变量与函数 - -- 变量与函数使用 **snake_case** -- 名称应**有描述性**,清晰表达用途 -- **避免缩写**,除非该缩写已被广泛接受 - -```python -# Good ✅ -project_name = "my-api" -template_directory = Path("templates") -user_input_data = get_user_input() - -def validate_email_address(email: str) -> bool: - """Validate email address format.""" - return "@" in email and "." in email - -# Bad ❌ -proj_nm = "my-api" -temp_dir = Path("templates") -usr_data = get_input() - -def validate_email(e): - return "@" in e and "." in e -``` - -### 类 - -- 类名使用 **PascalCase** -- 名称要**具体且具描述性** - -```python -# Good ✅ -class SomeClass: - """Represents example class of FastAPI-fastkit.""" - pass - -class SomeClassValidationError(Exception): - """Raised when example class validation fails.""" - pass - -class UserInputHandler: - """Handles user input validation and processing.""" - pass - -# Bad ❌ -class Class: - pass - -class Error(Exception): - pass - -class Handler: - pass -``` - -### 常量 - -- 使用带下划线的 **UPPER_CASE** -- 仅在**模块级**定义常量 - -```python -# Good ✅ -DEFAULT_TEMPLATE_NAME = "fastapi-default" -MAX_PROJECT_NAME_LENGTH = 50 -SUPPORTED_PYTHON_VERSIONS = ["3.8", "3.9", "3.10", "3.11", "3.12"] - -# Bad ❌ -default_template = "fastapi-default" -maxLength = 50 -versions = ["3.8", "3.9", "3.10", "3.11", "3.12"] -``` - -## 文档标准 - -### Docstring - -所有公共 API 使用 **Google 风格 docstring**: - -```python -def create_project_structure( - project_name: str, - template_path: Path, - output_directory: Optional[Path] = None, - overwrite: bool = False, -) -> List[Path]: - """Create project structure from template. - - Creates a new FastAPI project structure by copying and processing - template files. Supports variable substitution and file customization. - - Args: - project_name: Name of the project to create. Must be a valid - Python identifier. - template_path: Path to the template directory containing - source files and configuration. - output_directory: Directory where project will be created. - Defaults to current working directory. - overwrite: Whether to overwrite existing files. If False, - raises error when files exist. - - Returns: - List of created file paths in order of creation. - - Raises: - ValueError: If project_name is invalid or empty. - FileExistsError: If output directory exists and overwrite is False. - TemplateNotFoundError: If template_path doesn't exist. - PermissionError: If insufficient permissions to create files. - - Example: - ```python - template_path = Path("templates/fastapi-default") - created_files = create_project_structure( - project_name="my-api", - template_path=template_path, - output_directory=Path("./projects"), - overwrite=False - ) - print(f"Created {len(created_files)} files") - ``` - """ - # Implementation here... - pass -``` - -### 注释 - -- **解释 WHY,而不是 WHAT** -- **节制使用** —— 代码本身应具有自解释性 -- 代码改动后**同步更新注释** - -```python -# Good ✅ -def validate_dependencies(requirements: List[str]) -> bool: - """Validate project dependencies.""" - # Skip validation in development mode to allow experimental packages - if os.getenv("FASTKIT_DEV_MODE"): - return True - - # Check each requirement against known security vulnerabilities - for requirement in requirements: - if is_vulnerable_package(requirement): - return False - - return True - -# Bad ❌ -def validate_dependencies(requirements: List[str]) -> bool: - """Validate project dependencies.""" - # Check if dev mode - if os.getenv("FASTKIT_DEV_MODE"): - return True - - # Loop through requirements - for requirement in requirements: - # Check if vulnerable - if is_vulnerable_package(requirement): - return False - - # Return true - return True -``` - -## 错误处理 - -### 异常处理 - -- 尽量**捕获具体异常** -- **提供有意义的错误信息** -- **合理地记录错误日志** - -```python -# Good ✅ -def load_template_config(template_path: Path) -> Dict[str, Any]: - """Load template configuration from file.""" - config_file = template_path / "template.yaml" - - try: - with open(config_file, 'r') as f: - return yaml.safe_load(f) - except FileNotFoundError: - raise TemplateNotFoundError( - f"Template configuration not found: {config_file}" - ) - except yaml.YAMLError as e: - raise TemplateConfigError( - f"Invalid YAML syntax in {config_file}: {e}" - ) - except PermissionError: - raise TemplateAccessError( - f"Permission denied reading {config_file}" - ) - -# Bad ❌ -def load_template_config(template_path: Path) -> Dict[str, Any]: - """Load template configuration from file.""" - config_file = template_path / "template.yaml" - - try: - with open(config_file, 'r') as f: - return yaml.safe_load(f) - except Exception as e: - raise Exception(f"Error loading config: {e}") -``` - -### 自定义异常 - -为不同错误场景定义具体的异常类: - -```python -class FastKitError(Exception): - """Base exception for FastAPI-fastkit errors.""" - pass - -class ProjectCreationError(FastKitError): - """Raised when project creation fails.""" - pass - -class TemplateNotFoundError(FastKitError): - """Raised when template is not found.""" - pass - -class ValidationError(FastKitError): - """Raised when input validation fails.""" - - def __init__(self, message: str, field: str = None): - super().__init__(message) - self.field = field -``` - -## 测试标准 - -### 测试结构 - -测试要有清晰的结构与命名: - -```python -class TestProjectCreation: - """Test project creation functionality.""" - - def test_create_project_with_valid_name(self, tmp_path): - """Test project creation with valid project name.""" - project_name = "test-project" - result = create_project(project_name, template="minimal", output=tmp_path) - - assert result.success is True - assert (tmp_path / project_name).exists() - assert (tmp_path / project_name / "src" / "main.py").exists() - - def test_create_project_with_invalid_name(self): - """Test project creation fails with invalid name.""" - with pytest.raises(ValueError, match="Invalid project name"): - create_project("invalid-project-name!", template="minimal") - - def test_create_project_overwrites_existing(self, tmp_path): - """Test project creation overwrites existing directory when forced.""" - project_name = "existing-project" - project_dir = tmp_path / project_name - project_dir.mkdir() - - result = create_project( - project_name, - template="minimal", - output=tmp_path, - overwrite=True - ) - - assert result.success is True - assert project_dir.exists() -``` - -### 测试覆盖率 - -- 对新代码,**目标覆盖率 90% 以上** -- **覆盖边界情况**与异常路径 -- 对外部依赖使用 **mock** - -```python -def test_template_download_with_network_error(mock_requests): - """Test template download handles network errors gracefully.""" - mock_requests.get.side_effect = requests.ConnectionError("Network unreachable") - - with pytest.raises(TemplateDownloadError, match="Network error"): - download_template("https://example.com/template.zip") - -def test_file_creation_with_permission_error(mock_open): - """Test file creation handles permission errors.""" - mock_open.side_effect = PermissionError("Permission denied") - - with pytest.raises(FileCreationError, match="Permission denied"): - create_file(Path("/restricted/file.py"), content="test") -``` - -## Import 规范 - -### Import 组织 - -!!! note - - `isort` 格式化器会自动组织 import,只需运行 `bash scripts/format.sh` 即可。 - -1. **标准库** import 在最前 -2. **第三方** import 在中间 -3. **本地应用** import 在最后 -4. 每组之间用**空行**分隔 - -```python -# Standard library -import os -import sys -from pathlib import Path -from typing import Dict, List, Optional - -# Third-party -import click -import pydantic -import yaml -from fastapi import FastAPI - -# Local application -from fastapi_fastkit.commands.base import BaseCommand -from fastapi_fastkit.utils.validation import validate_project_name -from fastapi_fastkit.templates import TemplateManager -``` - -### Import 最佳实践 - -- **避免通配 import**(`from module import *`) -- 使用**绝对 import**,保持清晰 -- 当需要导入许多项时,**优先导入模块本身** - -```python -# Good ✅ -from fastapi_fastkit.utils import validation, files, formatting - -# Good ✅ (when importing few items) -from fastapi_fastkit.utils.validation import validate_email, validate_project_name - -# Bad ❌ -from fastapi_fastkit.utils.validation import * - -# Bad ❌ (when importing many items) -from fastapi_fastkit.utils.validation import ( - validate_email, validate_project_name, validate_template_name, - validate_dependencies, validate_python_version, validate_directory -) -``` - -## 安全规范 - -### 输入校验 - -始终对用户输入进行校验与净化: - -```python -def validate_project_name(name: str) -> str: - """Validate and sanitize project name.""" - if not name: - raise ValueError("Project name cannot be empty") - - if not name.isidentifier(): - raise ValueError("Project name must be a valid Python identifier") - - if name.startswith('_'): - raise ValueError("Project name cannot start with underscore") - - if len(name) > 50: - raise ValueError("Project name too long (max 50 characters)") - - # Sanitize by removing dangerous characters - sanitized = re.sub(r'[^a-zA-Z0-9_-]', '', name) - - return sanitized -``` - -### 文件操作 - -谨慎处理文件路径与文件操作: - -```python -def create_file_safely(file_path: Path, content: str, base_dir: Path) -> None: - """Create file safely within base directory.""" - # Resolve to prevent directory traversal attacks - resolved_path = file_path.resolve() - resolved_base = base_dir.resolve() - - # Ensure file is within base directory - try: - resolved_path.relative_to(resolved_base) - except ValueError: - raise SecurityError(f"File path outside base directory: {file_path}") - - # Create parent directories safely - resolved_path.parent.mkdir(parents=True, exist_ok=True) - - # Write file with appropriate permissions - resolved_path.write_text(content, encoding='utf-8') - resolved_path.chmod(0o644) # Read/write for owner, read for others -``` - -## 性能规范 - -### 高效的代码写法 - -- 对大数据集**使用生成器** -- **避免过早优化** -- **先剖析,再优化** - -```python -# Good ✅ - Generator for memory efficiency -def process_large_template(template_files: List[Path]) -> Iterator[ProcessedFile]: - """Process template files efficiently.""" - for file_path in template_files: - content = file_path.read_text() - processed_content = process_template_content(content) - yield ProcessedFile(path=file_path, content=processed_content) - -# Bad ❌ - Loads everything into memory -def process_large_template(template_files: List[Path]) -> List[ProcessedFile]: - """Process template files.""" - results = [] - for file_path in template_files: - content = file_path.read_text() - processed_content = process_template_content(content) - results.append(ProcessedFile(path=file_path, content=processed_content)) - return results -``` - -### 缓存 - -对开销大的操作使用缓存: - -```python -from functools import lru_cache - -@lru_cache(maxsize=128) -def get_template_metadata(template_path: Path) -> TemplateMetadata: - """Get template metadata with caching.""" - config_file = template_path / "template.yaml" - - if not config_file.exists(): - return TemplateMetadata(name=template_path.name) - - config = yaml.safe_load(config_file.read_text()) - return TemplateMetadata.from_config(config) -``` - -## Git 提交规范 - -### 提交信息格式 - -使用约定式提交(Conventional Commits)格式: - -``` -type(scope): description - -[optional body] - -[optional footer] -``` - -### 提交类型 - -- **feat**:新特性 -- **fix**:bug 修复 -- **docs**:文档相关改动 -- **style**:代码风格改动(格式化等) -- **refactor**:代码重构 -- **test**:增加或调整测试 -- **chore**:维护性任务 - -### 示例 - -```bash -# Good ✅ -feat(cli): add template validation command - -Add new command to validate template structure and configuration. -The command checks for required files, validates YAML syntax, -and ensures template follows conventions. - -Closes #123 - -# Good ✅ -fix(templates): handle missing dependency files gracefully - -When a template references a requirements file that doesn't exist, -show a clear error message instead of crashing. - -# Bad ❌ -update stuff - -# Bad ❌ -Fixed bug -``` - -## 代码评审规范 - -### 对作者而言 - -提交评审前请确认: - -1. **运行全部测试**,且全部通过 -2. **核查测试覆盖率**未下滑 -3. **必要时更新文档** -4. **遵循提交信息**规范 -5. **保持 PR 聚焦且小** - -### 对评审者而言 - -评审时请关注: - -1. **功能是否正确** —— 行为是否符合预期? -2. **测试是否完善** —— 是否覆盖边界情况? -3. **文档是否同步** —— 描述是否清晰、最新? -4. **代码风格** —— 是否遵循项目约定? -5. **是否考虑安全** —— 是否存在潜在漏洞? - -### 评审清单 - -- [ ] 代码符合风格规范 -- [ ] 测试齐备且全部通过 -- [ ] 文档已更新 -- [ ] 无安全漏洞 -- [ ] 已考虑性能问题 -- [ ] 错误处理得当 -- [ ] 提交信息符合规范 - -## 工具与自动化 - -### Pre-commit 钩子 - -我们使用 pre-commit 钩子来强制执行标准: - -```yaml -# .pre-commit-config.yaml -repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v6.0.0 - hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: check-yaml - - id: check-toml - -- repo: local - hooks: - - id: format - name: format - entry: black --config pyproject.toml --check . - language: python - types: [python] - additional_dependencies: ['black>=24.10.0'] - pass_filenames: false - - - id: isort-check - name: isort check - entry: isort --sp pyproject.toml --check-only --diff . - language: python - types: [python] - additional_dependencies: ['isort>=5.13.2'] - pass_filenames: false - - - id: isort-fix - name: isort fix - entry: isort --sp pyproject.toml . - language: python - types: [python] - additional_dependencies: ['isort>=5.13.2'] - pass_filenames: false - - - id: black-fix - name: black fix - entry: black --config pyproject.toml . - language: python - types: [python] - additional_dependencies: ['black>=24.10.0'] - pass_filenames: false - - - id: mypy - name: mypy - entry: mypy --config-file pyproject.toml src - language: python - types: [python] - additional_dependencies: - - mypy>=1.12.0 - - rich>=13.9.2 - - click>=8.1.7 - - pyyaml>=6.0.0 - - types-PyYAML>=6.0.12 - pass_filenames: false - -ci: - autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks - autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate -``` - -!!! note - - Pre-commit 钩子使用隔离的 Python 环境(`language: python`)。 - -### IDE 配置 - -推荐的 VS Code 设置: - -```json -{ - "python.linting.enabled": true, - "python.linting.mypyEnabled": true, - "python.formatting.provider": "black", - "python.sortImports.path": "isort", - "editor.formatOnSave": true, - "editor.codeActionsOnSave": { - "source.organizeImports": true - } -} -``` - -## 下一步 - -读完这些规范后: - -1. **配置开发环境**,参见 [开发环境配置](development-setup.md) -2. **从小贡献开始练手**,熟悉流程 -3. **在 GitHub Discussions 提问**,有不明之处随时问 -4. **阅读已有代码**,看看这些规范在实践中的样子 - -!!! tip "速查" - - 用 `make check-all` 验证您的代码是否满足全部规范 - - 配置 pre-commit 钩子,尽早发现问题 - - 拿不准时,看现有代码作为示例 - - 评审中遇到问题,不要犹豫,主动求助 - -遵循这些规范有助于让 FastAPI-fastkit 保持高水准的代码质量,并让所有人协作起来更轻松!🚀 diff --git a/docs/zh/contributing/development-setup.md b/docs/zh/contributing/development-setup.md index 420961d5..0c80a2ee 100644 --- a/docs/zh/contributing/development-setup.md +++ b/docs/zh/contributing/development-setup.md @@ -1,838 +1,161 @@ -# 开发环境配置 +# 开发环境搭建 -为参与 FastAPI-fastkit 贡献而准备开发环境的完整指南。 +本页介绍如何搭建 FastAPI-fastkit 仓库的开发环境、运行测试和检查、遵守代码规则、构建包含网页生成器的文档,以及准备发布。拉取请求的流程请阅读仓库中的 `CONTRIBUTING.md`。 -## 前置条件 +## 环境要求 -开始之前,请确认您已具备: +- Python 3.12 或更高版本(`requires-python = ">=3.12"`)。 +- git。 +- CI 工作流使用的 PDM,或者 uv。也可以使用 pip。 +- Node.js(CI 使用 22 版),仅在比较网页生成器与命令行的输出时需要。 -- 已安装 **Python 3.12 及以上** -- 已安装并配置 **Git** -- 具备 **Python 与 FastAPI 的基础知识** -- 一个 **文本编辑器或 IDE**(VS Code、PyCharm 等) +## 安装 -## 借助 Makefile 快速配置 - -FastAPI-fastkit 提供了用于简化开发环境配置的 Makefile: - -
+克隆仓库,并以可编辑模式安装 fastkit 及其开发工具: ```console $ git clone https://github.com/bnbong/FastAPI-fastkit.git $ cd FastAPI-fastkit -$ make install-dev -Setting up development environment... -Creating virtual environment... -Installing dependencies... -Installing pre-commit hooks... -✅ Development environment ready! -``` - -
- -这一条命令会: - -- 以可编辑模式安装包及其开发依赖 -- 安装 pre-commit 钩子 -- 配置开发工具 - -!!! note - - 在运行该命令前,建议先创建并激活虚拟环境。 - -## 手动配置 - -如果您倾向于手动配置,或 Makefile 在您的系统上无法正常工作: - -### 1. 克隆仓库 - -
- -```console -$ git clone https://github.com/bnbong/FastAPI-fastkit.git -$ cd FastAPI-fastkit -``` - -
- -### 2. 创建虚拟环境 - -
- -```console -$ python -m venv .venv -$ source .venv/bin/activate # On Windows: .venv\Scripts\activate -``` - -
- -### 3. 安装依赖 - -
- -```console -# Install package in editable mode with development dependencies -$ pip install -e ".[dev]" - -# Or install from requirements files -$ pip install -r requirements.txt -$ pip install -r requirements-dev.txt +$ pdm install -G dev -G test-runtime +$ pdm run pre-commit install ``` -
+使用 uv 时,运行 `uv sync --extra dev --group test-runtime`。使用 pip 时,先创建并激活虚拟环境,再运行 `make dev-setup`:它会升级 pip,用 `pip install -e ".[dev]"` 安装 fastkit,从 `requirements-docs.txt` 安装文档所需的依赖,并运行 `pre-commit install`。如果要运行运行时测试,再执行 `pip install --group test-runtime`(需要 pip 25.1 或更高版本)。 -### 4. 配置 pre-commit 钩子 +开发工具在 `pyproject.toml` 和两个锁文件中的版本相同:black 26.10.1、isort 9.0.1、mypy 2.3.1 和 ruff 0.17.6。pre-commit 钩子也把 black、isort 和 mypy 固定在相同的版本。拉取最新代码后,用 `pdm sync -G dev --clean`(或 `uv sync --extra dev`)让你的环境与之保持一致。 -
+启动生成的应用的那些测试需要 FastAPI 和另外几个包,这些包由 `test-runtime` 依赖组提供;缺少它们时,这些测试会被跳过。CI 用 `pdm install -G dev -G test-runtime` 安装该依赖组;在本地,你可以使用 `pdm sync -G dev -G test-runtime --clean`、`uv sync --extra dev --group test-runtime` 或 `pip install --group test-runtime`(需要 pip 25.1 或更高版本)。 -```console -$ pre-commit install -pre-commit installed at .git/hooks/pre-commit -``` - -
- -### 5. 验证安装 +## 运行测试 -
+在仓库根目录运行 `pytest` 即可执行整个测试套件(`testpaths = ["tests"]`)。标记为 `extended` 的测试是较慢的端到端测试,反复修改代码期间可以先排除它们: ```console -$ fastkit --version -fastapi-fastkit, version 1.2.1 - -$ python -m pytest tests/ -======================== test session starts ======================== -collected 45 items -tests/test_cli.py::test_init_command PASSED -tests/test_templates.py::test_template_listing PASSED -... -======================== 45 passed in 2.34s ======================== +$ pdm run pytest -m "not extended" +$ pdm run pytest tests/test_docs -q ``` -
- -## 开发工具 - -开发环境包含多种工具,用于维护代码质量: - -### 一行命令 +`make test` 运行 `pytest`;`make test-coverage` 在运行时统计覆盖率(`--cov-fail-under=80`),并生成 `htmlcov/` 和 `coverage.xml`。Test and Coverage 工作流在 Ubuntu 上用 Python 3.12、3.13 和 3.14 运行测试套件,在 Windows 上用 Python 3.12 和 3.14 运行。另一个作业会把隐式文本编码视为错误来运行测试套件,并在非 UTF-8 的 C locale 下再运行一次。 -使用 Makefile: +## 检查 ```console -$ make format lint -Running isort... -Running black... -Running mypy... -✅ All checks passed! -``` - -使用项目自带脚本: - -```console -$ ./scripts/format.sh -$ ./scripts/lint.sh -``` - -### 代码格式化 - -**Black** —— 代码格式化器: - -
- -```console -$ black src/ tests/ -reformatted src/main.py -reformatted tests/test_cli.py +$ make lint +Running isort check... +isort --sp pyproject.toml --check . +Skipped 5 files +Running black check... +black --config pyproject.toml --check . All done! ✨ 🍰 ✨ +253 files would be left unchanged. +Running mypy check... +mypy --config-file pyproject.toml src +Success: no issues found in 98 source files ``` -
- -**isort** —— import 排序: - -
- -```console -$ isort src/ tests/ -Fixing import order in src/main.py -``` - -
- -### 代码静态检查 - -**mypy** —— 类型检查: - -
- -```console -$ mypy src/ -Success: no issues found in 12 source files -``` - -
- -## 可用的 Make 命令 - -项目的 Makefile 为常见的开发任务提供了便捷命令: - -### 安装命令 - -| 命令 | 描述 | -|---------|-------------| -| `make install` | 以生产模式安装包 | -| `make install-dev` | 以包含开发依赖的方式安装包 | -| `make install-test` | 为测试用途安装包(卸载并重新安装) | -| `make uninstall` | 卸载包 | -| `make clean` | 清理构建产物与缓存文件 | - -### 代码质量命令 - -| 命令 | 描述 | -|---------|-------------| -| `make format` | 使用 black 与 isort 格式化代码 | -| `make format-check` | 检查代码格式,但不做修改 | -| `make lint` | 运行所有静态检查(isort、black、mypy) | - -### 测试命令 - -| 命令 | 描述 | -|---------|-------------| -| `make test` | 运行全部测试 | -| `make test-verbose` | 以详细模式运行测试 | -| `make test-coverage` | 运行测试并生成覆盖率报告 | -| `make coverage-report` | 生成详细的覆盖率报告(FORMAT=html/xml/json/all) | - -### 模板检查命令 - -| 命令 | 描述 | -|---------|-------------| -| `make inspect-templates` | 对所有模板执行模板检查 | -| `make inspect-templates-verbose` | 以详细输出运行模板检查 | -| `make inspect-template` | 检查指定模板(TEMPLATES 参数) | - -迭代开发时,底层脚本有三个值得了解的选项:`--offline`(跳过 PyPI 版本新鲜度查询)、`--no-smoke`(跳过用 uvicorn 启动生成项目这一最慢的步骤)以及 `--mypy`(对生成项目进行类型检查;由于速度较慢,需要显式开启)。每项检查具体做什么,请参阅 [模板质量保障](../reference/template-quality-assurance.md)。 - -```console -$ python scripts/inspect-templates.py --templates fastapi-sqlmodel --offline --no-smoke -``` - -### 生成的代码存放在 Jinja2 片段中 - -`fastkit init --interactive` 写入项目的所有内容 —— `main.py`、数据库与认证模块、Docker 文件、pytest 配置 —— 都是由 `src/fastapi_fastkit/fragments/` 下的模板渲染而成,而不是在 Python 中拼接字符串得到的。`main.py.j2` 不硬编码任何功能:它遍历由 `DynamicConfigGenerator` 提供的 `import_fragments`、`lifespan_fragments` 和 `setup_fragments` 列表,并逐一包含,因此各项功能可以自由组合。 - -添加一个功能的大致步骤: - -1. 把各部分放入 `main/imports/`、`main/lifespan/` 和/或 `main/setup/`(lifespan 片段缩进四个空格;另外两种不缩进)。 -2. 在 `DynamicConfigGenerator._main_fragments()` 中注册它们,并以相应的配置查询作为条件。 -3. 对于独立模块,添加 `/.py.j2`,并用 `self._render(...)` 渲染。 -4. 扩展 `tests/test_backends/test_project_builder_config_generator.py` 中的组合矩阵 —— 它会断言每个渲染出的 Python 文件都能被 `ast.parse` 解析。 - -有两个容易踩坑的约束:每个片段都必须以换行符结尾(环境以 `keep_trailing_newline=True` 构建),并且 `main.py.j2` 必须保留 `# fastkit:imports` / `# fastkit:routes` 锚点 —— `fastkit addroute` 会在这些位置插入代码。 - -权威的操作流程与片段本身放在一起,位于 [`src/fastapi_fastkit/fragments/README.md`](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fragments/README.md)。 - -### 文档命令 - -| 命令 | 描述 | -|---------|-------------| -| `make serve-docs` | 在本地启动文档服务 | -| `make build-docs` | 构建文档 | - -### 翻译命令 - -| 命令 | 描述 | -|---------|-----------| -| `make translate` | 翻译文档(LANG、PROVIDER、MODEL 参数) | - -### 示例 - -
- -```console -# Format code and run all checks -$ make format lint -Running isort... -Running black... -Running mypy... -✅ All checks passed! - -# Run tests with coverage -$ make test-coverage -======================== test session starts ======================== -collected 45 items -tests/test_cli.py::test_init_command PASSED -... -======================== 45 passed in 2.34s ======================== - ----------- coverage: platform darwin, python 3.12.1-final-0 ---------- -Name Stmts Miss Cover --------------------------------------------- -src/main.py 45 2 96% -src/cli.py 89 5 94% -src/templates.py 67 3 96% --------------------------------------------- -TOTAL 201 10 95% - -# Generate HTML coverage report -$ make coverage-report FORMAT=html -🌐 Opening HTML coverage report in browser... - -# Translate documentation to Korean -$ make translate LANG=ko PROVIDER=github MODEL=gpt-4o-mini -Starting translation... -Running: python scripts/translate.py --target-lang ko --api-provider github --model gpt-4o-mini -``` - -
- -## 项目结构 - -理解项目结构对开发工作至关重要: - -```bash -FastAPI-fastkit/ -├── src/ -│ ├── fastapi_fastkit/ -│ │ ├── __main__.py # Entry point of the application -│ │ ├── backend/ -│ │ │ ├── inspector.py # FastAPI-fastkit template inspector -│ │ │ ├── interactive/ -│ │ │ │ ├── config_builder.py # Configuration builder for interactive mode -│ │ │ │ ├── prompts.py # Prompts for interactive mode -│ │ │ │ ├── selectors.py # Selectors logic for interactive mode -│ │ │ │ └── validators.py # User input validators for interactive mode -│ │ │ ├── main.py # Backend's logic entry point -│ │ │ ├── package_managers/ -│ │ │ │ ├── base.py # Base class for package managers -│ │ │ │ ├── factory.py # Factory for package managers -│ │ │ │ ├── pdm_manager.py # PDM package manager -│ │ │ │ ├── pip_manager.py # pip package manager -│ │ │ │ ├── poetry_manager.py # Poetry package manager -│ │ │ │ └── uv_manager.py # uv package manager -│ │ │ ├── project_builder/ -│ │ │ │ ├── config_generator.py # Configuration generator for project builder -│ │ │ │ └── dependency_collector.py # Dependency collector for project builder -│ │ │ └── transducer.py # Transducer for project builder -│ │ ├── cli.py # FastAPI-fastkit main CLI entry point -│ │ ├── core/ -│ │ │ ├── exceptions.py # Exception handling -│ │ │ └── settings.py # Settings configuration -│ │ ├── fastapi_project_template/ -│ │ │ ├── PROJECT_README_TEMPLATE.md # fastkit template project base README file -│ │ │ ├── README.md # fastkit template README -│ │ │ ├── fastapi-custom-response/ -│ │ │ ├── fastapi-default/ -│ │ │ ├── fastapi-empty/ -│ │ │ ├── fastapi-hello/ -│ │ │ ├── fastapi-mcp/ -│ │ │ ├── fastapi-single-module/ -│ │ │ └── modules/ -│ │ │ ├── api/ -│ │ │ │ └── routes/ -│ │ │ ├── crud/ -│ │ │ └── schemas/ -│ │ ├── py.typed -│ │ └── utils/ -│ │ ├── logging.py # Logging configuration -│ │ └── main.py # FastAPI-fastkit main entry point -│ └── logs -├── tests -│ ├── conftest.py # pytest configuration -│ ├── test_backends/ -│ ├── test_cli_operations/ -│ ├── test_core.py -│ ├── test_rich/ -│ ├── test_templates/ -│ └── test_utils.py -├── uv.lock -├── docs/ # Documentation -├── scripts/ # Development scripts -├── mkdocs.yml -├── overrides/ # mkdocs overrides -├── pdm.lock -├── pyproject.toml -├── requirements-docs.txt # requirements for documentation -├── requirements.txt # requirements for development -├── CHANGELOG.md -├── CITATION.cff -├── CODE_OF_CONDUCT.md -├── CONTRIBUTING.md -├── LICENSE -├── MANIFEST.in -├── Makefile -├── README.md -├── SECURITY.md -└── env.example # environment example(configures translation AI model env vars) -``` - -### 关键目录 - -- **`src/fastapi_fastkit/`** —— 主包源码 - - **`cli.py`** —— 主 CLI 入口 - - **`backend/`** —— 核心后端逻辑 - - **`inspection/`** —— 模板检查流水线(context、checks、consistency、freshness、smoke、lint、report) - - **`inspector.py`** —— `inspection/` 之上的外观层(facade),为保留历史导入路径而存在 - - **`interactive/`** —— 交互模式相关组件(提示、选择器、校验器) - - **`package_managers/`** —— 包管理器实现(pip、uv、pdm、poetry) - - **`project_builder/`** —— 项目构建工具,包括由片段驱动的配置生成器 - - **`scaffolder.py`** —— `init` 与 `startdemo` 共用的生成流水线 - - **`transducer.py`** —— 模板 transducer - - **`core/`** —— 核心配置与异常 - - **`fragments/`** —— 渲染到生成项目中的 Jinja2 片段(见上文) - - **`fastapi_project_template/`** —— 项目模板(fastapi-default、fastapi-domain-starter 等) - - **`utils/`** —— 共享工具函数 -- **`tests/`** —— 测试套件 - - **`test_backends/`** —— 针对后端的测试 - - **`test_cli_operations/`** —— CLI 操作的测试 - - **`test_templates/`** —— 模板系统的测试 -- **`docs/`** —— 文档(MkDocs) - - 用户指南、教程与 API 参考 - -## 开发工作流 - -### 1. 创建特性分支 - -
- -```console -$ git checkout -b feature/add-new-template -Switched to a new branch 'feature/add-new-template' -``` - -
- -### 2. 进行改动 - -编辑代码、添加特性、修复 bug…… - -### 3. 运行测试与检查 - -
- -```console -$ make dev-check -Running all quality checks... -Running all tests... -✅ All tests passed! -``` - -
- -### 4. 提交改动 - -pre-commit 钩子会自动运行: - -
- -```console -$ git add . -$ git commit -m "Add new FastAPI template with authentication" -format...................................................................Passed -isort-check..............................................................Passed -black-fix................................................................Passed -mypy.....................................................................Passed -[feature/add-new-template abc1234] Add new FastAPI template with authentication -``` - -
- -### 5. 推送并创建 Pull Request - -
- -```console -$ git push origin feature/add-new-template -$ gh pr create --title "Add new FastAPI template with authentication" -``` - -
- -## 测试 - -### 运行测试 - -**全部测试:** - -
- -```console -$ make test -# or -$ python -m pytest -``` - -
- -**指定测试文件:** - -
- -```console -$ python -m pytest tests/test_cli.py -v -``` - -
- -**带覆盖率:** - -
- -```console -$ make test-coverage -# or -$ python -m pytest --cov=src --cov-report=html -``` - -
- -### 编写测试 - -新增特性时,务必同步编写测试: - -```python -# tests/test_commands/test_new_feature.py -import pytest -from fastapi_fastkit.commands.new_feature import NewFeatureCommand - -class TestNewFeatureCommand: - def test_command_success(self): - """Test successful command execution""" - command = NewFeatureCommand() - result = command.execute(valid_args) - assert result.success is True - assert result.message == "Feature executed successfully" - - def test_command_validation_error(self): - """Test command with invalid arguments""" - command = NewFeatureCommand() - with pytest.raises(ValueError, match="Invalid argument"): - command.execute(invalid_args) - - def test_command_edge_case(self): - """Test edge case handling""" - command = NewFeatureCommand() - result = command.execute(edge_case_args) - assert result.success is True - assert "warning" in result.message.lower() -``` - -### 测试分类 +| 命令 | 作用 | +| --- | --- | +| `make format` | 用 isort 整理导入顺序,并用 black 格式化代码。 | +| `make format-check` | 显示 `make format` 会做哪些修改,但不实际修改文件。 | +| `make lint` | 以检查模式运行 isort 和 black,然后运行 `mypy src`(严格模式)。 | +| `make dev-check` | 依次运行 `make format-check`、`make lint` 和 `make test`。 | +| `make dev-setup` | 用 pip 安装 fastkit 及其开发工具、文档所需的依赖和 pre-commit 钩子。 | +| `make help` | 列出所有目标。 | -**单元测试** —— 测试单个函数与类: +pre-commit 钩子运行同样的 isort、black 和 mypy 命令,此外还会检查行尾空白、文件末尾换行、YAML 和 TOML。 -```python -def test_validate_project_name(): - assert validate_project_name("valid-name") is True - assert validate_project_name("invalid name!") is False -``` - -**集成测试** —— 测试命令之间的交互: - -```python -def test_init_command_creates_project(tmp_path): - result = runner.invoke(cli, ['init'], input='test-project\n...') - assert result.exit_code == 0 - assert (tmp_path / "test-project").exists() -``` +## 代码规则 -**端到端测试** —— 测试完整的工作流: +- `src/fastapi_fastkit/` 下的代码(模板除外)通过 `src/fastapi_fastkit/utils/textio.py` 读写文本文件,该模块会设置 UTF-8 编码,并显式地保留或设置换行符。 +- 每次调用 `subprocess` 都要传入 `encoding="utf-8", errors="replace"`。 +- 平台差异(虚拟环境的 Windows 路径、可执行文件、控制台编码、文件删除)统一通过 `src/fastapi_fastkit/utils/platform.py` 处理。 +- 测试必须能在 Windows 上通过:不要写死 `/tmp`,预期路径不要用 `/` 拼接,`chmod` 相关的测试要标记为仅在 POSIX 上运行。要测试 Windows 分支,请 patch `src/fastapi_fastkit/utils/platform.py` 中的判断;绝不要 patch `os.name`。 +- 保留每个文件原有的换行符。 +- 新代码要附带针对其行为的测试。 -```python -def test_full_project_creation_workflow(tmp_path): - # Create project - result = runner.invoke(cli, ['init'], input='...') - assert result.exit_code == 0 +### 选项和生成的代码 - # Add route - result = runner.invoke(cli, ['addroute', 'test-project', 'users']) - assert result.exit_code == 0 +`fastkit init` 提供的选项、它们的依赖包以及选项之间的规则都来自 `src/fastapi_fastkit/catalog/catalog.toml`。新选项要加到该文件中对应的功能类别(axis)下,同时加到 `src/fastapi_fastkit/core/settings.py` 中对应的选项列表里;两者不一致时,`tests/test_catalog/test_agreement.py` 会失败。 - # Verify files exist - assert (tmp_path / "test-project" / "src" / "api" / "routes" / "users.py").exists() -``` +功能向项目添加的文件是 `src/fastapi_fastkit/fragments/` 下的 Jinja2 模板,绝不是在 Python 中拼接出来的字符串。`src/fastapi_fastkit/fragments/README.md` 说明了目录结构和添加功能的步骤。每个片段都以换行符结尾。 ## 文档 -### 在本地启动文档服务 - -
+本站用 MkDocs 和 Material 构建。先用 `pdm install -G docs` 或 `pip install -r requirements-docs.txt` 安装文档所需的依赖,再按 CI 的方式构建站点: ```console -$ make serve-docs -INFO - Building documentation... -INFO - Cleaning site directory -INFO - Documentation built in 0.43 seconds -INFO - [14:30:00] Serving on http://127.0.0.1:8000/ +$ mkdocs build --strict -d site ``` -
- -### 构建文档 - -
- -```console -$ make build-docs -INFO - Building documentation... -INFO - Documentation built in 0.43 seconds -``` - -
- -### 编写文档 - -文档使用 Markdown 编写,由 MkDocs 构建。以下是示例结构: - -**特性指南模板:** - -````markdown -# New Feature Guide - -This guide explains how to use the new feature. - -## Prerequisites - -- FastAPI-fastkit installed -- Basic Python knowledge - -## Usage - -
- -```console -$ fastkit new-feature --option value -✅ Feature executed successfully! -``` - -
- -!!! tip "Pro Tip" - Use `--help` to see all available options. -```` - -要了解 `mkdocs-material` 的详细参考,请查看 [mkdocs-material 文档](https://squidfunk.github.io/mkdocs-material/reference/admonitions/)。 - -## 代码风格指南 - -### Python 代码风格 +编辑期间,`make serve-docs` 会在 `http://127.0.0.1:8000/` 提供站点;`make build-docs` 构建时不加 `--strict`。英文页面位于 `docs/en/`;其他语言请参阅[翻译指南](translation-guide.md)。 -遵循 [PEP 8](https://www.python.org/dev/peps/pep-0008/),并附加以下具体约定: +### 生成块 -- **行宽**:88 字符(Black 默认) -- **import**:由 isort 组织 -- **类型注解**:所有公共函数都必须提供 -- **docstring**:所有公共 API 使用 Google 风格 +参考表格和帮助文本位于页面中的两行注释之间,由 catalog 和 CLI 渲染生成: -### 示例 - -```python -from typing import List, Optional -from pathlib import Path - -def create_project_structure( - project_name: str, - template_path: Path, - output_dir: Optional[Path] = None, -) -> List[Path]: - """Create project structure from template. - - Args: - project_name: Name of the project to create - template_path: Path to the template directory - output_dir: Output directory, defaults to current directory - - Returns: - List of created file paths - - Raises: - ValueError: If project_name is invalid - FileNotFoundError: If template_path doesn't exist - """ - if not project_name.isidentifier(): - raise ValueError(f"Invalid project name: {project_name}") - - if not template_path.exists(): - raise FileNotFoundError(f"Template not found: {template_path}") - - # Implementation here... - return created_files -``` - -## 环境变量 - -进行开发时,您可以设置以下环境变量: - -| 变量 | 描述 | 默认值 | -|----------|-------------|---------| -| `FASTKIT_DEBUG` | 启用调试日志 | `False` | -| `FASTKIT_DEV_MODE` | 启用开发模式特性 | `False` | -| `FASTKIT_TEMPLATE_DIR` | 自定义模板目录 | 内置模板 | -| `FASTKIT_CONFIG_DIR` | 配置目录 | `~/.fastkit` | -| `TRANSLATION_API_KEY` | 翻译 API key(使用 [Github AI 模型提供方](https://github.com/marketplace/models/azure-openai) 时填写 Github PAT) | `None` | - -
- -```console -$ export FASTKIT_DEBUG=true -$ export FASTKIT_DEV_MODE=true -$ fastkit init -DEBUG: Loading configuration from /home/user/.fastkit/ -DEBUG: Available templates: ['fastapi-default', ...] -``` - -
- -其他环境变量设置请参阅 [@settings.py](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/core/settings.py) 模块。 - -## 故障排查 - -### 常见问题 - -**1. pre-commit 钩子失败:** - -
- -```console -$ git commit -m "Fix bug" -black....................................................................Failed -hookid: black - -Files were modified by this hook. Additional output: - -would reformat src/cli.py -``` - -
- -**解决办法:** 运行格式化器后再次提交: - -
- -```console -$ make format -$ git add . -$ git commit -m "Fix bug" -``` - -
- -**2. 在不同 Python 版本上测试失败:** - -**解决办法:** 使用 tox 在多个 Python 版本上测试: - -
- -```console -$ pip install tox -$ tox -py38: commands succeeded -py39: commands succeeded -py310: commands succeeded -py311: commands succeeded -py312: commands succeeded +```markdown + +... + ``` -
- -**3. 开发时出现 import 错误:** - -**解决办法:** 以可编辑模式安装包: -
+绝不要编辑块内的内容。修改 catalog、某个命令的帮助文本或 doctor 检查之后,或者添加了一个块(两行注释,中间不留内容)之后,运行以下脚本: ```console -$ pip install -e . +$ python scripts/docs_blocks.py +$ python scripts/docs_blocks.py --check ``` -
- -### 获取帮助 - -- **[GitHub Issues](https://github.com/bnbong/FastAPI-fastkit/issues)**:报告 bug 与请求特性 -- **[GitHub Discussions](https://github.com/bnbong/FastAPI-fastkit/discussions)**:提问与分享想法 -- **文档**:查看 [用户指南](../user-guide/installation.md) +第一条命令会重写所有过期的块;`--check` 会列出过期的块,并以状态码 1 退出;加上 `--lang ko` 后,两者都只处理一种语言。只要还有过期的块,`tests/test_docs` 就会失败。 -## 贡献指南 +### 页面规则 -### 提交 PR 之前 +`tests/test_docs` 还会检查英文页面: -1. **运行所有检查:** `make dev-check` -2. **必要时更新文档** -3. **为新特性增加测试** -4. **遵循提交信息规范** +- `docs/en/` 下的每个页面都在 `mkdocs.yml` 的 `nav` 中,并且 `nav` 中的每个条目都存在。 +- 指向 FastAPI 文档的链接使用 catalog 中概念的地址(即生成的 `concepts` 块),或 `tests/test_docs/test_site_structure.py` 中列出的地址。 +- 不写拉取请求或 issue 的编号。 -### 提交信息格式 +在 ```` ```console ```` 块中,每条命令前都加上 `$ `,并且任何一行都不要以 `# ` 开头:复制按钮会把这样的行当作命令复制。请把注释写在命令后面。 -``` -type(scope): brief description - -Longer description if needed - -Fixes #123 -``` +### 移动或删除页面时 -**类型(type):** +把旧路径添加到 `scripts/mkdocs_hooks/redirects.py` 的 `REDIRECTS` 中,值为新地址。每次构建后,该钩子都会在旧地址上为每种语言写入一个页面,把读者引导到新地址。`tests/test_docs/test_redirects.py` 会检查旧路径不再作为页面存在,并且每个目标都存在。 -- `feat`:新特性 -- `fix`:bug 修复 -- `docs`:文档相关改动 -- `style`:代码风格改动 -- `refactor`:代码重构 -- `test`:增加 / 调整测试 -- `chore`:维护性任务 +### 网页生成器页面 -**示例:** +`docs/en/start/web-generator.md` 页面用 Pyodide 在浏览器中运行 fastkit。它加载的文件由 `scripts/web_generator/build_assets.py` 根据 fastkit 的 wheel 构建,因此在预览该页面之前要先构建这些文件。进行下文的比较需要 Node.js(CI 使用 22 版),还需要一个可以重新安装 fastkit 的虚拟环境,因为 wheel 会替换掉可编辑安装。 +```bash +python -m pip wheel --no-deps -w dist . +python -m pip install dist/fastapi_fastkit-*.whl +python scripts/web_generator/build_assets.py --wheel dist/fastapi_fastkit-*.whl \ + --out docs/en/assets/fastkit-generator +make serve-docs ``` -feat(cli): add new template command - -Add support for creating projects from custom templates. -The command accepts a template path and creates a new -project with the specified configuration. - -Fixes #45 -fix(templates): handle missing template files gracefully +然后在本地服务器上打开 `/start/web-generator/`。第一次构建会把 Pyodide 下载到 `.cache/web-generator`,并用固定的校验和检查每个文件(`--no-cache` 会跳过缓存)。`docs/en/assets/fastkit-generator/` 和 `.cache/web-generator/` 已被 git 忽略,绝不会被提交。没有这些资源文件时,页面会显示一条消息,说明生成器文件尚未构建。 -When a template file is missing, show a clear error message -instead of crashing with a stack trace. +要确认该页面生成的项目与命令行相同,请把 fixture 文件中的每个用例分别交给在 Node 中运行的页面生成器和已安装 wheel 的 `fastkit` 命令处理: -Fixes #67 +```bash +python scripts/web_generator/compare_with_cli.py \ + --assets docs/en/assets/fastkit-generator \ + --cases tests/fixtures/web_generator/cases.json ``` -## 发布流程 - -对维护者而言,发布流程如下: - -1. **更新版本号**(`setup.py` 与 `__init__.py`) -2. **更新 CHANGELOG.md** -3. **创建发布 PR** -4. **合并后打 tag** -5. **GitHub Actions** 自动构建并发布 - -
- -```console -$ git tag v1.2.0 -$ git push origin v1.2.0 -``` +加上 `--only 01-hello,03-layered` 可以只运行部分用例(使用 fixture 中的 id),加上 `--keep DIR` 可以保留两边的输出。要把从页面下载的某个 zip 与页面上显示的对应命令进行比较,请使用 `compare_with_cli.py --zip demo.zip -- init --project-name demo ...`。要检查构建好的站点,先运行 `mkdocs build --strict -d site`,再运行 `python scripts/web_generator/check_site.py site`。 -
+每种语言的页面字符串位于 `docs/js/web-generator-strings/.json`,级别和功能的文本来自 `src/fastapi_fastkit/catalog/i18n/` 中的 catalog 覆盖文件。`tests/test_docs` 会检查每种语言的键和占位符是否一致。 -## 下一步 +在 CI 中,修改了 `src/`、`docs/`、`README.md`、`CHANGELOG.md`、文档和网页生成器的脚本、`pyproject.toml` 或 `mkdocs.yml` 的拉取请求,以及推送到 `main` 的代码,都会触发 Web generator 工作流。它会构建 wheel 和资源文件,把每个用例与命令行的输出进行比较,以严格模式构建文档站点,并检查全部七种语言的该页面。文档部署在用 `mkdocs gh-deploy --strict` 发布之前,会再执行一遍构建和比较。 -开发环境已就绪后: +## 拉取请求 -1. **[浏览代码库](https://github.com/bnbong/FastAPI-fastkit/tree/main/src/fastapi_fastkit)** —— 理解整体架构 -2. **运行测试套件**,确认一切正常 -3. **从 GitHub 上挑选一个 [issue](https://github.com/bnbong/FastAPI-fastkit/issues)** 着手开发 -4. **加入 [discussions](https://github.com/bnbong/FastAPI-fastkit/discussions)**,与其他贡献者交流 +拉取请求的标题以 `CONTRIBUTING.md` 中的某个标签开头:`[FEAT]`、`[FIX]`、`[DOCS]`、`[STYLE]`、`[TEST]`、`[REFACTOR]` 或 `[CHORE]`,例如 `[FIX] Fix virtual environment activation in Windows`。推送之前运行 `make dev-check`。修改了模板的拉取请求还会运行[模板指南](template-creation-guide.md#checks)中介绍的模板检查。 -祝您编码愉快!🚀 +## 发布 -!!! tip "开发小贴士" - - 提交前先运行 `make dev-check` - - 优先编写测试(TDD 方式) - - 让每次提交保持小而聚焦 - - 新特性同时更新文档 +1. 在 `src/fastapi_fastkit/__init__.py` 中设置 `__version__`;包的版本号从这里读取。 +2. 在 `CHANGELOG.md` 中以 `## vX.Y.Z` 标题添加该版本。每个条目写一到两句话,不写拉取请求编号,也不写内部函数名。 +3. 发布一个 GitHub release。随后 Distribute 工作流会把发布标签写入 `src/fastapi_fastkit/__init__.py`,用 PDM 构建包并发布到 PyPI。 diff --git a/docs/zh/contributing/template-creation-guide.md b/docs/zh/contributing/template-creation-guide.md index f63a9249..a760a527 100644 --- a/docs/zh/contributing/template-creation-guide.md +++ b/docs/zh/contributing/template-creation-guide.md @@ -1,579 +1,182 @@ -# FastAPI 模板创建指南 +# 模板指南 -为 FastAPI-fastkit 添加新 FastAPI 项目模板的完整指南。 +本页介绍内置模板的目录结构、如何在 catalog 中注册模板、每个模板都要遵守的约定,以及对模板运行的检查。请先按照[开发环境搭建](development-setup.md)搭建好仓库。 -## 🎯 总览 +## 模板的目录结构 -添加新模板分为 5 个步骤: +每个模板都是 `src/fastapi_fastkit/fastapi_project_template/` 下的一个文件夹,以模板 id 命名(`fastapi-`,例如 `fastapi-auth-jwt`)。同一目录下的 `modules/` 不是模板:其中存放的是 `fastkit addroute` 写入的文件。 -1. **📋 规划与设计** —— 明确模板用途与结构 -2. **🏗️ 模板实现** —— 创建必需的结构与文件 -3. **🔍 本地校验** —— 用 inspector 校验模板 -4. **📚 文档** —— 编写 README 与使用指南 -5. **🚀 提交与评审** —— 创建 PR 并由社区评审 +fastkit 复制模板时,以 `-tpl` 结尾的文件会去掉这个后缀:`src/main.py-tpl` 变成 `src/main.py`,`.env.example-tpl` 变成 `.env.example`。每个 Python 文件都必须以 `.py-tpl` 结尾;只要有一个普通的 `.py` 文件,检查就会失败。生成项目时,会替换复制后文件中的四个占位符:``、``、`` 和 ``。 -## 📋 第 1 步:规划与设计 +一个模板至少需要: -### 明确模板用途 +- `README.md-tpl`。 +- `pyproject.toml-tpl`,并且其 `[project].dependencies` 中包含 `fastapi`。 +- `tests/` 文件夹,其中至少有一个 `test_*.py-tpl` 模块。 -在创建新模板之前,请回答以下问题: - -- **该模板的独特价值是什么?** -- **它与现有模板的差异在哪里?** -- **目标用户群体是谁?** -- **会包含怎样的技术栈?** - -### 模板命名规范 +大多数模板还带有以下文件;可以从 `fastapi-default` 复制过来再加以修改: +```text +fastapi-default/ +├── .env.example-tpl +├── .gitattributes-tpl +├── .gitignore-tpl +├── README.md-tpl +├── pyproject.toml-tpl +├── requirements-dev.txt-tpl +├── requirements.txt-tpl +├── scripts/ +├── src/ +│ ├── api/ +│ ├── core/ +│ ├── crud/ +│ ├── main.py-tpl +│ ├── mocks/ +│ └── schemas/ +└── tests/ ``` -fastapi-{purpose}-{stack} -``` - -示例: -- `fastapi-microservice`(微服务模板) -- `fastapi-graphql`(GraphQL 集成模板) -- `fastapi-auth-jwt`(JWT 认证模板) +`template-config.yml-tpl` 是可选的,只有检查脚本会读取它:例如,`requires_docker: true` 会在模板的 Docker Compose 环境中运行模板的测试,`app_module` 则指定冒烟测试要启动的应用。它永远不会被复制到生成的项目中。 -### 技术栈规划 +## 在 catalog 中注册模板 -事先定义好要包含的主要技术: +在 `src/fastapi_fastkit/catalog/catalog.toml` 中添加一个 `[[templates]]` 条目。条目的顺序就是 `fastkit list-templates` 列出模板的顺序。 -```yaml -# Example: fastapi-microservice template -core_dependencies: - - fastapi - - uvicorn - - pydantic - - pydantic-settings - -additional_features: - - sqlalchemy (ORM) - - alembic (migrations) - - redis (caching) - - celery (background tasks) - - pytest (testing) - -development_tools: - - black (code formatting) - - isort (import sorting) - - mypy (type checking) - - pre-commit (Git hooks) +```toml title="src/fastapi_fastkit/catalog/catalog.toml" +[[templates]] +id = "fastapi-auth-jwt" +kind = "example" +description = "FastAPI JWT Authentication" +read_first = "Read `src/app/main.py`, then `src/app/domains/auth/` and `src/app/core/security.py`." +addroute = false ``` -## 🏗️ 第 2 步:模板实现 +| 键 | 含义 | +| --- | --- | +| `id` | 文件夹名称。条目和文件夹必须一一对应。 | +| `kind` | `level`(通过级别使用)、`example`(通过 `fastkit init --template` 使用)或 `internal`(随包附带但不提供给用户选择)。新的示例项目使用 `example`。 | +| `description` | `README.md-tpl` 的第一个标题,不含 `# `。 | +| `read_first` | “Next steps”列表中“首先阅读”这一步的文本;`level` 和 `example` 必须提供。反引号中的每个路径都必须在模板中存在。 | +| `extend` | “扩展”这一步的文本,可选。 | +| `concepts` | 模板中带有注释的 `[[concepts]]` 条目的 id;没有时省略。 | +| `addroute` | 当“Next steps”列表不应建议运行 `fastkit addroute` 时设为 `false`;默认值为 `true`。 | -### 必需的目录结构 +catalog 加载器会拒绝未知的键和未知的概念 id。条目与其文件夹或 README 标题不一致时,`tests/test_catalog/test_agreement.py` 会失败。还要把翻译后的 `description`、`read_first` 和 `extend` 添加到每个 `src/fastapi_fastkit/catalog/i18n/.toml` 覆盖文件中;在所有语言都补齐之前,覆盖文件的测试会一直失败(参阅[翻译指南](translation-guide.md#catalog-overlays))。 -``` -fastapi-{template-name}/ -├── src/ # Application source code -│ ├── main.py-tpl # ✅ FastAPI app entry point (required) -│ ├── __init__.py-tpl -│ ├── api/ # API routers -│ │ ├── __init__.py-tpl -│ │ ├── api.py-tpl # Main API router -│ │ └── routes/ # Individual routes -│ │ ├── __init__.py-tpl -│ │ └── items.py-tpl # Example route -│ ├── core/ # Core configuration -│ │ ├── __init__.py-tpl -│ │ └── config.py-tpl # Settings management -│ ├── crud/ # CRUD logic -│ │ ├── __init__.py-tpl -│ │ └── items.py-tpl -│ ├── schemas/ # Pydantic models -│ │ ├── __init__.py-tpl -│ │ └── items.py-tpl -│ └── utils/ # Utility functions -│ ├── __init__.py-tpl -│ └── helpers.py-tpl -├── tests/ # ✅ Tests (required) -│ ├── __init__.py-tpl -│ ├── conftest.py-tpl # pytest configuration -│ └── test_items.py-tpl # Example tests -├── scripts/ # Scripts -│ ├── format.sh-tpl # Code formatting -│ ├── lint.sh-tpl # Linting -│ ├── run-server.sh-tpl # Server execution -│ └── test.sh-tpl # Test execution -├── pyproject.toml-tpl # ✅ Primary metadata (PEP 621, required) -├── requirements.txt-tpl # 🟡 Optional when pyproject declares deps -├── setup.cfg-tpl # Development tools configuration -├── README.md-tpl # ✅ Project documentation (required) -├── .env-tpl # Environment variables template -└── .gitignore-tpl # Git ignore file -``` +## 约定 -**最少必备文件。** 一个模板至少要提供: +### HTTP API -- `tests/` 目录 -- `README.md-tpl` -- `pyproject.toml-tpl`(PEP 621) -- 在 `pyproject.toml-tpl` 的 `[project].dependencies` 或 `requirements.txt-tpl` 中声明 `fastapi` 依赖 +带有业务路由的模板遵循[生成的项目](../reference/generated-projects.md#http-api)中描述的 API:路由位于 `settings.API_V1_PREFIX` 之下,根路径的 `GET /health` 返回 `{"status": "ok"}`,列表接收 `limit` 和 `offset` 并返回 `Page[XRead]`,创建时返回 201 和 `Location`,删除时返回 204,`PUT` 整体替换、`PATCH` 部分更新,找不到时返回 404 `{"detail": " not found"}`,schema 命名为 `XCreate`、`XUpdate`、`XRead`。路由器只带有自身资源的前缀(`APIRouter(prefix="/items", tags=["items"])`)。 -当 `pyproject.toml-tpl` 已声明 `[project].dependencies` 时,`requirements.txt-tpl` 不是必需的 —— 但如果模板同时附带两者,它们必须保持一致:两者之间存在依赖漂移时检查会失败。 +模板中如果带有 `core/pagination.py-tpl` 和 `core/responses.py-tpl`,它们必须与 `fastapi_project_template/modules/core/` 中的文件完全相同;仓库中的一个测试会比较每一份副本。 -**新模板以 pyproject 为先,不得附带 `setup.py-tpl`。**截至 v1.4.0,没有任何内置模板包含该文件。检查仍然接受该文件,以便仓库外的模板继续可用,但这是一条遗留路径。 +### 设置和密钥 -**统一以 Python 3.12 为目标**:`requires-python = ">=3.12"`、black 的 `target-version = ["py312"]`、mypy 的 `python_version = "3.12"`,以及任何 Docker 基础镜像都使用 `python:3.12-slim`。检查会确认这三处固定版本保持一致。 +- 由一个基于 pydantic-settings 的设置模块读取环境变量和 `.env`。从 `fastapi-default/src/core/config.py-tpl` 复制 `SECRET_KEY` 的检查和公开示例密钥的列表:当 `ENVIRONMENT=staging` 或 `production` 时,如果 `SECRET_KEY` 缺失、属于公开的示例或过短(少于 32 字节),应用会拒绝启动。 +- 提供带有占位值的 `.env.example-tpl`,绝不要提供 `.env-tpl`。fastkit 会根据它创建带有唯一 `SECRET_KEY` 的 `.env`。 +- `.gitignore-tpl` 忽略 `.env` 和 `.env.*`,并用 `!.env.example` 重新包含示例文件。 +- `.gitattributes-tpl` 把 shell 脚本、Docker 相关文件、`Makefile` 和 env 文件的换行符固定为 LF。 +- CORS 允许的源只来自 `BACKEND_CORS_ORIGINS`,并且设为 `*` 时会关闭凭据。 -**切勿将 `FastAPI-fastkit` 声明为生成项目的运行时依赖。**该 CLI 是开发工具;模板的依赖列表只应包含生成的应用本身会导入的内容。 +### 依赖和工具 -### 文件编写指南 +- 所有地方都以 Python 3.12 为目标:`requires-python = ">=3.12"`、black 的 `target-version = ["py312"]`、mypy 的 `python_version = "3.12"`,以及作为 Docker 基础镜像的 `python:3.12-slim`。检查脚本会检查前三项。 +- 运行时依赖包放在 `[project].dependencies` 和 `requirements.txt-tpl` 中;测试和 lint 工具放在 `dev` 依赖组和 `requirements-dev.txt-tpl` 中,后者以 `-r requirements.txt` 开头。`Dockerfile-tpl` 只安装 `requirements.txt`。如果 `[project].dependencies` 中的某个包没有出现在 `requirements.txt-tpl` 中,检查就会失败。 +- 绝不要把 `FastAPI-fastkit` 列为生成的项目的依赖。 +- 保留 `managed = true` 的 `[tool.fastapi-fastkit]` 表,以及 `description` 中的 `[FastAPI-fastkit templated]` 前缀;该块的其余内容由 fastkit 在生成时填写。 +- 把所有工具的设置都放在 `pyproject.toml-tpl` 中(`[tool.pytest.ini_options]`、`[tool.coverage.*]`、`[tool.black]`、`[tool.isort]`、`[tool.mypy]`、`[tool.ruff]`);任何模板都不提供 `setup.cfg-tpl` 或 `pytest.ini-tpl`。除 `fastapi-hello` 之外,每个模板都带有与 `fastkit init --feature tooling=ruff` 写入的内容相同的 `[tool.ruff]` 块,生成的项目必须通过 black、isort、`ruff check` 和 `ruff format --check`。`fastapi-hello` 之后的各级别模板还会在 `dev` 组中列出 pytest-cov、black、isort、mypy 和 ruff,并带有覆盖率设置,因此在由它们生成的每个项目中都能使用 `pytest --cov`。 -#### 1. 编写 main.py-tpl +### 注释行和 README 标记 -```python -""" -FastAPI application entry point +- `main.py-tpl` 以及汇总各资源路由器的模块要保留 `# fastkit:imports` 和 `# fastkit:routes` 这两行注释:`fastkit init` 和 `fastkit addroute` 会在这些位置插入代码。 +- `README.md-tpl` 中恰好有一行 ``,位于简介之后、下一个 `##` 标题之前,上下各留一个空行。生成项目时,这一行会被替换为“Next steps”列表。 -This file is the main application for the project created with FastAPI-fastkit. -""" -from fastapi import FastAPI -from fastapi.middleware.cors import CORSMiddleware +### 概念注释 -from api.api import api_router -from core.config import settings +概念注释在 FastAPI 的某个构造第一次出现在模板中的位置对它进行解释,由紧贴在代码上方的两行组成: -# Create FastAPI app (required for inspector validation) +```python title="fastapi-default/src/main.py-tpl" +# `app` is the FastAPI application that uvicorn serves: `uvicorn src.main:app`. +# https://fastapi.tiangolo.com/tutorial/first-steps/ app = FastAPI( - title="", - description="Project created with FastAPI-fastkit", - version="1.0.0", -) - -# CORS middleware configuration -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) - -# Register API router -app.include_router(api_router, prefix="/api/v1") - -@app.get("/") -async def root(): - """Root endpoint""" - return {"message": "Hello from !"} - -@app.get("/health") -async def health_check(): - """Health check endpoint""" - return {"status": "healthy"} - -if __name__ == "__main__": - import uvicorn - uvicorn.run(app, host="0.0.0.0", port=8000) -``` - -#### 2. 编写 pyproject.toml-tpl(推荐) - -新模板应使用 PEP 621 的 `pyproject.toml-tpl` 来声明元数据与依赖。该文件至少要有一个 `[project]` 段,内含 `name`、`version`、`description`,以及包含 `fastapi` 的 `dependencies` 列表。模板还必须携带两个 FastAPI-fastkit 身份标识,这样 `is_fastkit_project()` 才能在用户工作区中把生成的项目与无关的 FastAPI 项目区分开: - -- 在 `description` 中带 `[FastAPI-fastkit templated]` 前缀 -- 专门提供 `[tool.fastapi-fastkit]` 表,并设置 `managed = true` - -识别时只需任一标识匹配即可(不区分大小写)。若模板遗漏了它们,元数据注入会在项目生成时自动补上,但作者**应当显式包含**它们。 - -```toml -[project] -name = "" -version = "0.1.0" -description = "[FastAPI-fastkit templated] " -authors = [ - {name = "", email = ""}, -] -readme = "README.md" -requires-python = ">=3.12" -dependencies = [ - "fastapi>=0.115.0", - "uvicorn[standard]>=0.34.0", - "pydantic>=2.10.0", - "pydantic-settings>=2.7.0", - "python-dotenv>=1.0.0", -] - -[project.optional-dependencies] -dev = [ - "pytest>=8.0.0", - "httpx>=0.28.0", -] - -[tool.fastapi-fastkit] -managed = true - -[build-system] -requires = ["hatchling"] -build-backend = "hatchling.build" -``` - -#### 3. 编写 requirements.txt-tpl(可选) - -当 `pyproject.toml-tpl` 已经声明 `[project].dependencies` 时为可选。对于偏好纯 `pip` 工作流的模板,仍然有用。 - -```txt -# FastAPI core dependencies (required) -fastapi==0.104.1 -uvicorn[standard]==0.24.0 - -# Data validation -pydantic==2.5.0 -pydantic-settings==2.1.0 - -# Environment variable management -python-dotenv==1.0.0 - -# Database (if needed) -sqlalchemy==2.0.23 -alembic==1.13.0 - -# Development tools -pytest==7.4.3 -pytest-asyncio==0.21.1 -httpx==0.25.2 - -# Code quality -black==23.11.0 -isort==5.12.0 -mypy==1.7.1 -``` - -#### 4. 路由锚点 - -附带 `main.py-tpl` 或 API 聚合模块的模板,应当标记出 `fastkit addroute` 插入代码的位置: - -```python -from src.app.api import health - -# fastkit:imports - -api_router = APIRouter() -api_router.include_router(health.router) - -# fastkit:routes -``` - -如果没有这些锚点,`addroute` 会退回到基于 AST 的插入方式,自行定位 import 块和路由注册位置 —— 因此缺少锚点的模板仍然可以工作,但结果的可预测性较差。编辑这些文件时请保留这些注释。 - -#### 5. 编写测试文件 - -```python -# tests/test_items.py-tpl -""" -Items API test module -""" -import pytest -from fastapi.testclient import TestClient -from main import app - -client = TestClient(app) - -def test_read_root(): - """Test root endpoint""" - response = client.get("/") - assert response.status_code == 200 - assert "message" in response.json() - -def test_health_check(): - """Test health check""" - response = client.get("/health") - assert response.status_code == 200 - assert response.json() == {"status": "healthy"} - -def test_create_item(): - """Test item creation""" - item_data = { - "name": "Test Item", - "description": "Test Description" - } - response = client.post("/api/v1/items/", json=item_data) - assert response.status_code == 200 - data = response.json() - assert data["name"] == item_data["name"] - assert data["description"] == item_data["description"] - -def test_read_items(): - """Test reading items list""" - response = client.get("/api/v1/items/") - assert response.status_code == 200 - assert isinstance(response.json(), list) -``` - -## 🔍 第 3 步:本地校验 - -### 运行自动校验脚本 - -新模板准备好后,用以下命令进行校验: - -```bash -# Validate all templates -make inspect-templates - -# Validate specific template only -make inspect-template TEMPLATES="fastapi-your-template" - -# Validate with verbose output -python scripts/inspect-templates.py --templates "fastapi-your-template" --verbose - -# Fast local loop: no network, no server boot -python scripts/inspect-templates.py --templates "fastapi-your-template" \ - --offline --no-smoke - -# Full check before opening a PR (adds mypy over the generated project) -python scripts/inspect-templates.py --templates "fastapi-your-template" --mypy -``` - -`--offline` 会跳过 PyPI 依赖新鲜度查询,`--no-smoke` 会跳过启动生成项目(最慢的步骤),`--mypy` 会对生成项目进行类型检查。每项检查具体做什么,请参阅 [模板质量保障](../reference/template-quality-assurance.md)。 - -!!! note - - 您提交 PR 后,**Template PR Inspection** 工作流会自动运行并校验您的模板改动,反馈会直接出现在 PR 上。 - -### 校验清单 - -inspector 会自动校验以下项目: - -#### ✅ 文件结构校验 - -- [ ] 存在 `tests/` 目录 -- [ ] 存在 `README.md-tpl` 文件 -- [ ] 存在 `pyproject.toml-tpl`(新模板中不包含 `setup.py-tpl`) - -#### ✅ 文件扩展名校验 - -- [ ] 所有 Python 文件使用 `.py-tpl` 扩展名 -- [ ] 不存在 `.py` 扩展名的文件 - -#### ✅ 依赖校验 - -- [ ] `fastapi` 至少声明于以下其一: - - [ ] `pyproject.toml-tpl` 的 `[project].dependencies`(推荐) - - [ ] `requirements.txt-tpl` -- [ ] `requirements.txt-tpl` 与 `[project].dependencies` 不存在冲突 -- [ ] `FastAPI-fastkit` **不是**运行时依赖 - -#### ✅ FastAPI 实现校验 - -- [ ] `main.py-tpl` 中存在 `FastAPI` 的 import -- [ ] `main.py-tpl` 中存在形如 `app = FastAPI()` 的应用创建 - -#### ✅ 测试执行校验 - -- [ ] 成功创建虚拟环境 -- [ ] 成功安装依赖 -- [ ] 所有 pytest 测试通过 - -#### ✅ 冒烟测试 - -- [ ] 生成的项目可以在 uvicorn 下启动 -- [ ] `/docs` 有响应 -- [ ] `/health` 有响应 - -uvicorn 的目标依次从生成的 `pyproject.toml` 中的 `[tool.fastapi-fastkit].app_module`、`template-config.yml` 中的 `app_module`,以及约定俗成的 `main.py` 位置解析得到。 - -#### ✅ 配置一致性 - -- [ ] `requires-python`、black 的 `target-version` 与 mypy 的 `python_version` 都指向 Python 3.12 -- [ ] `requirements.txt-tpl` 与 `[project].dependencies` 之间不存在依赖漂移 -- [ ] 不存在对 `FastAPI-fastkit` 的自我依赖 - -#### ✅ 占位符残留 - -- [ ] 项目生成后不残留任何 `` - -#### ✅ 自动化模板测试 - -FastAPI-fastkit 自带**自动化模板测试**,会对所有模板执行完整测试: - -**测试覆盖范围:** - -- ✅ 模板创建过程 -- ✅ 项目元数据注入 -- ✅ 虚拟环境搭建 -- ✅ 依赖安装(覆盖所有包管理器) -- ✅ 基本项目结构校验 -- ✅ FastAPI 项目识别 - -**测试执行:** -```console -# Test all templates automatically -$ pytest tests/test_templates/test_all_templates.py -v - -# Test specific template -$ pytest tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[your-template-name] -v ``` -**模板测试自动发现:** -新模板会被**自动发现**并测试,无需手动配置: +- 第一行是一句话,并且不提及 fastkit;第二行只有 URL,并且必须是 catalog 中某个 `[[concepts]]` 条目的 URL。两行都不超过 88 列。 +- 一个模板中每个概念最多链接一次。`level` 模板中注释的 id 必须与它在 catalog 中的 `concepts` 列表完全一致;`example` 模板中的注释必须包含在它的列表中。 +- 该注释块紧贴在代码上方:不能放在 import 块内部,也不能放在装饰器和它所装饰的函数之间。 +- `modules/` 下的文件不带概念注释。 -1. ✅ **零配置**:加入模板即可自动测试 -2. ✅ **一致的测试**:对所有模板使用相同的质量标准 -3. ✅ **多种包管理器**:覆盖 UV、PDM、Poetry 与 PIP -4. ✅ **全面校验**:结构、元数据与功能性都会检查 +`tests/test_templates/test_concept_comments.py` 会检查本节中的每一条规则。 -**这对您意味着什么:** +## 检查 {#checks} -- 🚀 **`FastAPI-fastkit` 主源码中无需新增测试**:您的模板会被自动测试 -- ⚡ **开发更快**:专注模板内容,而不是测试配置 -- 🛡️ **质量保证**:所有模板拥有一致的测试体验 -- 🔄 **CI/CD 集成**:Pull Request 中自动测试 +### 在本地检查模板 -**仍需手动测试的内容:** +`scripts/inspect-templates.py` 会用模板创建一个真实的项目(不创建虚拟环境),对它依次运行一系列检查,并在第一个失败处停止: -- 🧪 **模板特有的功能**:业务逻辑与定制特性 -- 🔧 **集成测试**:外部服务与复杂工作流 -- 📱 **端到端场景**:完整的用户流程 +| 步骤 | 检查内容 | +| --- | --- | +| File structure | `tests/`、`README.md-tpl` 和 `pyproject.toml-tpl` 存在。 | +| File extensions | 没有不带 `-tpl` 的 `.py` 文件。 | +| Test suite presence | `tests/` 下至少有一个 `test_*.py-tpl`。 | +| Junk files | 没有 `.DS_Store`、`__pycache__`、`.venv`、`.pyc` 之类的文件。 | +| Dependencies | 声明了 `fastapi`。 | +| Configuration consistency | 固定了 Python 3.12,`[project].dependencies` 中的包在 `requirements.txt-tpl` 中都有列出,并且没有对 `FastAPI-fastkit` 的依赖。 | +| FastAPI implementation | 生成的项目创建了一个 `FastAPI(...)` 应用。 | +| Placeholder substitution | 生成的项目中没有残留任何 ``。 | +| Compile check | 每个 Python 文件都能编译。 | +| Template tests | 创建虚拟环境,安装依赖,然后运行 `scripts/test.sh`;没有该脚本时运行 `pytest tests/ -v`。 | +| Type check | 在生成的项目中,使用模板的 mypy 设置对包括测试在内的代码运行 `mypy .`(仅在指定 `--mypy` 时)。 | +| Smoke test | 用 uvicorn 启动应用;`/docs` 必须返回 200,`/health` 存在时也必须返回 200。 | +| Dependency freshness | 当固定的版本落后于 PyPI 上的最新版本时发出警告(指定 `--offline` 时跳过)。 | -**测试最佳实践:** ```console -# 1. Test your template locally -$ fastkit startdemo your-template-name - -# 2. Run automated tests -$ pytest tests/test_templates/test_all_templates.py::TestAllTemplates::test_template_creation[your-template-name] -v - -# 3. Test with different package managers -$ fastkit startdemo your-template-name --package-manager poetry -$ fastkit startdemo your-template-name --package-manager pdm -$ fastkit startdemo your-template-name --package-manager uv -``` - -### 手动校验清单 - -在自动校验之外,还要手动检查以下项: - -#### 🔧 代码质量 - -- [ ] 代码遵循 PEP 8 风格指南 -- [ ] 合理使用类型注解 -- [ ] 变量与函数命名有意义 -- [ ] 注释与 docstring 得当 - -#### 🏗️ 架构 - -- [ ] 关注点分离(API、业务逻辑、数据访问相互独立) -- [ ] 组件设计可复用 -- [ ] 结构便于扩展 -- [ ] 落实安全最佳实践 - -#### 📚 文档 - -- [ ] README.md-tpl 遵循 PROJECT_README_TEMPLATE.md 的格式 -- [ ] 明确说明安装与运行方式 -- [ ] 提供 API 文档(OpenAPI / Swagger) -- [ ] 解释环境变量 +$ python scripts/inspect-templates.py --help +usage: inspect-templates.py [-h] [--templates TEMPLATES] [--output OUTPUT] + [--verbose] [--offline] [--no-smoke] [--mypy] -## 📚 第 4 步:文档 - -### 编写 README.md-tpl - -参照 [PROJECT_README_TEMPLATE.md](https://github.com/bnbong/FastAPI-fastkit/blob/main/src/fastapi_fastkit/fastapi_project_template/PROJECT_README_TEMPLATE.md) 指南编写。 - -### 编写模板说明文档 - -在 `src/fastapi_fastkit/fastapi_project_template/README.md` 中加入对新模板的说明: - -```markdown -## fastapi-your-template - -Write a brief description and use cases for your new template here. - -### Features: -- Feature 1 -- Feature 2 -- Feature 3 - -### Use Cases: -- Use case 1 -- Use case 2 -``` - -## 🚀 第 5 步:提交与评审 - -### 创建 PR 前的清单 - -- [ ] 全部自动校验通过(`make inspect-templates`) -- [ ] 完成代码格式化(`make format`) -- [ ] 静态检查通过(`make lint`) -- [ ] 所有测试通过(`make test`) -- [ ] 文档已完成 -- [ ] 遵循 CONTRIBUTING.md 的规范 - -### PR 标题与描述 +Inspect FastAPI templates locally +options: + -h, --help show this help message and exit + --templates TEMPLATES + Specific templates to inspect (comma-separated, leave + empty for all) + --output OUTPUT Output JSON file for results + --verbose Enable verbose output + --offline Skip every network lookup (dependency freshness + reporting) + --no-smoke Skip booting the generated project with uvicorn + --mypy Type check the generated project with mypy (slow) ``` -[TEMPLATE] Add fastapi-{template-name} template -## Overview -Adds a new {purpose} template. +模板测试需要 `PATH` 中有 uv。不指定 `--output` 时,结果写入 `template_inspection_results.json`。检查单个模板的示例: -## Key Features -- Feature 1 -- Feature 2 -- Feature 3 - -## Validation Results -- [ ] Inspector validation passed -- [ ] All tests passed -- [ ] Documentation completed - -## Usage Example -\```bash -fastkit startdemo -# Select template: fastapi-{template-name} -\``` - -## Related Issues -Closes #issue-number +```console +$ python scripts/inspect-templates.py --templates fastapi-hello --offline --output results.json +📋 Found 1 templates to inspect: fastapi-hello +============================================================ +🔍 Inspecting template: fastapi-hello +... +✅ fastapi-hello: PASSED +---------------------------------------- +============================================================ +📊 INSPECTION SUMMARY + Total templates: 1 + ✅ Passed: 1 + ❌ Failed: 0 +🎉 All templates passed inspection! +📄 Results saved to: results.json ``` -### 评审流程 - -1. **自动校验**:GitHub Actions 自动校验模板 - - **Template PR Inspection**:对修改模板的 PR 运行 `inspect-changed-templates.py` - - **Weekly Inspection**:每周三对所有模板进行完整校验 -2. **代码评审**:维护者与社区评审代码 -3. **测试**:在不同环境中测试模板 -4. **文档评审**:核对文档的准确性与完整性 -5. **批准与合并**:所有要求满足后合并到 main 分支 - -!!! note - - 您会自动收到带有校验结果的 PR 评论。在请求评审前先确认这些结果! - -## 🎯 最佳实践 - -### 安全考量 - -- 用环境变量管理敏感信息 -- 合理配置 CORS -- 校验输入数据 -- 预防 SQL 注入 - -### 性能优化 - -- 善用异步处理 -- 优化数据库查询 -- 合理的缓存策略 -- 配置响应压缩 - -### 可维护性 +`make inspect-templates` 检查所有模板,`make inspect-templates-verbose` 会加上 `--verbose`,`make inspect-template TEMPLATES="fastapi-default,fastapi-hello"` 只检查你指定的模板。反复修改期间,`--offline --no-smoke` 可以跳过网络访问和最慢的步骤。`--mypy` 比生成的项目自身运行的检查更严格:项目的 `scripts/lint.sh` 只检查 `mypy src`,而 `--mypy` 还会对测试进行类型检查。`fastapi-domain-starter` 能通过其他所有步骤,但无法通过 `--mypy`,因为它的测试没有类型注解。 -- 代码结构清晰 -- 测试覆盖全面 -- 文档详尽 -- 配置日志与监控 +### 仓库测试 -## 🆘 需要帮助? +`pytest` 同样覆盖模板:`tests/test_templates/` 会用每个模板创建项目,对生成的项目运行 linter,把依赖文件与 `pyproject.toml-tpl` 进行比较,并检查概念注释和 README 标记。新的模板文件夹会被其中大多数测试自动发现;但 `tests/test_templates/test_template_requirements_split.py` 按名称列出了每个模板,因此要把你的模板也加到那里。 -- 📖 [开发环境配置指南](development-setup.md) -- 📋 [代码规范](code-guidelines.md) -- 💬 [GitHub Discussions](https://github.com/bnbong/FastAPI-fastkit/discussions) -- 📧 [联系维护者](mailto:bbbong9@gmail.com) +### CI 中的检查 -为 FastAPI-fastkit 社区添加新模板是非常宝贵的贡献。 -您的创意与付出会对其他开发者大有帮助!🚀 +- 每当拉取请求修改了 `src/fastapi_fastkit/fastapi_project_template/` 下的文件时,Template PR Inspection 工作流都会运行 `scripts/inspect-changed-templates.py --offline`,并把结果作为评论发布到该拉取请求上。 +- Weekly Template Inspection 工作流每周三 00:00 UTC 检查所有模板,并包含依赖新鲜度检查;某个模板失败时,它会创建一个 issue。也可以手动启动该工作流,只检查选定的模板。 diff --git a/docs/zh/contributing/translation-guide.md b/docs/zh/contributing/translation-guide.md index 14ad7ddf..b0a2c64c 100644 --- a/docs/zh/contributing/translation-guide.md +++ b/docs/zh/contributing/translation-guide.md @@ -1,367 +1,153 @@ # 翻译指南 -本指南说明如何为 FastAPI-fastkit 文档贡献翻译。 +本文档以七种语言发布:英语(`en`)、韩语(`ko`)、日语(`ja`)、中文(`zh`)、西班牙语(`es`)、法语(`fr`)和德语(`de`)。本页说明哪些内容需要翻译、哪些内容保留英文,如何翻译生成的表格、catalog 文本和网页生成器页面,以及测试如何检查译文。 -## 权威来源与翻译政策 +## 英文是源文本 -> **英文(`en`)是 FastAPI-fastkit 文档的权威来源。** 其他所有语言都是翻译目标,可能在某个版本或单个页面上落后于英文。 -> -> 当翻译页面与英文页面不一致时,**请以英文页面为准**,直到翻译跟上为止。翻译以贡献者达到的进度发布 —— 部分覆盖是正常且符合预期的。 +每个页面都先用英文写在 `docs/en/` 中。每种语言在 `docs//` 下的相同路径都有对应的同一页面,例如 `docs/en/learn/generate.md` 对应 `docs/ko/learn/generate.md`。每个页面都要有全部七种语言的版本;添加或修改英文页面时,六种译文要在同一个拉取请求或紧接着的下一个拉取请求中跟进。 -与该政策相对应的用户视角说明是 [翻译状态](../reference/translation-status.md) 页面,它会列出每个语言的实际完成度,以及尚未翻译时 MkDocs 的呈现方式(简而言之:回退到英文)。 +如果某种语言缺少某个页面的文件,站点会在该语言的菜单中显示英文页面。请把这种情况视为有待填补的空缺,而不是正常状态。 -仓库根目录的 `CHANGELOG.md` 也保持英文,作为权威发布历史。如果某个语言提供了 `changelog.md` 页面,该页面应当链接或包含规范的英文 changelog,而不要单独维护一份翻译过的 changelog —— 除非将来项目政策做出明确调整。 +`CHANGELOG.md` 保持英文。每个 `docs//changelog.md` 只包含 `\{!CHANGELOG.md!}`,用来引入英文文件。 -每次贡献翻译时,也请同步更新状态页中的表格,这样用户无需从语言切换器中猜测就能知道有哪些可用内容。 +## 保留英文的内容 -## 总览 +- 命令行打印或询问的所有内容:提问、消息、表格、帮助文本和其他输出。读者会拿页面与自己的终端进行对照。 +- 命令、选项、文件名、路径、代码、配置键和包名,无论是否位于代码块中。 +- 代码块。每个围栏代码块都与英文完全相同,包括其中的注释和示例输出。 +- `cli` 生成块(CLI 参考页面上的 `--help` 文本)和 `doctor-checks` 表格中的检查标题。脚本在每种语言中都以英文渲染它们。 +- 图片中的文字。图片是 `docs/img/` 中的共享文件,每种语言都使用同一张图片,因此请直接链接它,不要制作翻译版本的副本。 +- 链接目标和标题 id。有些标题以 `{#features}` 这样的 id 结尾,因为其他页面和重定向会链接到它。翻译标题文本,保留 id。示例项目页面上以模板 id 为标题的那些标题(`## fastapi-auth-jwt {#fastapi-auth-jwt}` 等)保持原样。 -FastAPI-fastkit 使用一套基于 AI 的自动化翻译系统,把文档翻译成多种语言。该系统会: +需要翻译的是它们周围的正文、标题、提示框文本、链接文本以及每张图片的替代文本。相对链接保持原样:所有语言中的路径都相同。 -- 读取英文源文档 -- 使用 AI API(OpenAI 或 Anthropic)翻译内容 -- 将翻译结果保存到对应语言目录 -- 创建 GitHub Pull Request 以供评审 +## 生成块 -自动化只提供起点,合并前**仍需人工评审**。AI 生成的翻译在 PR 中应标记为「draft」,并由该语言的熟练使用者评审后再合入。 +有些表格由 catalog 和 CLI 生成。它们在页面中位于两行注释之间: -## 支持的语言 - -以下是文档站当前**会构建**的语言。仅仅配置了构建目标**并不**意味着该语言已被翻译 —— 真实完成度请参阅 [翻译状态](../reference/translation-status.md)。 - -- 🇰🇷 韩文(ko) -- 🇯🇵 日文(ja) -- 🇨🇳 中文(zh) -- 🇪🇸 西班牙文(es) -- 🇫🇷 法文(fr) -- 🇩🇪 德文(de) - -## 前置条件 - -### 1. 安装翻译相关依赖 - -```bash -# Install using pip -pip install openai anthropic - -# Or using pdm -pdm install -G translation -``` - -### 2. 配置 API key - -您需要 OpenAI 或 Anthropic 任一家的 API key: - -```bash -# For OpenAI -export TRANSLATION_API_KEY="sk-..." - -# Or for Anthropic -export TRANSLATION_API_KEY="sk-ant-..." +```markdown + +... + ``` -### 3. 安装 GitHub CLI(可选) - -用于自动创建 PR: - -```bash -# macOS -brew install gh - -# Linux -curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg -echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null -sudo apt update -sudo apt install gh - -# Authenticate -gh auth login -``` - -## 使用方式 - -### 使用 Make 命令(推荐) +从英文页面复制这两行注释,并且绝不要翻译或编辑两行之间的内容。然后渲染你所翻译语言的块: -运行翻译最便捷的方式: - -```bash -# Translate all docs to all languages -make translate - -# Translate to specific language -make translate LANG=ko - -# Specify API provider and model -make translate LANG=ko PROVIDER=openai MODEL=gpt-4 -make translate LANG=ko PROVIDER=github MODEL=gpt-4o-mini +```console +$ python scripts/docs_blocks.py --lang ko +$ python scripts/docs_blocks.py --check ``` -### 直接使用脚本 +catalog 块(`levels`、`features`、`rules`、`package-managers`、`examples`、`concepts`)从页面所属语言的 catalog 覆盖文件中获取文本,覆盖文件见下文。表格中固定的词语来自 `scripts/docs_blocks.py` 开头的 `HEADINGS` 表:列标题、`{when} needs {require}.` 这样的短句,以及列表的标点和连接方式(`separator`、`join_or`、`join_and`),这样日语等语言就可以去掉其两侧的空格。已翻译的语言需要一个条目,包含 `en` 的每个键和相同的 `{placeholders}`;没有条目的语言使用英文词语。`cli` 块和 `doctor-checks` 表格中的检查标题保持英文,因为它们是命令行自身的文本。 -#### 翻译全部文档 +## Catalog 覆盖文件 {#catalog-overlays} -把全部文档翻译为所有支持的语言: +级别说明、功能的标签和简介、规则消息、概念标题以及 Next steps 的文本都来自 catalog。英文文本位于 `src/fastapi_fastkit/catalog/catalog.toml`;每种语言在 `src/fastapi_fastkit/catalog/i18n/.toml` 都有一个键相同的覆盖文件: -```bash -python scripts/translate.py --api-provider openai +```toml title="src/fastapi_fastkit/catalog/i18n/ko.toml" +[levels."hello"] +label = "Hello" +description = "main.py 하나에 엔드포인트 3개와 메모리 데이터가 들어 있고, 테스트도 함께 제공됩니다." ``` -### 翻译为指定语言 +覆盖文件为生成块和网页生成器页面提供文本。要查看所有需要翻译的键,请打印英文骨架: -仅翻译为韩文: - -```bash -python scripts/translate.py --target-lang ko --api-provider openai +```console +$ python -m fastapi_fastkit.catalog strings +[levels."hello"] +label = "Hello" +description = "One main.py: 3 endpoints, in-memory data, tests." +... ``` -### 翻译指定文件 +`tests/test_catalog` 检查的规则: -只翻译特定的文档文件: +- 覆盖文件要翻译骨架中的每一条文本,并且不能包含 catalog 中没有的键。 +- id、包名和 URL 绝不翻译,反引号中的代码片段与英文完全相同。 +- `{services}` 这样的占位符保留,名称不变。 +- 只有 `tests/test_catalog/test_overlays.py` 中列出的少数名称(例如 `Hello` 级别的标签)可以与英文相同。 -```bash -python scripts/translate.py \ - --target-lang ko \ - --files user-guide/installation.md user-guide/quick-start.md \ - --api-provider openai -``` +## 网页生成器页面 -### 跳过 PR 创建 +`docs//start/web-generator.md` 是英文页面的副本,其中只翻译以下内容: -翻译但不创建 GitHub PR: +- H1 和介绍段落(保留 Pyodide 链接和 `fastkit init ... --no-venv` 代码片段); +- `