code-documentation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code 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:
FieldHow to Determine
Language(s)Check file extensions,
package.json
,
pyproject.toml
,
go.mod
,
Cargo.toml
, etc.
FrameworkLook at dependencies for known frameworks (React, Django, Express, Spring, etc.)
Build SystemCheck for
Makefile
,
CMakeLists.txt
,
webpack.config.js
,
build.gradle
, etc.
Package Managernpm/yarn/pnpm, pip/uv/poetry, cargo, go modules, etc.
Project StructureMap out the directory tree to understand the architecture
Entry PointsFind main files, CLI entry points, exported modules
Existing DocsCheck for existing README, docs/, wiki, or inline documentation
确定项目基础信息:
字段确定方法
语言检查文件扩展名、
package.json
pyproject.toml
go.mod
Cargo.toml
等。
框架查看依赖项以识别已知框架(React、Django、Express、Spring等)
构建系统检查是否存在
Makefile
CMakeLists.txt
webpack.config.js
build.gradle
等。
包管理器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
undefined

Get 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"
undefined
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"
undefined

Step 1.3: Identify Documentation Scope

步骤1.3:确定文档范围

Based on analysis, determine what documentation to produce:
Project SizeRecommended Documentation
Single file / scriptInline comments + usage header
Small libraryREADME with API reference
Medium projectREADME + API docs + examples
Large projectREADME + 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
undefined

Project Name

项目名称

[One-line project description — what it does and why it matters]
Badge Badge
[一行项目描述——它的功能和重要性]
徽章 徽章

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
[许可证信息]
undefined

Step 2.2: API Reference Generation

步骤2.2:API参考生成

For each public API surface, document:
Function / Method Documentation:
markdown
undefined
针对每个公共API接口,需记录:
函数/方法文档
markdown
undefined

functionName(param1, param2, options?)

functionName(param1, param2, options?)

Brief description of what this function does.
Parameters:
ParameterTypeRequiredDefaultDescription
param1
string
YesDescription of param1
param2
number
YesDescription of param2
options
Object
No
{}
Configuration options
options.timeout
number
No
5000
Timeout in milliseconds
Returns:
Promise<Result>
— Description of return value
Throws:
  • ValidationError
    — When param1 is empty
  • TimeoutError
    — When the operation exceeds the timeout
Example:
```javascript const result = await functionName("hello", 42, { timeout: 10000 }); console.log(result.data); ```

**Class Documentation**:

```markdown
该函数功能的简要描述。
参数:
参数类型是否必填默认值描述
param1
string
param1的描述
param2
number
param2的描述
options
Object
{}
配置选项
options.timeout
number
5000
超时时间(毫秒)
返回值:
Promise<Result>
— 返回值描述
抛出异常:
  • ValidationError
    — 当param1为空时
  • TimeoutError
    — 当操作超时的时候
示例:
javascript
const result = await functionName("hello", 42, { timeout: 10000 });
console.log(result.data);

**类文档**:

```markdown

ClassName

ClassName

Brief description of the class and its purpose.
Constructor:
```javascript new ClassName(config) ```
ParameterTypeDescription
config.option1
string
Description
config.option2
boolean
Description
Methods:
Properties:
PropertyTypeDescription
property1
string
Description
property2
number
Read-only. Description
undefined
类及其用途的简要描述。
构造函数:
javascript
new ClassName(config)
参数类型描述
config.option1
string
描述
config.option2
boolean
描述
方法:
属性:
属性类型描述
property1
string
描述
property2
number
只读。描述
undefined

Step 2.3: Architecture Documentation

步骤2.3:架构文档生成

For medium-to-large projects, include architecture documentation:
markdown
undefined
对于中大型项目,需包含架构文档:
markdown
undefined

Architecture 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 --> E

Component 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
  • 背景:导致该决策的场景
  • 决策:做出的决定
  • 理由:选择此方案的原因
  • 权衡:牺牲的内容
undefined

Step 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:质量标准

StandardCheck
AccuracyEvery code example must actually work with the described API
CompletenessNo public API surface left undocumented
ConsistencySame formatting and structure throughout
FreshnessDocumentation matches the current code, not an older version
AccessibilityNo jargon without explanation, acronyms defined on first use
ExamplesEvery 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

写作原则

  1. Lead with the "why" — Before explaining how something works, explain why it exists
  2. Progressive disclosure — Start simple, add complexity gradually
  3. Show, don't tell — Prefer code examples over lengthy explanations
  4. Active voice — "The function returns X" not "X is returned by the function"
  5. Present tense — "The server starts on port 8080" not "The server will start on port 8080"
  6. Second person — "You can configure..." not "Users can configure..."
  1. 先讲“为什么” — 在解释工作原理之前,先说明它存在的原因
  2. 逐步披露 — 从简单开始,逐步增加复杂度
  3. 展示而非讲述 — 优先使用代码示例而非冗长解释
  4. 主动语态 — 使用“函数返回X”而非“X被函数返回”
  5. 现在时态 — 使用“服务器在8080端口启动”而非“服务器将在8080端口启动”
  6. 第二人称 — 使用“你可以配置...”而非“用户可以配置...”

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
    code formatting
    for function names, file paths, variable names, and CLI commands
  • 使用ATX风格标题(
    #
    ##
    ###
  • 使用带语言指定的围栏代码块(
    ```python
    ```bash
  • 使用表格展示结构化信息(参数、选项、配置)
  • 使用警示框展示重要提示、警告和技巧
  • 保持行长度可读(源文件中 prose 部分每行约80-100字符时换行)
  • 对函数名、文件路径、变量名和CLI命令使用
    代码格式

Language-Specific Conventions

特定语言规范

LanguageDoc FormatStyle Guide
PythonGoogle-style docstringsPEP 257
TypeScript/JavaScriptTSDoc / JSDocTypeDoc conventions
GoGoDoc commentsEffective Go
RustRustdoc (
///
)
Rust API Guidelines
JavaJavadocOracle Javadoc Guide
C/C++DoxygenDoxygen manual
语言文档格式风格指南
PythonGoogle风格docstringsPEP 257
TypeScript/JavaScriptTSDoc / JSDocTypeDoc规范
GoGoDoc注释Effective Go
RustRustdoc (
///
)
Rust API指南
JavaJavadocOracle Javadoc指南
C/C++DoxygenDoxygen手册

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
    present_files
    tool
  • 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
    deep-research
    skill for documenting third-party integrations or dependencies
  • 编写文档前务必分析实际代码——切勿猜测API签名或行为
  • 如果存在现有文档,除非用户明确要求重写,否则保留其结构
  • 对于大型代码库,优先记录公共API接口和关键抽象
  • 文档应使用与项目现有文档相同的语言;如果没有现有文档,默认使用英语
  • 生成变更日志时,使用Keep a Changelog格式
  • 此技能与
    deep-research
    技能配合使用效果良好,可用于记录第三方集成或依赖项