代码文档自动生成:从函数签名到注释的 AI 撰写
FreeGuideOnline
最新
2026-06-25
typescript function distance(x1: number, y1: number, x2: number, y2: number, unit: 'km' | 'mile' = 'km'): number { const dx = x2 - x1; const dy = y2 - y1; const raw = Math.sqrt(dx * dx + dy * dy); return unit === 'mile' ? raw * 0.621371 : raw; }
### 步骤 1:触发 AI 文档生成
在 VS Code 中,光标定位到函数上方,输入 `/**` 并回车(Copilot 启用时),它会自动补全 JSDoc 注释:
```typescript
/**
* 计算两个点之间的欧几里得距离,支持公里/英里转换
* @param x1 - 起点 x 坐标
* @param y1 - 起点 y 坐标
* @param x2 - 终点 x 坐标
* @param y2 - 终点 y 坐标
* @param unit - 距离单位,默认为公里
* @returns 两点距离,单位由 unit 参数决定
*/
这个生成过程 AI 做了这些事:
- 从函数名
distance推断出计算距离; - 从参数名
x1, y1, x2, y2识别为坐标; - 从参数类型
'km' | 'mile'和默认值理解单位选项; - 发现返回类型
number且函数体存在单位转换,补充了单位信息。
步骤 2:优化生成的文档
AI 生成的内容可以作为初稿,你还需要根据项目规范进行人工微调:
- 补充边界说明:
@throws当坐标值非有限数字时; - 补充使用示例:
@example; - 统一语气:采用“计算”、“返回”等动词开头的句子。
步骤 3:集成到文档系统
有了完整的 JSDoc 注释后,可以配合 TypeDoc 生成静态 API 文档站点:
npx typedoc --out docs src/index.ts
生成的 HTML 中会包含上述文字描述、参数表格,以及自动提取的类型信息。
Python 中的 AI 文档生成
Python 社区的传统方案是 reStructuredText 或 Google 风格的 docstring,结合 Sphinx 进行渲染。借助 AI 工具(如 GitHub Copilot、Continue.dev 或本地 Ollama 模型),你可以这样生成文档:
代码片段:
def fetch_user_data(user_id: int, include_inactive: bool = False) -> dict:
response = requests.get(f"https://api.example.com/users/{user_id}")
data = response.json()
if not include_inactive and not data.get("active"):
raise ValueError("User is inactive")
return data
在 Copilot 协助下,输入 """ 后得到的 docstring:
"""
Retrieve user data from the remote API.
Args:
user_id: The unique identifier of the user.
include_inactive: If True, also return inactive users.
Defaults to False.
Returns:
A dictionary containing user profile fields.
Raises:
ValueError: If the user is inactive and include_inactive is False.
requests.exceptions.RequestException: On network error.
"""