codebase-documenter
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCodebase Documenter
代码库文档编写技能
Overview
概述
This skill enables creating comprehensive, beginner-friendly documentation for codebases. It provides structured templates and best practices for writing READMEs, architecture guides, code comments, and API documentation that help new users quickly understand and contribute to projects.
此技能可用于为代码库创建全面、对初学者友好的文档。它提供结构化模板和最佳实践,用于编写README、架构指南、代码注释和API文档,帮助新用户快速理解项目并参与贡献。
Core Principles for Beginner-Friendly Documentation
面向初学者的文档编写核心原则
When documenting code for new users, follow these fundamental principles:
- Start with the "Why" - Explain the purpose before diving into implementation details
- Use Progressive Disclosure - Present information in layers from simple to complex
- Provide Context - Explain not just what the code does, but why it exists
- Include Examples - Show concrete usage examples for every concept
- Assume No Prior Knowledge - Define terms and avoid jargon when possible
- Visual Aids - Use diagrams, flowcharts, and file tree structures
- Quick Wins - Help users get something running within 5 minutes
当为新用户编写代码文档时,请遵循以下基本原则:
- 从“为什么”开始 - 在深入实现细节前先解释目的
- 逐步披露信息 - 从简单到复杂分层呈现信息
- 提供上下文 - 不仅说明代码做什么,还要解释其存在的原因
- 包含示例 - 为每个概念展示具体的使用示例
- 假设用户无前置知识 - 定义术语,尽可能避免行话
- 使用视觉辅助 - 使用图表、流程图和文件树结构
- 快速上手 - 帮助用户在5分钟内让项目运行起来
Documentation Types and When to Use Them
文档类型及适用场景
1. README Documentation
1. README文档
When to create: For project root directories, major feature modules, or standalone components.
Structure to follow:
markdown
undefined适用场景: 项目根目录、主要功能模块或独立组件。
遵循以下结构:
markdown
undefinedProject Name
Project Name
What This Does
What This Does
[1-2 sentence plain-English explanation]
[1-2 sentence plain-English explanation]
Quick Start
Quick Start
[Get users running the project in < 5 minutes]
[Get users running the project in < 5 minutes]
Project Structure
Project Structure
[Visual file tree with explanations]
[Visual file tree with explanations]
Key Concepts
Key Concepts
[Core concepts users need to understand]
[Core concepts users need to understand]
Common Tasks
Common Tasks
[Step-by-step guides for frequent operations]
[Step-by-step guides for frequent operations]
Troubleshooting
Troubleshooting
[Common issues and solutions]
**Best practices:**
- Lead with the project's value proposition
- Include setup instructions that actually work (test them!)
- Provide a visual overview of the project structure
- Link to deeper documentation for advanced topics
- Keep the root README focused on getting started[Common issues and solutions]
**最佳实践:**
- 从项目的价值主张入手
- 包含实际可行的设置说明(请测试!)
- 提供项目结构的可视化概述
- 链接到进阶主题的深度文档
- 根目录README聚焦于快速上手2. Architecture Documentation
2. 架构文档
When to create: For projects with multiple modules, complex data flows, or non-obvious design decisions.
Structure to follow:
markdown
undefined适用场景: 包含多个模块、复杂数据流或非直观设计决策的项目。
遵循以下结构:
markdown
undefinedArchitecture Overview
Architecture Overview
System Design
System Design
[High-level diagram and explanation]
[High-level diagram and explanation]
Directory Structure
Directory Structure
[Detailed breakdown with purpose of each directory]
[Detailed breakdown with purpose of each directory]
Data Flow
Data Flow
[How data moves through the system]
[How data moves through the system]
Key Design Decisions
Key Design Decisions
[Why certain architectural choices were made]
[Why certain architectural choices were made]
Module Dependencies
Module Dependencies
[How different parts interact]
[How different parts interact]
Extension Points
Extension Points
[Where and how to add new features]
**Best practices:**
- Use diagrams to show system components and relationships
- Explain the "why" behind architectural decisions
- Document both the happy path and error handling
- Identify boundaries between modules
- Include visual file tree structures with annotations[Where and how to add new features]
**最佳实践:**
- 使用图表展示系统组件及关系
- 解释架构决策背后的“原因”
- 记录正常流程和错误处理流程
- 明确模块之间的边界
- 包含带注释的可视化文件树结构3. Code Comments
3. 代码注释
When to create: For complex logic, non-obvious algorithms, or code that requires context.
Annotation patterns:
Function/Method Documentation:
javascript
/**
* Calculates the prorated subscription cost for a partial billing period.
*
* Why this exists: Users can subscribe mid-month, so we need to charge
* them only for the days remaining in the current billing cycle.
*
* @param {number} fullPrice - The normal monthly subscription price
* @param {Date} startDate - When the user's subscription begins
* @param {Date} periodEnd - End of the current billing period
* @returns {number} The prorated amount to charge
*
* @example
* // User subscribes on Jan 15, period ends Jan 31
* calculateProratedCost(30, new Date('2024-01-15'), new Date('2024-01-31'))
* // Returns: 16.13 (17 days out of 31 days)
*/Complex Logic Documentation:
python
undefined适用场景: 复杂逻辑、非直观算法或需要上下文说明的代码段。
注释模式:
函数/方法文档:
javascript
/**
* Calculates the prorated subscription cost for a partial billing period.
*
* Why this exists: Users can subscribe mid-month, so we need to charge
* them only for the days remaining in the current billing cycle.
*
* @param {number} fullPrice - The normal monthly subscription price
* @param {Date} startDate - When the user's subscription begins
* @param {Date} periodEnd - End of the current billing period
* @returns {number} The prorated amount to charge
*
* @example
* // User subscribes on Jan 15, period ends Jan 31
* calculateProratedCost(30, new Date('2024-01-15'), new Date('2024-01-31'))
* // Returns: 16.13 (17 days out of 31 days)
*/复杂逻辑文档:
python
undefinedWhy this check exists: The API returns null for deleted users,
Why this check exists: The API returns null for deleted users,
but empty string for users who never set a name. We need to
but empty string for users who never set a name. We need to
distinguish between these cases for the audit log.
distinguish between these cases for the audit log.
if user_name is None:
# User was deleted - log this as a security event
log_deletion_event(user_id)
elif user_name == "":
# User never completed onboarding - safe to skip
continue
**Best practices:**
- Explain "why" not "what" - the code shows what it does
- Document edge cases and business logic
- Add examples for complex functions
- Explain parameters that aren't self-explanatory
- Note any gotchas or counterintuitive behaviorif user_name is None:
# User was deleted - log this as a security event
log_deletion_event(user_id)
elif user_name == "":
# User never completed onboarding - safe to skip
continue
**最佳实践:**
- 解释“为什么”而非“做什么”——代码本身已展示功能
- 记录边缘情况和业务逻辑
- 为复杂函数添加示例
- 解释非自明的参数
- 注意任何陷阱或违反直觉的行为4. API Documentation
4. API文档
When to create: For any HTTP endpoints, SDK methods, or public interfaces.
Structure to follow:
markdown
undefined适用场景: 所有HTTP端点、SDK方法或公共接口。
遵循以下结构:
markdown
undefinedEndpoint Name
Endpoint Name
What It Does
What It Does
[Plain-English explanation of the endpoint's purpose]
[Plain-English explanation of the endpoint's purpose]
Endpoint
Endpoint
POST /api/v1/resourcePOST /api/v1/resourceAuthentication
Authentication
[What auth is required and how to provide it]
[What auth is required and how to provide it]
Request Format
Request Format
[JSON schema or example request]
[JSON schema or example request]
Response Format
Response Format
[JSON schema or example response]
[JSON schema or example response]
Example Usage
Example Usage
[Concrete example with curl/code]
[Concrete example with curl/code]
Common Errors
Common Errors
[Error codes and what they mean]
[Error codes and what they mean]
Related Endpoints
Related Endpoints
[Links to related operations]
**Best practices:**
- Provide working curl examples
- Show both success and error responses
- Explain authentication clearly
- Document rate limits and constraints
- Include troubleshooting for common issues[Links to related operations]
**最佳实践:**
- 提供可运行的curl示例
- 展示成功和错误响应
- 清晰解释认证方式
- 记录速率限制和约束条件
- 包含常见问题的故障排除指南Documentation Workflow
文档编写工作流程
Step 1: Analyze the Codebase
步骤1:分析代码库
Before writing documentation:
- Identify entry points - Main files, index files, app initialization
- Map dependencies - How modules relate to each other
- Find core concepts - Key abstractions users need to understand
- Locate configuration - Environment setup, config files
- Review existing docs - Build on what's there, don't duplicate
编写文档前:
- 识别入口点 - 主文件、索引文件、应用初始化逻辑
- 映射依赖关系 - 模块之间的关联方式
- 梳理核心概念 - 用户需要理解的关键抽象
- 定位配置信息 - 环境设置、配置文件
- 审查现有文档 - 基于已有内容扩展,避免重复
Step 2: Choose Documentation Type
步骤2:选择文档类型
Based on user request and codebase analysis:
- New project or missing README → Start with README documentation
- Complex architecture or multiple modules → Create architecture documentation
- Confusing code sections → Add inline code comments
- HTTP/API endpoints → Write API documentation
- Multiple types needed → Address in order: README → Architecture → API → Comments
根据用户需求和代码库分析结果:
- 新项目或缺少README → 从README文档开始
- 复杂架构或多模块项目 → 创建架构文档
- 易混淆的代码段 → 添加内联代码注释
- HTTP/API端点 → 编写API文档
- 需要多种文档类型 → 按以下顺序处理:README → 架构 → API → 注释
Step 3: Generate Documentation
步骤3:生成文档
Use the templates from as starting points:
assets/templates/- - For project READMEs
assets/templates/README.template.md - - For architecture docs
assets/templates/ARCHITECTURE.template.md - - For API documentation
assets/templates/API.template.md
Customize templates based on the specific codebase:
- Fill in project-specific information - Replace placeholders with actual content
- Add concrete examples - Use real code from the project
- Include visual aids - Create file trees, diagrams, flowcharts
- Test instructions - Verify setup steps actually work
- Link related docs - Connect documentation pieces together
使用中的模板作为起点:
assets/templates/- - 项目README模板
assets/templates/README.template.md - - 架构文档模板
assets/templates/ARCHITECTURE.template.md - - API文档模板
assets/templates/API.template.md
根据具体代码库自定义模板:
- 填充项目特定信息 - 用实际内容替换占位符
- 添加具体示例 - 使用项目中的真实代码
- 包含视觉辅助 - 创建文件树、图表、流程图
- 测试说明 - 验证设置步骤是否可行
- 关联相关文档 - 建立文档之间的导航链接
Step 4: Review for Clarity
步骤4:审查清晰度
Before finalizing documentation:
- Read as a beginner - Does it make sense without project context?
- Check completeness - Are there gaps in the explanation?
- Verify examples - Do code examples actually work?
- Test instructions - Can someone follow the setup steps?
- Improve structure - Is information easy to find?
最终确定文档前:
- 以初学者视角阅读 - 无需项目上下文是否能理解?
- 检查完整性 - 解释是否存在遗漏?
- 验证示例 - 代码片段和命令是否可运行?
- 测试步骤 - 有人能按照设置步骤操作吗?
- 优化结构 - 信息是否易于查找?
Documentation Templates
文档模板
This skill includes several templates in that provide starting structures:
assets/templates/此技能在中包含多个模板,提供初始结构:
assets/templates/Available Templates
可用模板
- README.template.md - Comprehensive README structure with sections for quick start, project structure, and common tasks
- ARCHITECTURE.template.md - Architecture documentation template with system design, data flow, and design decisions
- API.template.md - API endpoint documentation with request/response formats and examples
- CODE_COMMENTS.template.md - Examples and patterns for effective inline documentation
- README.template.md - 包含快速上手、项目结构和常见任务的全面README结构
- ARCHITECTURE.template.md - 包含系统设计、数据流和设计决策的架构文档模板
- API.template.md - 包含请求/响应格式和示例的API端点文档模板
- CODE_COMMENTS.template.md - 有效内联文档的示例和模式
Using Templates
使用模板
- Read the appropriate template from
assets/templates/ - Customize for the specific project - Replace placeholders with actual information
- Add project-specific sections - Extend the template as needed
- Include real examples - Use actual code from the codebase
- Remove irrelevant sections - Delete parts that don't apply
- 读取对应模板 从中获取
assets/templates/ - 针对特定项目自定义 - 用实际信息替换占位符
- 添加项目特定章节 - 根据需要扩展模板
- 包含真实示例 - 使用代码库中的实际代码
- 删除无关章节 - 移除不适用的部分
Best Practices Reference
最佳实践参考
For detailed documentation best practices, style guidelines, and advanced patterns, refer to:
- - Comprehensive style guide and best practices
references/documentation_guidelines.md - - How to create effective diagrams and file trees
references/visual_aids_guide.md
Load these references when:
- Creating documentation for complex enterprise codebases
- Dealing with multiple stakeholder requirements
- Needing advanced documentation patterns
- Standardizing documentation across a large project
如需详细的文档编写最佳实践、风格指南和进阶模式,请参考:
- - 全面的风格指南和最佳实践
references/documentation_guidelines.md - - 如何创建有效的图表和文件树
references/visual_aids_guide.md
在以下场景中使用这些参考资料:
- 为复杂企业代码库创建文档
- 处理多方利益相关者需求
- 需要进阶文档编写模式
- 在大型项目中标准化文档
Common Patterns
常见模式
Creating File Tree Structures
创建文件树结构
File trees help new users understand project organization:
project-root/
├── src/ # Source code
│ ├── components/ # Reusable UI components
│ ├── pages/ # Page-level components (routing)
│ ├── services/ # Business logic and API calls
│ ├── utils/ # Helper functions
│ └── types/ # TypeScript type definitions
├── public/ # Static assets (images, fonts)
├── tests/ # Test files mirroring src structure
└── package.json # Dependencies and scripts文件树帮助新用户理解项目组织:
project-root/
├── src/ # Source code
│ ├── components/ # Reusable UI components
│ ├── pages/ # Page-level components (routing)
│ ├── services/ # Business logic and API calls
│ ├── utils/ # Helper functions
│ └── types/ # TypeScript type definitions
├── public/ # Static assets (images, fonts)
├── tests/ # Test files mirroring src structure
└── package.json # Dependencies and scriptsExplaining Complex Data Flows
解释复杂数据流
Use numbered steps with diagrams:
User Request Flow:
1. User submits form → 2. Validation → 3. API call → 4. Database → 5. Response
[1] components/UserForm.tsx
↓ validates input
[2] services/validation.ts
↓ sends to API
[3] services/api.ts
↓ queries database
[4] Database (PostgreSQL)
↓ returns data
[5] components/UserForm.tsx (updates UI)使用带图表的编号步骤:
User Request Flow:
1. User submits form → 2. Validation → 3. API call → 4. Database → 5. Response
[1] components/UserForm.tsx
↓ validates input
[2] services/validation.ts
↓ sends to API
[3] services/api.ts
↓ queries database
[4] Database (PostgreSQL)
↓ returns data
[5] components/UserForm.tsx (updates UI)Documenting Design Decisions
记录设计决策
Capture the "why" behind architectural choices:
markdown
undefined捕捉架构选择背后的“原因”:
markdown
undefinedWhy We Use Redux
Why We Use Redux
Decision: State management with Redux instead of Context API
Context: Our app has 50+ components that need access to user
authentication state, shopping cart, and UI preferences.
Reasoning:
- Context API causes unnecessary re-renders with this many components
- Redux DevTools helps debug complex state changes
- Team has existing Redux expertise
Trade-offs:
- More boilerplate code
- Steeper learning curve for new developers
- Worth it for: performance, debugging, team familiarity
undefinedDecision: State management with Redux instead of Context API
Context: Our app has 50+ components that need access to user
authentication state, shopping cart, and UI preferences.
Reasoning:
- Context API causes unnecessary re-renders with this many components
- Redux DevTools helps debug complex state changes
- Team has existing Redux expertise
Trade-offs:
- More boilerplate code
- Steeper learning curve for new developers
- Worth it for: performance, debugging, team familiarity
undefinedOutput Guidelines
输出指南
When generating documentation:
- Write for the target audience - Adjust complexity based on whether documentation is for beginners, intermediate, or advanced users
- Use consistent formatting - Follow markdown conventions, consistent heading hierarchy
- Provide working examples - Test all code snippets and commands
- Link between documents - Create a documentation navigation structure
- Keep it maintainable - Documentation should be easy to update as code changes
- Add dates and versions - Note when documentation was last updated
生成文档时:
- 面向目标受众编写 - 根据文档面向初学者、中级或高级用户调整复杂度
- 使用一致格式 - 遵循Markdown规范、统一标题层级
- 提供可运行示例 - 测试所有代码片段和命令
- 建立文档间链接 - 创建文档导航结构
- 保持可维护性 - 文档应随代码变更易于更新
- 添加日期和版本 - 记录文档最后更新时间
Quick Reference
快速参考
Command to generate README:
"Create a README file for this project that helps new developers get started"
Command to document architecture:
"Document the architecture of this codebase, explaining how the different modules interact"
Command to add code comments:
"Add explanatory comments to this file that help new developers understand the logic"
Command to document API:
"Create API documentation for all the endpoints in this file"
生成README的指令:
"为这个项目创建一个帮助新开发者快速上手的README文件"
记录架构的指令:
"记录这个代码库的架构,解释不同模块之间的交互方式"
添加代码注释的指令:
"为这个文件添加解释性注释,帮助新开发者理解逻辑"
生成API文档的指令:
"为这个文件中的所有端点创建API文档"