07-实战案例
OpenCode 操作指导书(七):实战案例
适用版本:OpenCode v1.18.3
本篇目标:通过 6 个可照做的真实案例,把前六篇的能力串成肌肉记忆。每个案例含"目标 / 步骤 / 提示词 / 要点"。
案例 1:解释陌生代码库
目标:接手新项目,快速理解认证逻辑。
cd/path/to/unknown-project opencode /init# 先生成 AGENTS.md对话:
How is authentication handled in @packages/functions/src/api/index.ts? Walk me through the request lifecycle from entry to DB.要点:用@文件精准引用;可连续追问"那错误如何处理?"。
案例 2:新增功能(Plan → Build 工作流)
目标:给"笔记"应用加"回收站"功能。
步骤:
Tab切到Plan模式。- 输入需求:
When a user deletes a note, flag it as deleted in the database. Then create a screen that shows all recently deleted notes, where the user can undelete or permanently delete.- 可拖入设计稿图片作为参考,追加:“Use this design as reference.”
- 满意后
Tab切回Build,执行:Sounds good! Go ahead and make the changes. - 对权限提示按
y允许;review diff。
案例 3:调试与重构
目标:定位并修复一个性能问题,再重构。
There's a slow query in @packages/functions/src/notes.ts listNotes(). Profile it and suggest a fix, then implement it.重构练习:
Refactor the function in @packages/functions/src/api/index.ts to reduce nesting. Show me the diff before committing.回退:/undo若结果不如预期。
案例 4:为代码补充单元测试
目标:给核心模块加测试。
- Plan 模式:
Write unit tests for the validation logic in @src/utils/validate.ts using the project's existing test framework. Cover edge cases.- Build 执行后,
/compact压缩上下文,再让其"补充边界用例"。
要点:让 OpenCode 先看项目里已有测试的风格(@tests/...)保持一致。
案例 5:GitHub 评论触发自动化
目标:在 Issue 中让 OpenCode 自动调研并开 PR。
- 安装:
opencode github install(引导配置 Actions 与 Secret)。 - 在 Issue 评论:
/opencode investigate this bug and open a PR with a fix- OpenCode 会在新分支修复并提 PR;支持事件:
issue_comment、pull_request_review_comment、issues、pull_request、schedule。
工作流示意:
案例 6:批处理脚本调用(CI / 自动化)
目标:用run对一批文件做说明生成,写入文档。
# 启动无头服务(避免每次冷启动 MCP)opencode serve&forfinsrc/*.ts;doopencode run--attachhttp://localhost:4096\"Summarize the public API of @$fin one paragraph"\>>api-docs.mddone或单次非交互:
opencode run"List all TODO comments in the repo and group by file"--formatjson综合练习清单
| 案例 | 用到的能力 | 对应篇章 |
|---|---|---|
| 1 解释代码 | @引用//init | 04 |
| 2 新功能 | Plan/Build / 权限 | 04 |
| 3 调试重构 | diff //undo | 04 |
| 4 单测 | 风格对齐 | 04/05 |
| 5 GitHub | github install | 05/06 |
| 6 批处理 | run/serve | 06 |
做完这 6 个,你已基本熟练。最后查漏补缺见08-常见问题与最佳实践.md。
本篇为 OpenCode 操作指导书系列之一,版本 v1.18.3。