code-documentation
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode Documentation Skill
代码文档技能
Overview
概述
This skill generates professional, comprehensive documentation for software projects, codebases, libraries, and APIs. It follows industry best practices from projects like React, Django, Stripe, and Kubernetes to produce documentation that is accurate, well-structured, and useful for both new contributors and experienced developers.
The output ranges from single-file READMEs to multi-document developer guides, always matched to the project's complexity and the user's needs.
本技能为软件项目、代码库、库和API生成专业、全面的文档。它遵循React、Django、Stripe和Kubernetes等项目的行业最佳实践,生成准确、结构清晰且对新贡献者和资深开发者均有用的文档。
输出内容从单文件README到多文档开发者指南不等,始终匹配项目的复杂度和用户需求。
Core Capabilities
核心功能
- Generate comprehensive README.md files with badges, installation, usage, and API reference
- Create API reference documentation from source code analysis
- Produce architecture and design documentation with diagrams
- Write developer onboarding and contribution guides
- Generate changelogs from commit history or release notes
- Create inline code documentation following language-specific conventions
- Support JSDoc, docstrings, GoDoc, Javadoc, and Rustdoc formats
- Adapt documentation style to the project's language and ecosystem
- 生成包含徽章、安装说明、使用方法和API参考的全面README.md文件
- 通过源代码分析创建API参考文档
- 生成带图表的架构和设计文档
- 编写开发者入职指南和贡献指南
- 根据提交历史或发布说明生成变更日志
- 遵循特定语言规范创建内联代码文档
- 支持JSDoc、docstrings、GoDoc、Javadoc和Rustdoc格式
- 根据项目的语言和生态系统调整文档风格
When to Use This Skill
使用场景
Always load this skill when:
- User asks to "document", "create docs", or "write documentation" for any code
- User requests a README, API reference, or developer guide
- User shares a codebase or repository and wants documentation generated
- User asks to improve or update existing documentation
- User needs architecture documentation, including diagrams
- User requests a changelog or migration guide
在以下情况请加载此技能:
- 用户要求为任何代码“生成文档”“创建文档”或“编写文档”
- 用户请求README、API参考或开发者指南
- 用户分享代码库或仓库并希望生成文档
- 用户要求改进或更新现有文档
- 用户需要包含图表的架构文档
- 用户请求变更日志或迁移指南
Documentation Workflow
文档工作流程
Phase 1: Codebase Analysis
阶段1:代码库分析
Before writing any documentation, thoroughly understand the codebase.
在编写任何文档之前,需全面了解代码库。
Step 1.1: Project Discovery
步骤1.1:项目探索
Identify the project fundamentals:
| Field | How to Determine |
|---|---|
| Language(s) | Check file extensions, |
| Framework | Look at dependencies for known frameworks (React, Django, Express, Spring, etc.) |
| Build System | Check for |
| Package Manager | npm/yarn/pnpm, pip/uv/poetry, cargo, go modules, etc. |
| Project Structure | Map out the directory tree to understand the architecture |
| Entry Points | Find main files, CLI entry points, exported modules |
| Existing Docs | Check for existing README, docs/, wiki, or inline documentation |
确定项目基础信息:
| 字段 | 确定方法 |
|---|---|
| 语言 | 检查文件扩展名、 |
| 框架 | 查看依赖项以识别已知框架(React、Django、Express、Spring等) |
| 构建系统 | 检查是否存在 |
| 包管理器 | npm/yarn/pnpm、pip/uv/poetry、cargo、Go Modules等 |
| 项目结构 | 绘制目录树以理解架构 |
| 入口点 | 查找主文件、CLI入口点、导出模块 |
| 现有文档 | 检查是否存在现有README、docs/目录、wiki或内联文档 |
Step 1.2: Code Structure Analysis
步骤1.2:代码结构分析
Use sandbox tools to explore the codebase:
bash
undefined使用沙箱工具探索代码库:
bash
undefinedGet directory structure
获取目录结构
ls /mnt/user-data/uploads/project-dir/
ls /mnt/user-data/uploads/project-dir/
Read key files
读取关键文件
read_file /mnt/user-data/uploads/project-dir/package.json
read_file /mnt/user-data/uploads/project-dir/pyproject.toml
read_file /mnt/user-data/uploads/project-dir/package.json
read_file /mnt/user-data/uploads/project-dir/pyproject.toml
Search for public API surfaces
搜索公共API接口
grep -r "export " /mnt/user-data/uploads/project-dir/src/
grep -r "def " /mnt/user-data/uploads/project-dir/src/ --include=".py"
grep -r "func " /mnt/user-data/uploads/project-dir/ --include=".go"
undefinedgrep -r "export " /mnt/user-data/uploads/project-dir/src/
grep -r "def " /mnt/user-data/uploads/project-dir/src/ --include=".py"
grep -r "func " /mnt/user-data/uploads/project-dir/ --include=".go"
undefinedStep 1.3: Identify Documentation Scope
步骤1.3:确定文档范围
Based on analysis, determine what documentation to produce:
| Project Size | Recommended Documentation |
|---|---|
| Single file / script | Inline comments + usage header |
| Small library | README with API reference |
| Medium project | README + API docs + examples |
| Large project | README + Architecture + API + Contributing + Changelog |
基于分析结果,确定要生成的文档类型:
| 项目规模 | 推荐文档 |
|---|---|
| 单文件/脚本 | 内联注释 + 使用说明头部 |
| 小型库 | 带API参考的README |
| 中型项目 | README + API文档 + 示例 |
| 大型项目 | README + 架构文档 + API文档 + 贡献指南 + 变更日志 |
Phase 2: Documentation Generation
阶段2:文档生成
Step 2.1: README Generation
步骤2.1:README生成
Every project needs a README. Follow this structure:
markdown
undefined每个项目都需要README。遵循以下结构:
markdown
undefinedProject Name
项目名称
Features
特性
- [Key feature 1 — brief description]
- [Key feature 2 — brief description]
- [Key feature 3 — brief description]
- [关键特性1——简要描述]
- [关键特性2——简要描述]
- [关键特性3——简要描述]
Quick Start
快速开始
Prerequisites
前提条件
- [Prerequisite 1 with version requirement]
- [Prerequisite 2 with version requirement]
- [前提条件1及版本要求]
- [前提条件2及版本要求]
Installation
安装
[Installation commands with copy-paste-ready code blocks]
[可直接复制粘贴的安装命令代码块]
Basic Usage
基本使用
[Minimal working example that demonstrates core functionality]
[展示核心功能的最小可运行示例]
Documentation
文档
- [Link to full API reference if separate]
- [Link to architecture docs if separate]
- [Link to examples directory if applicable]
- [指向独立完整API参考的链接(如有)]
- [指向架构文档的链接(如有)]
- [指向示例目录的链接(如适用)]
API Reference
API参考
[Inline API reference for smaller projects OR link to generated docs]
[小型项目的内联API参考 或 指向生成文档的链接]
Configuration
配置
[Environment variables, config files, or runtime options]
[环境变量、配置文件或运行时选项]
Examples
示例
[2-3 practical examples covering common use cases]
[2-3个覆盖常见用例的实用示例]
Development
开发
Setup
环境搭建
[How to set up a development environment]
[如何搭建开发环境]
Testing
测试
[How to run tests]
[如何运行测试]
Building
构建
[How to build the project]
[如何构建项目]
Contributing
贡献
[Contribution guidelines or link to CONTRIBUTING.md]
[贡献指南或指向CONTRIBUTING.md的链接]
License
许可证
[License information]
undefined[许可证信息]
undefinedStep 2.2: API Reference Generation
步骤2.2:API参考生成
For each public API surface, document:
Function / Method Documentation:
markdown
undefined针对每个公共API接口,需记录:
函数/方法文档:
markdown
undefinedfunctionName(param1, param2, options?)
functionName(param1, param2, options?)functionName(param1, param2, options?)
functionName(param1, param2, options?)Brief description of what this function does.
Parameters:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| | Yes | — | Description of param1 |
| | Yes | — | Description of param2 |
| | No | | Configuration options |
| | No | | Timeout in milliseconds |
Returns: — Description of return value
Promise<Result>Throws:
- — When param1 is empty
ValidationError - — When the operation exceeds the timeout
TimeoutError
Example:
```javascript
const result = await functionName("hello", 42, { timeout: 10000 });
console.log(result.data);
```
**Class Documentation**:
```markdown该函数功能的简要描述。
参数:
| 参数 | 类型 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|---|
| | 是 | — | param1的描述 |
| | 是 | — | param2的描述 |
| | 否 | | 配置选项 |
| | 否 | | 超时时间(毫秒) |
返回值: — 返回值描述
Promise<Result>抛出异常:
- — 当param1为空时
ValidationError - — 当操作超时的时候
TimeoutError
示例:
javascript
const result = await functionName("hello", 42, { timeout: 10000 });
console.log(result.data);
**类文档**:
```markdownClassName
ClassNameClassName
ClassNameBrief description of the class and its purpose.
Constructor:
```javascript
new ClassName(config)
```
| Parameter | Type | Description |
|---|---|---|
| | Description |
| | Description |
Methods:
- — Brief description
method1() - — Brief description
method2(param)
Properties:
| Property | Type | Description |
|---|---|---|
| | Description |
| | Read-only. Description |
undefined类及其用途的简要描述。
构造函数:
javascript
new ClassName(config)| 参数 | 类型 | 描述 |
|---|---|---|
| | 描述 |
| | 描述 |
方法:
- — 简要描述
method1() - — 简要描述
method2(param)
属性:
| 属性 | 类型 | 描述 |
|---|---|---|
| | 描述 |
| | 只读。描述 |
undefinedStep 2.3: Architecture Documentation
步骤2.3:架构文档生成
For medium-to-large projects, include architecture documentation:
markdown
undefined对于中大型项目,需包含架构文档:
markdown
undefinedArchitecture Overview
架构概述
System Diagram
系统图
[Include a Mermaid diagram showing the high-level architecture]
```mermaid
graph TD
A[Client] --> B[API Gateway]
B --> C[Service A]
B --> D[Service B]
C --> E[(Database)]
D --> E
```
[包含展示高层架构的Mermaid图表]
mermaid
graph TD
A[客户端] --> B[API网关]
B --> C[服务A]
B --> D[服务B]
C --> E[(数据库)]
D --> EComponent Overview
组件概述
Component Name
组件名称
- Purpose: What this component does
- Location:
src/components/name/ - Dependencies: What it depends on
- Public API: Key exports or interfaces
- 用途:该组件的功能
- 位置:
src/components/name/ - 依赖项:它依赖的内容
- 公共API:关键导出或接口
Data Flow
数据流
[Describe how data flows through the system for key operations]
[描述关键操作中数据在系统中的流动过程]
Design Decisions
设计决策
Decision Title
决策标题
- Context: What situation led to this decision
- Decision: What was decided
- Rationale: Why this approach was chosen
- Trade-offs: What was sacrificed
undefined- 背景:导致该决策的场景
- 决策:做出的决定
- 理由:选择此方案的原因
- 权衡:牺牲的内容
undefinedStep 2.4: Inline Code Documentation
步骤2.4:内联代码文档生成
Generate language-appropriate inline documentation:
Python (Docstrings — Google style):
python
def process_data(input_path: str, options: dict | None = None) -> ProcessResult:
"""Process data from the given file path.
Reads the input file, applies transformations based on the provided
options, and returns a structured result object.
Args:
input_path: Absolute path to the input data file.
Supports CSV, JSON, and Parquet formats.
options: Optional configuration dictionary.
- "validate" (bool): Enable input validation. Defaults to True.
- "format" (str): Output format ("json" or "csv"). Defaults to "json".
Returns:
A ProcessResult containing the transformed data and metadata.
Raises:
FileNotFoundError: If input_path does not exist.
ValidationError: If validation is enabled and data is malformed.
Example:
>>> result = process_data("/data/input.csv", {"validate": True})
>>> print(result.row_count)
1500
"""TypeScript (JSDoc / TSDoc):
typescript
/**
* Fetches user data from the API and transforms it for display.
*
* @param userId - The unique identifier of the user
* @param options - Configuration options for the fetch operation
* @param options.includeProfile - Whether to include the full profile. Defaults to `false`.
* @param options.cache - Cache duration in seconds. Set to `0` to disable.
* @returns The transformed user data ready for rendering
* @throws {NotFoundError} When the user ID does not exist
* @throws {NetworkError} When the API is unreachable
*
* @example
* ```ts
* const user = await fetchUser("usr_123", { includeProfile: true });
* console.log(user.displayName);
* ```
*/Go (GoDoc):
go
// ProcessData reads the input file at the given path, applies the specified
// transformations, and returns the processed result.
//
// The input path must be an absolute path to a CSV or JSON file.
// If options is nil, default options are used.
//
// ProcessData returns an error if the file does not exist or cannot be parsed.
func ProcessData(inputPath string, options *ProcessOptions) (*Result, error) {生成符合语言规范的内联文档:
Python(Google风格Docstrings):
python
def process_data(input_path: str, options: dict | None = None) -> ProcessResult:
"""处理给定文件路径中的数据。
读取输入文件,根据提供的选项应用转换,并返回结构化结果对象。
参数:
input_path: 输入数据文件的绝对路径。
支持CSV、JSON和Parquet格式。
options: 可选配置字典。
- "validate" (bool): 启用输入验证。默认为True。
- "format" (str): 输出格式("json"或"csv")。默认为"json"。
返回:
包含转换后数据和元数据的ProcessResult对象。
抛出异常:
FileNotFoundError: 当input_path不存在时。
ValidationError: 当启用验证且数据格式不正确时。
示例:
>>> result = process_data("/data/input.csv", {"validate": True})
>>> print(result.row_count)
1500
"""TypeScript(JSDoc / TSDoc):
typescript
/**
* 从API获取用户数据并转换为可展示格式。
*
* @param userId - 用户的唯一标识符
* @param options - 获取操作的配置选项
* @param options.includeProfile - 是否包含完整个人资料。默认为`false`。
* @param options.cache - 缓存时长(秒)。设为`0`以禁用缓存。
* @returns 转换后可直接渲染的用户数据
* @throws {NotFoundError} 当用户ID不存在时
* @throws {NetworkError} 当API无法访问时
*
* @example
* ```ts
* const user = await fetchUser("usr_123", { includeProfile: true });
* console.log(user.displayName);
* ```
*/Go(GoDoc):
go
// ProcessData读取给定路径的输入文件,应用指定的转换,并返回处理后的结果。
//
// 输入路径必须是CSV或JSON文件的绝对路径。
// 如果options为nil,则使用默认选项。
//
// 如果文件不存在或无法解析,ProcessData会返回错误。
func ProcessData(inputPath string, options *ProcessOptions) (*Result, error) {Phase 3: Quality Assurance
阶段3:质量保证
Step 3.1: Documentation Completeness Check
步骤3.1:文档完整性检查
Verify the documentation covers:
- What it is — Clear project description that a newcomer can understand
- Why it exists — Problem it solves and value proposition
- How to install — Copy-paste-ready installation commands
- How to use — At least one minimal working example
- API surface — All public functions, classes, and types documented
- Configuration — All environment variables, config files, and options
- Error handling — Common errors and how to resolve them
- Contributing — How to set up dev environment and submit changes
验证文档是否涵盖以下内容:
- 是什么 — 清晰的项目描述,让新手也能理解
- 为什么存在 — 它解决的问题和价值主张
- 如何安装 — 可直接复制粘贴的安装命令
- 如何使用 — 至少一个最小可运行示例
- API接口 — 所有公共函数、类和类型均已文档化
- 配置 — 所有环境变量、配置文件和选项
- 错误处理 — 常见错误及解决方法
- 贡献指南 — 如何搭建开发环境和提交变更
Step 3.2: Quality Standards
步骤3.2:质量标准
| Standard | Check |
|---|---|
| Accuracy | Every code example must actually work with the described API |
| Completeness | No public API surface left undocumented |
| Consistency | Same formatting and structure throughout |
| Freshness | Documentation matches the current code, not an older version |
| Accessibility | No jargon without explanation, acronyms defined on first use |
| Examples | Every complex concept has at least one practical example |
| 标准 | 检查项 |
|---|---|
| 准确性 | 每个代码示例必须能与描述的API配合正常运行 |
| 完整性 | 无未文档化的公共API接口 |
| 一致性 | 整个文档格式和结构保持一致 |
| 时效性 | 文档与当前代码匹配,而非旧版本 |
| 易读性 | 无未解释的行话,首字母缩写首次出现时需定义 |
| 示例 | 每个复杂概念至少有一个实用示例 |
Step 3.3: Cross-reference Validation
步骤3.3:交叉引用验证
Ensure:
- All mentioned file paths exist in the project
- All referenced functions and classes exist in the code
- All code examples use the correct function signatures
- Version numbers match the project's actual version
- All links (internal and external) are valid
确保:
- 所有提及的文件路径在项目中存在
- 所有引用的函数和类在代码中存在
- 所有代码示例使用正确的函数签名
- 版本号与项目实际版本匹配
- 所有链接(内部和外部)均有效
Documentation Style Guide
文档风格指南
Writing Principles
写作原则
- Lead with the "why" — Before explaining how something works, explain why it exists
- Progressive disclosure — Start simple, add complexity gradually
- Show, don't tell — Prefer code examples over lengthy explanations
- Active voice — "The function returns X" not "X is returned by the function"
- Present tense — "The server starts on port 8080" not "The server will start on port 8080"
- Second person — "You can configure..." not "Users can configure..."
- 先讲“为什么” — 在解释工作原理之前,先说明它存在的原因
- 逐步披露 — 从简单开始,逐步增加复杂度
- 展示而非讲述 — 优先使用代码示例而非冗长解释
- 主动语态 — 使用“函数返回X”而非“X被函数返回”
- 现在时态 — 使用“服务器在8080端口启动”而非“服务器将在8080端口启动”
- 第二人称 — 使用“你可以配置...”而非“用户可以配置...”
Formatting Rules
格式规则
- Use ATX-style headers (,
#,##)### - Use fenced code blocks with language specification (,
```python)```bash - Use tables for structured information (parameters, options, configuration)
- Use admonitions for important notes, warnings, and tips
- Keep line length readable (wrap prose at ~80-100 characters in source)
- Use for function names, file paths, variable names, and CLI commands
code formatting
- 使用ATX风格标题(、
#、##)### - 使用带语言指定的围栏代码块(、
```python)```bash - 使用表格展示结构化信息(参数、选项、配置)
- 使用警示框展示重要提示、警告和技巧
- 保持行长度可读(源文件中 prose 部分每行约80-100字符时换行)
- 对函数名、文件路径、变量名和CLI命令使用
代码格式
Language-Specific Conventions
特定语言规范
| Language | Doc Format | Style Guide |
|---|---|---|
| Python | Google-style docstrings | PEP 257 |
| TypeScript/JavaScript | TSDoc / JSDoc | TypeDoc conventions |
| Go | GoDoc comments | Effective Go |
| Rust | Rustdoc ( | Rust API Guidelines |
| Java | Javadoc | Oracle Javadoc Guide |
| C/C++ | Doxygen | Doxygen manual |
| 语言 | 文档格式 | 风格指南 |
|---|---|---|
| Python | Google风格docstrings | PEP 257 |
| TypeScript/JavaScript | TSDoc / JSDoc | TypeDoc规范 |
| Go | GoDoc注释 | Effective Go |
| Rust | Rustdoc ( | Rust API指南 |
| Java | Javadoc | Oracle Javadoc指南 |
| C/C++ | Doxygen | Doxygen手册 |
Output Handling
输出处理
After generation:
- Save documentation files to
/mnt/user-data/outputs/ - For multi-file documentation, maintain the project directory structure
- Present generated files to the user using the tool
present_files - Offer to iterate on specific sections or adjust the level of detail
- Suggest additional documentation that might be valuable
生成后:
- 将文档文件保存到
/mnt/user-data/outputs/ - 对于多文件文档,保持项目目录结构
- 使用工具向用户展示生成的文件
present_files - 提供对特定部分进行迭代或调整详细程度的服务
- 建议可能有价值的额外文档内容
Notes
注意事项
- Always analyze the actual code before writing documentation — never guess at API signatures or behavior
- When existing documentation exists, preserve its structure unless the user explicitly asks for a rewrite
- For large codebases, prioritize documenting the public API surface and key abstractions first
- Documentation should be written in the same language as the project's existing docs; default to English if none exist
- When generating changelogs, use the Keep a Changelog format
- This skill works well in combination with the skill for documenting third-party integrations or dependencies
deep-research
- 编写文档前务必分析实际代码——切勿猜测API签名或行为
- 如果存在现有文档,除非用户明确要求重写,否则保留其结构
- 对于大型代码库,优先记录公共API接口和关键抽象
- 文档应使用与项目现有文档相同的语言;如果没有现有文档,默认使用英语
- 生成变更日志时,使用Keep a Changelog格式
- 此技能与技能配合使用效果良好,可用于记录第三方集成或依赖项
deep-research