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 工作流)

目标:给"笔记"应用加"回收站"功能。

Plan 模式描述需求

OpenCode 输出计划

你反馈/补充

切回 Build 执行

权限确认 y

完成 + 展示 diff

步骤:

  1. Tab切到Plan模式。
  2. 输入需求:
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.
  1. 可拖入设计稿图片作为参考,追加:“Use this design as reference.”
  2. 满意后Tab切回Build,执行:Sounds good! Go ahead and make the changes.
  3. 对权限提示按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:为代码补充单元测试

目标:给核心模块加测试。

  1. Plan 模式:
Write unit tests for the validation logic in @src/utils/validate.ts using the project's existing test framework. Cover edge cases.
  1. Build 执行后,/compact压缩上下文,再让其"补充边界用例"。

要点:让 OpenCode 先看项目里已有测试的风格(@tests/...)保持一致。


案例 5:GitHub 评论触发自动化

目标:在 Issue 中让 OpenCode 自动调研并开 PR。

  1. 安装:opencode github install(引导配置 Actions 与 Secret)。
  2. 在 Issue 评论:
/opencode investigate this bug and open a PR with a fix
  1. OpenCode 会在新分支修复并提 PR;支持事件:issue_commentpull_request_review_commentissuespull_requestschedule

工作流示意:

Issue 评论 /oc

GitHub Actions 触发

OpenCode 新建分支修复

自动提交 PR


案例 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 解释代码@引用//init04
2 新功能Plan/Build / 权限04
3 调试重构diff //undo04
4 单测风格对齐04/05
5 GitHubgithub install05/06
6 批处理run/serve06

做完这 6 个,你已基本熟练。最后查漏补缺见08-常见问题与最佳实践.md


本篇为 OpenCode 操作指导书系列之一,版本 v1.18.3。