关于 code-documentation-generator
面向开发者的代码文档编写技能,涵盖代码注释、API 参考和项目指南,并强调清晰、一致、准确及适配不同经验水平的读者。
主要功能
- 01JavaScript 和 TypeScript 的 JSDoc
- 02Google 与 NumPy 风格的 Python 文档字符串
- 03REST API 与 Markdown 文档
- 04README 模板和示例
- 05TypeDoc 与 Sphinx 自动化指南
适用场景
- 01为导出的 API 编写文档
- 02编写 Python 函数文档字符串
- 03创建 REST 端点参考文档
- 04配置自动生成文档
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ dengineproblem/ agents-monorepo --skill code-documentation-generator安装后在 Claude Code 中输入/code-documentation-generator确认已加载。
详细介绍
代码文档生成器
创建高质量代码文档的专家。
基本原则
- 清晰 > 复杂 — 清晰比复杂更重要
- 渐进式呈现 — 从概览到细节
- 一致性 — 格式统一
- 准确性 — 与代码保持同步
- 易用性 — 适合不同水平的开发者
JSDoc(JavaScript/TypeScript)
/**
* Calculates the total price including tax and discounts.
*
* @param {number} basePrice - The original price before modifications
* @param {number} taxRate - Tax rate as decimal (e.g., 0.21 for 21%)
* @param {number} [discount=0] - Optional discount as decimal
* @returns {number} The final calculated price
* @throws {Error} If basePrice or taxRate is negative
*
* @example
* // Calculate price with 21% tax and 10% discount
* const total = calculateTotalPrice(100, 0.21, 0.10);
* // Returns: 108.90
*/
function calculateTotalPrice(basePrice, taxRate, discount = 0) {
if (basePrice < 0 || taxRate < 0) {
throw new Error('Price and tax rate must be non-negative');
}
const discountedPrice = basePrice * (1 - discount);
return discountedPrice * (1 + taxRate);
}
使用 JSDoc 的 TypeScript
/**
* User service for managing user operations.
*/
export class UserService {
/**
* Creates a new user in the system.
*
* @param userData - The user data for registration
* @returns Promise resolving to the created user
* @throws {ValidationError} When user data is invalid
* @throws {DuplicateError} When email already exists
*
* @example
* const user = await userService.createUser({
* email: '[email protected]',
* name: 'John Doe'
* });
*/
async createUser(userData: CreateUserDTO): Promise<User> {
// Implementation
}
/**
* Retrieves a user by their unique identifier.
*
* @param id - The user's UUID
* @returns The user if found, null otherwise
*/
async getUserById(id: string): Promise<User | null> {
// Implementation
}
}
Python Docstrings(Google 风格)
def process_transaction(
amount: float,
currency: str,
metadata: dict | None = None
) -> TransactionResult:
"""Process a financial transaction with validation and logging.
This function handles the complete transaction lifecycle including
validation, processing, and audit logging. It supports multiple
currencies and optional metadata attachment.
Args:
amount: The transaction amount in the specified currency.
Must be positive and not exceed the daily limit.
currency: ISO 4217 currency code (e.g., 'USD', 'EUR').
metadata: Optional dictionary with additional transaction
details. Keys 'reference' and 'notes' are recommended.
Returns:
TransactionResult containing:
- transaction_id: Unique identifier for the transaction
- status: 'completed', 'pending', or 'failed'
- timestamp: UTC datetime of processing
- fee: Applied transaction fee
Raises:
ValidationError: If amount is negative or exceeds limits.
CurrencyNotSupportedError: If currency code is invalid.
InsufficientFundsError: If account balance is too low.
Example:
>>> result = process_transaction(
... amount=100.50,
... currency='USD',
... metadata={'reference': 'INV-001'}
... )
>>> print(result.transaction_id)
'txn_abc123xyz'
Note:
Transactions over $10,000 require additional verification
and may be held for compliance review.
"""
pass
Python Docstrings(NumPy 风格)
def calculate_statistics(
data: np.ndarray,
weights: np.ndarray | None = None,
axis: int = 0
) -> dict:
"""
Calculate weighted statistics for the input data.
Parameters
----------
data : np.ndarray
Input data array of shape (n_samples, n_features).
weights : np.ndarray, optional
Weight array of shape (n_samples,). If None, uniform
weights are used.
axis : int, default=0
Axis along which to compute statistics.
Returns
-------
dict
Dictionary containing:
- 'mean' : np.ndarray
Weighted mean values.
- 'std' : np.ndarray
Weighted standard deviation.
- 'median' : np.ndarray
Weighted median values.
Raises
------
ValueError
If data and weights have incompatible shapes.
TypeError
If data is not a numpy array.
See Also
--------
numpy.average : Compute weighted average.
scipy.stats.describe : Compute descriptive statistics.
Examples
--------
>>> data = np.array([[1, 2], [3, 4], [5, 6]])
>>> stats = calculate_statistics(data)
>>> stats['mean']
array([3., 4.])
"""
pass
REST API 文档
# OpenAPI/Swagger style
paths:
/api/users:
post:
summary: Create a new user
description: |
Creates a new user account with the provided information.
Email must be unique across the system.
tags:
- Users
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateUserRequest'
example:
email: "[email protected]"
name: "John Doe"
role: "member"
responses:
'201':
description: User created successfully
content:
application/json:
schema:
$ref: '#/components/schemas/User'
'400':
description: Invalid request data
'409':
description: Email already exists
Markdown API 文档
## Create User
Creates a new user account.
**Endpoint:** `POST /api/users`
**Authentication:** Bearer token required
### Request Body
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| email | string | Yes | User's email address |
| name | string | Yes | Full name (2-100 chars) |
| role | string | No | Role: "admin", "member" (default) |
### Example Request
```json
{
"email": "[email protected]",
"name": "John Doe",
"role": "member"
}
响应
201 已创建
{
"id": "usr_abc123",
"email": "[email protected]",
"name": "John Doe",
"role": "member",
"createdAt": "2024-01-15T10:30:00Z"
}
错误响应
| 代码 | 描述 |
|---|---|
| 400 | 请求数据无效 |
| 401 | 未授权 |
| 409 | 邮箱已存在 |
## README Template
```markdown
# Project Name
Brief description of what this project does.
## Features
- Feature 1
- Feature 2
- Feature 3
## Quick Start
```bash
npm install project-name
import { Client } from 'project-name';
const client = new Client({ apiKey: 'your-key' });
const result = await client.doSomething();
前置条件
- Node.js 18+
- npm 8+
安装
# Using npm
npm install project-name
# Using yarn
yarn add project-name
配置
| 变量 | 默认值 | 描述 |
|---|---|---|
| API_KEY | - | 您的 API 密钥(必填) |
| TIMEOUT | 30000 | 请求超时时间(毫秒) |
| DEBUG | false | 启用调试日志 |
贡献
请参阅 CONTRIBUTING.md
许可证
MIT
## Inline Comments
```javascript
// GOOD: Explain WHY, not WHAT
// Skip validation for internal requests to improve performance
// External requests are validated at the API gateway
if (request.isInternal) {
return processDirectly(data);
}
// BAD: States the obvious
// Check if user is null
if (user === null) {
return null;
}
// GOOD: Document complex logic
// Using binary search for O(log n) lookup in sorted array
// Linear search would be O(n) for 10k+ items
const index = binarySearch(sortedItems, targetId);
// GOOD: Explain business rules
// Orders over $1000 require manager approval per policy DOC-123
// This threshold was set by finance team in Q3 2023
if (order.total > 1000 && !order.hasManagerApproval) {
throw new ApprovalRequiredError();
}
文档自动化
TypeDoc
{
"typedocOptions": {
"entryPoints": ["src/index.ts"],
"out": "docs",
"plugin": ["typedoc-plugin-markdown"],
"readme": "README.md",
"excludePrivate": true,
"excludeInternal": true
}
}
Sphinx(Python)
# conf.py
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx.ext.viewcode',
'sphinx_autodoc_typehints'
]
autodoc_default_options = {
'members': True,
'undoc-members': True,
'show-inheritance': True
}
最佳实践
- 记录公共 API — 所有导出的内容
- 代码示例 — 真实用例
- 同步更新 — 文档是 PR 的一部分
- 使用代码检查工具 — eslint-plugin-jsdoc、pydocstyle
- 进行版本管理 — 文档应与代码版本保持一致
评论
支持 Markdown