Compare commits

...
Author SHA1 Message Date
ceo d0334434c5 fix:next/mine 漏掉空倉庫中的分派 issue(#43)
iterOrgRepos(issue 掃描,供 Mine 與 members --has-work)不再跳過
empty=true 的倉庫——Gitea 允許空倉庫持有 open issue(「初始化項目」
型工作),行為基準 gitea.py 的 for_all_repositories 掃 issue 時
本來就不檢查 empty;teai 先前過度套用了空倉庫跳過條件,導致
teai next 對 colony-tick-demo issue #1 回 null。

PR 掃描(iterOpenPulls)、stalled、milestone overview 維持跳過
空倉庫不變(與 gitea.py 一致)。附回歸測試兩則。
2026-09-13 08:45:48 +08:00
alex 5506daa5f5 Merge pull request 'feat+docs:tag 安裝支援(#38)——version 讀 build info、README 安裝章節改以 go install 為主' (#42) from feat/issue38-versioned-install into main 2026-09-13 00:32:55 +08:00
ceo 9a4887a677 docs:修正安裝章節版本顯示說明(複審 #42)——@v0.1.0 仍顯示 0.1.0-dev、clone 建置為 pseudo-version 2026-09-13 00:28:40 +08:00
ceo 02fad53aa4 Merge pull request 'dailyops:補齊 tea 對等指令(#40)' (#41) from feat/issue40-tea-parity into main 2026-09-13 00:14:17 +08:00
ceo 5a48fdd590 feat+docs:tag 安裝支援(#38)——version 讀 build info、README 安裝章節改以 go install 為主 2026-09-13 00:09:56 +08:00
max d01108bda3 移除建置產物 teai-bin,加入 .gitignore 2026-09-13 00:00:43 +08:00
max 3470a96392 dailyops:補齊 tea 對等指令(#40)— pulls approve/close/checkout、通用 comment、issues list --labels 2026-09-13 00:00:40 +08:00
ceo 36a50b95ed Merge pull request 'docs+test:空清單輸出判決定案(維持 []/null,補 stalled 空輸出測試)(#37)' (#39) from fix/issue37-empty-output-docs into main 2026-09-12 23:56:52 +08:00
chenyunda218 9e699f3b4e docs+test:空輸出判決 #37——維持 []/null、補 stalled 空輸出測試 2026-09-12 23:43:29 +08:00
queena d689107eea Merge pull request 'internal/workflow:directLastActivity 排除跨 issue 引用事件(#34)' (#36) from fix/issue34-direct-last-activity into main 2026-09-12 15:24:23 +08:00
ceo 027ed1ade9 workflow_test:fakeSource.OpenIssues 依 number 排序,消除 map 迭代隨機性
審核意見(PR #36):issue 1 與 issue 3 在新邏輯下同為 10h,
sort.SliceStable 平手時順序取決於 map 迭代隨機順序,
TestScanStalledIssueReasons 的 got[0].Number != 1 斷言不穩定。

採建議修法 1:fakeSource.OpenIssues 回傳前依 number 遞增排序,
對齊真實 Gitea API(issues 依 id 遞增)行為。實作未動。

go build / go vet / go test ./... 全綠;
TestScanStalledIssueReasons -count=50 重跑全綠。
2026-09-12 15:21:21 +08:00
ceo e4212b9c90 internal/workflow:directLastActivity 排除跨 issue 引用事件(#34)
同步 agents #34/#38/#40 三個停滯判定修補到 Go 端:

- Source 介面新增 IssueTimeline(GET /repos/{o}/{r}/issues/{n}/timeline,分頁),
  giteaapi.go 與 cmd/xcheck 同步實作
- 新增 directLastActivity:updated_at 晚於全部已知直接活動時拉 timeline 核對,
  排除 comment_ref/issue_ref 引用事件後取最晚;全為引用事件回退已知直接活動
  最晚時刻(agents #40);timeline 失敗保守沿用 updated_at
- considerIssue/considerPull 對自身 updated_at、childActivity 對子項 updated_at
  (含子項 created_at 入已知活動)套用同一排除邏輯(agents #38)
- 回歸測試:子項 updated_at 被引用刷新(TestRunStalledChildXrefRefresh)、
  timeline 全引用事件回退與拉取失敗保守路徑(TestRunStalledTimelineAllXrefFallback)
- 修正 workflow_test.go:timelines 須在 ScanStalled 呼叫前設定

驗證:go build/vet/test 全綠;xcheck 對真實 API 掃描,
stalled 輸出與 gitea.py(agents @ 78769ec)位元組一致(5833 bytes)。
2026-09-12 15:10:31 +08:00
queena a2baf55fce Merge pull request 'dailyops:list 命令 --state all 明確帶 state=all(#33)' (#35) from fix/issue33-state-all into main 2026-09-11 11:32:53 +08:00
chenyunda218 1f6806ff99 dailyops:list 命令 --state all 明確帶 state=all(#33)
issues/milestones 端點省略 state 時 API 預設 open,closed 項目漏列;
pulls 端點省略時雖回全部,仍明確帶上避免依賴端點預設。三處同修並補
回歸測試(TestStateAllSendsExplicitParam)。
2026-09-11 11:29:00 +08:00
ceo 87d00ae440 Merge pull request 'milestones:跨倉庫里程碑總覽命令(#31)' (#32) from feat/issue31-milestones-overview into main 2026-09-10 21:26:39 +08:00
chenyunda218 744e7ad809 milestones:新增跨倉庫里程碑總覽命令(#31)
- teai milestones(不帶 --repo)輸出跨所屬組織各倉庫 open 里程碑概況,
  對應 gitea.py milestones(管理者巡邏,agents AGENTS.md 10.1):
  欄位 repo/id/title/url/open_issues/closed_issues/due_on/due_hours/
  overdue/unassigned/updated_at,排序期限近者在前、無期限最後。
- internal/workflow.MilestoneOverview:判定核心(Source 注入、離線可測);
  MilestoneEntry 自訂 MarshalJSON,鍵集鍵序與 gitea.py 全等
  (null 表示、due_hours 定點一位、unassigned PR 條目帶 author)。
- internal/workflow.APIClient 增 OpenMilestones/MilestoneOpenIssues
  (issues 端點刻意不帶 type=issues,PR 條目保留供覆蓋檢查,同 gitea.py)。
- milestones --repo a/b 維持現行單倉庫 list 語義不變。
- 空清單輸出 [](gitea.py 無輸出;#26 慣例差異,README 已文件化)。
- 交叉驗證:同帳號同時跑 gitea.py milestones 與 teai milestones,
  含逾期/未到期/無期限里程碑與未分派 issue/PR 條目,輸出位元組全等。
2026-09-10 21:20:19 +08:00
chenyunda218 fd3b8cbd6b Merge pull request 'docs:已知輸出差異補 mine/pulls 欄位集差異(#26)' (#27) from docs/issue26-output-fieldset-diff into main
Reviewed-on: #27
2026-09-10 18:51:29 +08:00
queena 3a587f60ad Merge pull request 'internal/cli:允許命令旗標與位置參數交錯(#25)' (#28) from fix/issue25-interleaved-flags into main 2026-09-10 15:38:37 +08:00
alex 3ed20b6aba internal/cli:允許命令旗標與位置參數交錯(#25)
parseFlags 改為先分離旗標與位置參數、再剖析旗標串、最後以第二次
Parse 把位置參數設回 fs.Args;Go 標準 flag 遇位置參數即停止的問題
不再影響「位置參數在前、旗標在後」的用法(teai api --method、
issues/pulls view --comments 等照 README 範例可用了)。

- login.go/workflow_commands.go 直接呼叫 fs.Parse 的六處改走
  parseFlags,行為一致(login default/remove 的名稱也可與旗標交錯)。
- errHelp(命令 -h/--help)在 exitCodeFor 視為成功,與其既有註解
  宣稱一致;命令層 -h 結束碼由 1/2 修正為 0。
- 新增 interleaved_flags_test.go 回歸測試:api/issues view/
  pulls view/stalled/login default/login remove 的交錯組合。
2026-09-10 15:35:16 +08:00
ceo 3d555e38d9 docs:已知輸出差異補 mine/pulls 欄位集差異(#26)
gitea.py 的 mine/pulls 輸出完整 API 物件是 _dump 直接傾倒的副作用,
欄位集隨 Gitea 版本浮動;teai 維持策展摘要欄位(機器可讀優先),
交叉驗證比對項目集合與判定語義,不逐欄位比對。判定 #26。
2026-09-10 15:24:09 +08:00
alex ffae335e62 Merge pull request 'internal/cli:stalled 與 xrefs 命令接線,完成 #7 CLI 層(堆疊於 #23)' (#24) from feat/issue7-cli-stalled-xrefs into main 2026-09-10 12:30:10 +08:00
ceo ab94cdce9f internal/cli:stalled 與 xrefs 命令接線,完成 #7 CLI 層(堆疊於 #23)
- workflow 新增 StalledSource 介面(Source+CurrentUser+GetIssue)與
  高階入口 RunStalled/ResolveIssueXrefs(xrefs 輸出附 source 出處)
- APIClient 補上 StalledSource 面向(GetIssue/TryGetIssue 等)
- CLI 新增 teai stalled [--hours N](JSON 與 gitea.py 位元組相容:
  停用 HTML 轉義、縮排 2)與 teai xrefs <owner>/<repo> <number>
  (404 → exit 3);table 模式 stalled_hours 定點一位小數
- 接線層與 workflow 層單元測試(注入假資料源、固定時刻)
- README 狀態行更新

驗證:go build/vet/test 全綠;對真實 API 並行掃描,stalled 輸出
與 gitea.py 位元組一致(2169 bytes);xrefs 邊界案例(PR#50/
issue#49 略過、CJK 緊鄰、跨倉庫 owner/repo#N)與 Python 版一致。
2026-09-10 12:20:39 +08:00
chenyunda218 32c3b30934 Merge pull request 'internal/workflow:統一型別宣告,修復 main 編譯失敗(#21)' (#23) from fix/issue21-workflow-types into main
Reviewed-on: #23
2026-09-10 11:45:39 +08:00
ceo 5f323a685e 合併 main(47056dd)保持 #23 分支最新 2026-09-10 11:41:49 +08:00
ceo 4582dfaa4e internal/workflow:統一型別宣告,修復 #12 合併後 main 編譯失敗(#21)
#12 的 workflow.go 與 #13 的 types.go 各自宣告 User/Comment/Issue/
PullRequest/Repository,文字合併無衝突但語意衝突,main 自 a8c1f3e 起
go build 失敗。

統一採 #13 的字串模型(types.go 為唯一型別來源):
- Issue/Comment 補 State/Body/ClosedAt 欄位,新增 parseMoment
  (對應 gitea.py _parse_iso8601;保留原時區偏移,輸出與 Python
  isoformat 位元組一致)
- workflow.go 移除重複宣告,stalled/xref 邏輯改用該模型與 judge.go
  既有輔助(AssigneeNames/ReviewerNames/LastComment/containsString)
- Source 介面 number 改 int64(與 types.go 對齊),cmd/xcheck 同步
- workflow_test.go 測試資料改新型別模型(字串時刻、指標欄位)

驗證:
- go build/go vet/go test ./... 全綠(#6 與 #7 案例皆未回歸)
- xcheck 對真實 API 並行掃描,stalled 輸出與 gitea.py 位元組一致(含
  bear-cli#9 父追蹤項子項摘要、+08:00 時區偏移)
- xref 邊界案例(nope#9/PR#50 略過、bear-cli#9 內嵌解析)與 Python 一致
2026-09-10 11:32:40 +08:00
alex 47056dda43 Merge pull request 'docs:README 補上完整安裝指南(#15)' (#22) from docs/issue15-install-guide into main 2026-09-10 11:26:25 +08:00
ceo 9948357f52 docs:README 補上完整安裝指南(#15) 2026-09-10 10:48:12 +08:00
alex 0b0c3cefcb Merge pull request 'internal/cli:命令保留旗標機制,修正 login add 旗標被全域剖析搶走(#18)' (#20) from fix/issue18-reserved-flags into main 2026-09-10 10:37:20 +08:00
queena a8c1f3e018 Merge pull request 'internal/workflow:xref 解析與 stalled 掃描核心邏輯(#7)' (#12) from feat/issue7-stalled-xrefs into main 2026-09-10 10:35:35 +08:00
max 0ed6f262c8 合併 main(4a34def)並把 exitcode_test.go 四處 extractGlobals 呼叫補上第三參數 nil(#20) 2026-09-10 10:32:53 +08:00
max fb2990dc04 Merge remote-tracking branch 'origin/main' into fix/issue18-reserved-flags 2026-09-10 10:32:19 +08:00
ceo 67cafcff59 cmd/xcheck:帳號改由 /user API 取得,移除 USERNAME 預設 ceo(審核意見)
依 #12 第二輪審核意見:xcheck 原以 USERNAME 環境變數取帳號、
未設時靜默退回 ceo,與 gitea.py find_stalled_work 的
get_current_username()(打 /user 取 token 實際帳號)不同源。
非 ceo 帳號跑 xcheck 時催促冷卻會以錯誤身分套用,造成漏掃,
兩版輸出表面位元組相同實則基準錯誤。

改法:apiSource 新增 CurrentUser(),呼叫 /user 並依
username → login 取值;失敗或取不到帳號即報錯退出,
不靜默退回任何預設。移除 USERNAME 環境變數與 ceo fallback。

驗證:go build/go vet/go test 全綠(16 個測試函式);
 USERNAME 未設下 xcheck 與 gitea.py stalled 並行交叉驗證,
輸出位元組相同(1749B cmp IDENTICAL)。
2026-09-10 10:30:46 +08:00
ceo 4a34def1f5 Merge pull request 'gitea.py 工作流命令 Go 化:whoami/orgs/members/pulls/mine/next(#6)' (#13) from feature/issue6-workflow-commands into main 2026-09-10 10:24:21 +08:00
ceo 15c2d35935 合併 main(#16/#17)並解 cli.go 衝突
衝突原因:#13(本分支 927855d)與 #16(main 7badd9e)各自實作了
同一問題(帶旗標命令被全域剖析攔下)的抽取式修正。採 main 現行
架構(dispatch 內 extractGlobals)為準,並保留本分支的:

- runVersion 參數檢查(version 不接受參數,TestWiringVersionRejectsArgs)
- workflow 命令與接線層測試(workflow_commands_test.go)

go build/vet/gofmt 綠;單元測試僅餘 main 既有回歸
(3 個 login 測試,#16 合併後即失敗,與本 PR 無關)。
2026-09-10 10:22:42 +08:00
queena f7d63d6e8f Merge pull request '測試改斷言具體結束碼數值,對照 README 規格(#10)' (#19) from fix/issue10-exitcode-tests into main 2026-09-10 10:20:23 +08:00
chenyunda218 f481377b9a 測試改斷言具體結束碼數值,對照 README 規格(#10)
cli_test、dailyops_commands_test、login_test、exitcode_test 原以
int(ExitUsage)/int(ExitAPI)/int(ExitInternal) 常數互比,常數若再
與 README 脫鉤測試仍會綠。改為直接斷言 0/2/3(內部錯誤 1)。

常數本體已隨 #5(6951817)改為明確數值,未知命令實測回 2。
2026-09-10 10:12:35 +08:00
ceo b2dd2f3aac 修正 JSON 位元組相容與 xref Unicode 邊界(審核意見)
依 #12 審核意見修正四項偏差,並補一項同源問題:

1. iterXrefs 前一字元檢查改 Unicode:isWordChar 改用
   unicode.IsLetter/IsDigit,且以 utf8 正確解碼前一 rune
   (原版只認 ASCII 又取單一位元組)。另補齊 Python finditer
   的重試語義:起點被 lookbehind 擋下時從下一 rune 重試,
   否則「修復bear-cli#9」會整段丟失(Python 匹配後半 cli#9);
   lookbehind 字元集含 #(##5 不匹配)。
2. writeJSON 改 json.Encoder + SetEscapeHTML(false):
   Python ensure_ascii=False 不轉義 <、>、&,json.Marshal 預設
   會,標題含這些字元即失去位元組相容。
3. stalled_hours 改 strconv.FormatFloat(v,'f',1,64):整數值輸出
   48.0(原 %g 輸出 48,極大值還會變 1e+06)。
4. Child.last_activity_at 無可解析時刻時輸出 null(原輸出 ""),
   型別改 *string;格式對齊 FormatMoment(UTC 記 +00:00 非 Z)。
5. cmd/xcheck 輸出同樣停用 HTML 轉義(Marshal* 對自訂
   MarshalJSON 的輸出仍會轉義)。

驗證:go build/vet/test 全綠(16 測試函式,新增 CJK、##5、
全形數字、HTML 字元、48.0、null 等案例);cmd/xcheck 與
gitea.py stalled 對真實 API 並行掃描輸出位元組相同(1749B,
含 bear-cli#9 父追蹤項與 5 子項摘要);--xrefs 對 CJK
邊界輸入與 Python 一致。
2026-09-10 09:47:46 +08:00
chenyunda218 927855d3ca cli:修正帶旗標命令被全域剖析攔下的阻斷問題(#13 審核)
- parseGlobals 改為抽取式 extractGlobals:只取走已知全域選項,非全域
  選項(--has-work/--mine/--reviewer/--repo)原樣交回子命令 flagset,
  任何順序(含與全域選項交錯)皆可解析;-- 之後停止抽取。
- runVersion 補參數檢查:version --wat 仍回 exit 2。
- workflow:commentsFor 對 number<=0 視為無留言,不打 API(對齊 gitea.py
  在 number 缺漏時跳過留言檢查,避免 issues/0/comments 404 中斷掃描)。
- 新增 internal/cli/workflow_commands_test.go:以注入假 client 的接線層
  測試補上 workflow 單元測試覆蓋不到的分派路徑(members --has-work、
  pulls --mine/--reviewer/--repo、全域選項交錯、next null/table)。
- README:註明與 gitea.py 的已知輸出差異(空清單 [] vs 無輸出;
  全域選項可出現在命令前後)。

實機交叉驗證(alex):members --has-work、pulls --mine/--reviewer、
pulls --repo、next、mine 兩者輸出一致;go vet/test 全綠。
2026-09-10 09:41:53 +08:00
ceo a86803d336 internal/workflow:xref 解析與 stalled 掃描核心邏輯(#7)
完整移植 gitea.py 的 _resolve_xref_targets 與 find_stalled_work:
- xref:#N/repo#N/owner/repo#N;單段 repo 僅在存在於組織時解析
  (PR#50、issue#49 這類寫法自動略過);owner 需為所屬組織。
  Go regexp 無 lookbehind,掃描時檢查前一字元等價實作。
- stalled:reason 分類(issue:no-assignee/assignee-idle/no-commenter/
  waiting-outside/parent-tracking;PR:no-reviewer/author-idle/
  reviewer-idle/no-commenter)、24h 催促冷卻、父追蹤項把子項活動
  (留言、state 變更、PR 合併)計入 last_activity、上行引用不採計。
- 資料以 Source 介面注入:邏輯離線可測,CLI 接線待 #5 基礎建設。
- 輸出 JSON 與 gitea.py 位元組相容(鍵序、assignees/author 欄位、
  isoformat 時刻、round(x,1) 半偶數舍入)。
- cmd/xcheck:交叉驗證工具(--xrefs 與停滯掃描模式),已對真實 API
  與 gitea.py 並行比對,輸出一致。

go build/vet/test 全綠;單元測試覆蓋 xref 邊界與 stalled 判定。
2026-09-10 08:36:31 +08:00
29 changed files with 4772 additions and 96 deletions
+1
View File
@@ -19,3 +19,4 @@ coverage.*
# 作業系統 # 作業系統
.DS_Store .DS_Store
Thumbs.db Thumbs.db
teai-bin
+132 -8
View File
@@ -6,17 +6,72 @@ teai 是 Gitea 的命令列(CLI)工具,以更完整、更可靠的方式
- **語言:** Go(與 Gitea 本體一致),僅用標準庫,離線可建置 - **語言:** Go(與 Gitea 本體一致),僅用標準庫,離線可建置
- **目標站點:** `https://gitea.alterminal.com` - **目標站點:** `https://gitea.alterminal.com`
- **狀態:** 基礎建設(#5:internal/gitea)、工作流命令(#6:whoami/orgs/members/mine/pulls/next)與日常操作命令(#8:issues/pulls/labels/milestones/releases/repos/api)已實作;stalled/xrefs(#7)進行中 - **狀態:** 基礎建設(#5:internal/gitea)、工作流命令(#6:whoami/orgs/members/mine/pulls/next)、日常操作命令(#8:issues/pulls/labels/milestones/releases/repos/api)與管理者巡邏命令(#7:stalled/xrefs)已實作
- **範圍(#3):** 不避開 tea 已有的功能;單一工具涵蓋完整操作 - **範圍(#3):** 不避開 tea 已有的功能;單一工具涵蓋完整操作
## 安裝與建置 ## 安裝與建置
需要 Go 1.26 以上。 ### 需求
- **Go 1.26 以上**(`go version` 確認;本倉庫僅用標準庫,離線可建置)
- **git**
- Gitea 帳號的 **API token**(設定階段使用;在 Gitea「設定 → 應用程式」產生)
### 以 go install 安裝(建議)
自 v0.1.0 起 module 已發佈 tag,可直接以版本安裝(二元檔裝進 `GOBIN`,預設 `~/go/bin`):
```sh ```sh
go build -o teai ./cmd/teai go install gitea.alterminal.com/alterminal/teai/cmd/teai@latest # 最新 tag(亦可 @v<版本> 指定)
teai version # 驗證:顯示安裝的 tag 版本(見下方說明)
``` ```
本 module 為公開倉庫,預設 `GOPROXY`/`GOSUMDB` 即可解析(已於乾淨環境驗證)。
若所在網路環境無法經公用 proxy 抓取,可改設 `GOPRIVATE=gitea.alterminal.com`
(略過 proxy 與 checksum database,直接從 Gitea 抓取)。
`teai version` 顯示建入的 module 版本,即安裝指定的 tag(如 `v0.1.1`)。
注意:讀 build info 顯示安裝版本的支援,自包含該變更的 tag 起(v0.1.1)才生效——
v0.1.0 早於此變更,以 `@v0.1.0` 安裝(或此變更前的 `@latest`)仍顯示舊行為 `0.1.0-dev`。
### 從原始碼建置(開發用)
開發、離線或想鎖定特定 commit 時,clone 後自行建置:
```sh
git clone https://gitea.alterminal.com/alterminal/teai.git
cd teai
go build -o teai ./cmd/teai
install -Dm755 teai ~/.local/bin/teai # 或複製到任何 PATH 內目錄
teai version # 驗證:teai version v0.1.1-0.<時間戳>-<commit>(見下方說明)
```
也可以在 clone 目錄內直接裝進 `GOBIN`:
```sh
go install ./cmd/teai
```
clone 建置時 Go 會把 VCS 狀態寫進 build info:位於 tag 上顯示該 tag、
其後的 commit 顯示 pseudo-version(如 `v0.1.1-0.20260912160956-5a48fdd590b2`)、
工作樹有修改再附加 `+dirty`;無 VCS 資訊(如從 tarball 解壓建置)時
`Main.Version` 為 `(devel)`,此時退回開發版本號 `0.1.0-dev`。
### 登入設定(首次使用)
teai 與 `tea` 共用同一份組態檔;若 `tea whoami` 已可正常輸出,可跳過本節。
```sh
teai login add --url https://gitea.alterminal.com
# 未給 --token 時自 stdin 讀一行:貼上 token 後按 Enter(不會進 shell 歷史)
teai whoami # 驗證:應輸出 {"username":"<你的帳號>"}
```
- token 驗證失敗(HTTP 401)不會寫入組態,結束碼 3。
- 組態檔:`--config`/`TEA_CONFIG` 指定,預設 `~/.config/tea/config.yml`;teai 採行級編輯,
不會改壞 tea 也在使用的欄位,檔案權限 `0600`。
- 多站台以 `--name` 區分、`teai login default <名稱>` 切換預設;詳見下方 [`teai login`](#teai-login--管理登入) 一節。
## 指令設計 ## 指令設計
> 工作流規則的唯一來源是 [`alterminal/agents`](https://gitea.alterminal.com/alterminal/agents) 的 `AGENTS.md`; > 工作流規則的唯一來源是 [`alterminal/agents`](https://gitea.alterminal.com/alterminal/agents) 的 `AGENTS.md`;
@@ -37,20 +92,27 @@ issues/pulls/labels/milestones/releases/repos/api 的日常操作,
```sh ```sh
# issues # issues
teai issues list --repo <owner>/<repo> [--state open|closed|all] teai issues list --repo <owner>/<repo> [--state open|closed|all] [--labels a,b] # 多標籤 AND
teai issues view --repo <owner>/<repo> <number> [--comments] teai issues view --repo <owner>/<repo> <number> [--comments]
teai issues create --repo <owner>/<repo> --title … [--body …] [--assignees a,b] --yes teai issues create --repo <owner>/<repo> --title … [--body …] [--assignees a,b] --yes
teai issues close --repo <owner>/<repo> --yes <number> teai issues close --repo <owner>/<repo> --yes <number>
teai issues comment --repo <owner>/<repo> --body … --yes <number> teai issues comment --repo <owner>/<repo> [--body …] --yes <number> [留言…] # 位置參數優先(#40)
# pulls(無子命令仍是工作流清單:--mine/--reviewer/--repo) # pulls(無子命令仍是工作流清單:--mine/--reviewer/--repo)
teai pulls list --repo <owner>/<repo> [--state open|closed|all] teai pulls list --repo <owner>/<repo> [--state open|closed|all]
teai pulls view --repo <owner>/<repo> <number> [--comments] teai pulls view --repo <owner>/<repo> <number> [--comments]
teai pulls create --repo <owner>/<repo> --head <branch> [--base main] --title … [--body …] --yes teai pulls create --repo <owner>/<repo> --head <branch> [--base main] --title … [--body …] --yes
teai pulls merge --repo <owner>/<repo> [--style merge|rebase|rebase-merge|squash] --yes <number> teai pulls merge --repo <owner>/<repo> [--style merge|rebase|rebase-merge|squash] --yes <number>
teai pulls comment --repo <owner>/<repo> --body … --yes <number> teai pulls approve --repo <owner>/<repo> [--body …] --yes <number> [意見…] # POST reviews,event=APPROVED(#40)
teai pulls close --repo <owner>/<repo> --yes <number> # 關閉不合併(PATCH state=closed;#40)
teai pulls checkout --repo <owner>/<repo> [--dir <path>] <number> # 本機 git 取得 head(#40)
teai pulls comment --repo <owner>/<repo> [--body …] --yes <number> [留言…]
# 通用留言(tea comment 對等;issue 與 PR 共用端點,#40)
teai comment --repo <owner>/<repo> [--body …] --yes <number> [留言…]
# labels/milestones/releases/repos # labels/milestones/releases/repos
teai labels list --repo <owner>/<repo> teai labels list --repo <owner>/<repo>
teai labels create --repo <owner>/<repo> --name … [--color #RRGGBB] [--description …] --yes teai labels create --repo <owner>/<repo> --name … [--color #RRGGBB] [--description …] --yes
teai milestones # 跨倉庫 open 里程碑總覽(gitea.py milestones 對應;期限近者在前)
teai milestones --repo <owner>/<repo> # 同 milestones list(單倉庫,維持既有語義)
teai milestones list --repo <owner>/<repo> [--state open|closed|all] teai milestones list --repo <owner>/<repo> [--state open|closed|all]
teai milestones create --repo <owner>/<repo> --title … [--description …] [--due RFC3339] --yes teai milestones create --repo <owner>/<repo> --title … [--description …] [--due RFC3339] --yes
teai releases list --repo <owner>/<repo> teai releases list --repo <owner>/<repo>
@@ -59,8 +121,9 @@ teai repos list [--org <org>]
teai api <path> [--method GET|POST|PATCH|DELETE] [--data '<json>'] [--yes] teai api <path> [--method GET|POST|PATCH|DELETE] [--data '<json>'] [--yes]
``` ```
> `--yes` 閘門:所有寫入類命令(create/close/comment/merge/labels create/milestones create/api 非 GET 動詞)未帶 `--yes` 時回 exit 2(用法錯誤),且不發出任何 HTTP 請求。 > `--yes` 閘門:所有寫入類命令(create/close/comment/merge/approve/labels create/milestones create/api 非 GET 動詞)未帶 `--yes` 時回 exit 2(用法錯誤),且不發出任何 HTTP 請求。
> `teai api` 的 path 內含查詢字串(如 `/repos/a/b/issues?state=closed`)時會正確傳遞。 > `teai api` 的 path 內含查詢字串(如 `/repos/a/b/issues?state=closed`)時會正確傳遞。
> `teai pulls checkout` 是本機唯讀輔助:同倉庫 head 在 `--dir`(預設當前目錄)的既有工作樹 `git fetch origin <ref> && git checkout -B <ref> FETCH_HEAD`;跨倉庫 head 需 `--dir`(新目錄)執行 `git clone --branch <ref> <clone_url>`。teai 不代管 git 認證,私有倉庫請自備 credential helper。
### 全域介面 ### 全域介面
@@ -172,6 +235,47 @@ PR 改帶 `author` 與 `reviewers` 欄位。`reason` 取值:
- issue:`no-assignee`、`assignee-idle`、`no-commenter`、`waiting-outside`、`parent-tracking` - issue:`no-assignee`、`assignee-idle`、`no-commenter`、`waiting-outside`、`parent-tracking`
- PR:`no-reviewer`、`author-idle`、`reviewer-idle`、`no-commenter` - PR:`no-reviewer`、`author-idle`、`reviewer-idle`、`no-commenter`
### `teai milestones` — 跨倉庫里程碑總覽
```sh
teai milestones # 各倉庫 open 里程碑概況(跨所屬組織;期限近者在前)
teai milestones --output table
```
管理者巡邏用(`gitea.py milestones` 對應,agents AGENTS.md 10.1)。帶 `--repo` 時
維持現行單倉庫 `list` 語義(`teai milestones --repo a/b` = `teai milestones list --repo a/b`)。
每筆欄位(鍵集鍵序與 `gitea.py` 全等,實測位元組一致):
```json
{
"repo": "alterminal/test",
"id": 6,
"title": "xcheck31-ms-overdue",
"url": "https://gitea.alterminal.com/alterminal/test/milestone/6",
"open_issues": 2,
"closed_issues": 0,
"due_on": "2026-09-08T08:00:00+08:00",
"due_hours": 61.3,
"overdue": true,
"unassigned": [
{
"type": "issue",
"number": 14,
"title": "…",
"url": "https://gitea.alterminal.com/alterminal/test/issues/14"
}
],
"updated_at": "2026-09-10T21:17:37+08:00"
}
```
- **排序**:`due_on` 近者在前;無期限者最後(`gitea.py` 的 `(due_on is None, due_on)` 鍵)。
- **`overdue`/`due_hours`**:期限已過為 `true`(`due_hours` 正數);無期限 → `null`。
- **`unassigned`**:該里程碑 open 條目(issue 與 PR)中無 assignee 者的摘要;PR 條目另帶 `author`。
- **`updated_at`**:里程碑本身與其 open 條目 `updated_at` 的最大值(判斷活躍度用)。
- 空輸出 → `[]`(`gitea.py` 無輸出;依 #26 慣例差異)。
### `teai members [--has-work]` ### `teai members [--has-work]`
```sh ```sh
@@ -221,7 +325,7 @@ teai whoami # 目前帳號(讀 tea 組態)
| 碼 | 意義 | | 碼 | 意義 |
| --- | --- | | --- | --- |
| 0 | 成功(含「沒有工作」→ 輸出 `null`/`[]`) | | 0 | 成功(含「沒有結果」→ 清單類命令輸出 `[]`、`next` 輸出 `null`;#37 判決) |
| 2 | 用法錯誤(未知命令/參數) | | 2 | 用法錯誤(未知命令/參數) |
| 3 | API 錯誤(連線失敗、401、403、5xx) | | 3 | API 錯誤(連線失敗、401、403、5xx) |
@@ -231,11 +335,31 @@ teai whoami # 目前帳號(讀 tea 組態)
| --- | --- | --- | | --- | --- | --- |
| `next` | `teai next` | 相同:author-PR → reviewer-PR → issue,最久未更新優先 | | `next` | `teai next` | 相同:author-PR → reviewer-PR → issue,最久未更新優先 |
| `stalled [--hours N]` | `teai stalled [--hours N]` | 相同,含 xref 父子追蹤與冷卻 | | `stalled [--hours N]` | `teai stalled [--hours N]` | 相同,含 xref 父子追蹤與冷卻 |
| `milestones` | `teai milestones` | 相同:跨倉庫 open 里程碑總覽,期限近者在前(#31) |
| `members [--has-work]` | `teai members [--has-work]` | 相同 | | `members [--has-work]` | `teai members [--has-work]` | 相同 |
| `pulls`/`pulls --mine`/`pulls --reviewer` | `teai pulls [--mine\|--reviewer]` | 相同 | | `pulls`/`pulls --mine`/`pulls --reviewer` | `teai pulls [--mine\|--reviewer]` | 相同 |
| `mine` | `teai mine` | 相同 | | `mine` | `teai mine` | 相同 |
| (底線函式) | `internal/` 套件 | 不設 CLI 命令;`xrefs` 為其邏輯的公開化 | | (底線函式) | `internal/` 套件 | 不設 CLI 命令;`xrefs` 為其邏輯的公開化 |
已知輸出差異(刻意保留,機器可讀優先):
- **空清單**:`gitea.py` 的 `_dump` 對空清單**不輸出任何內容**;teai 的清單類命令
(`mine`/`pulls`/`stalled`/`milestones` 總覽)空清單一律輸出 `[]`(exit 0)。對 JSON
消費者來說 `[]` 比「無輸出」更明確(可區分「沒有結果」與「查詢失敗無輸出」),交叉驗證時
以此差異為準。`next` 兩者語義相同:無工作時 teai 輸出 `null`(exit 0)、`gitea.py` 印
「沒有未完成的工作」。**判決 #37:維持 teai 現行 JSON 一致性(方向 2)**——消費端
(agents 倉庫巡邏提示與觸發腳本)應以「輸出 `[]`/`null` 且 exit 0」為「沒有」判據,
不得以「無輸出」判斷;`members [--has-work]` 維持逐行帳號、空時無輸出(兩者一致,不受影響)。
- **清單欄位集(`mine`/`pulls`)**:`gitea.py` 直接傾倒完整 Gitea API 物件
(`_dump` 的副作用,欄位集隨 Gitea 版本浮動);teai 輸出策展摘要欄位
(`mine`:repo/number/title/url;`pulls`:number/title/state/author/
head/base/updated_at…依命令定義)。交叉驗證比對**項目集合**(列出哪些
issue/PR)與判定語義,不逐欄位比對;`next`/`stalled`/`milestones` 總覽
兩者為策展欄位且鍵集鍵序全等,可逐欄位比對(#31 實測位元組一致)。判定 #26(維持摘要、文件化差異)。
- **全域選項位置**:teai 的全域選項(`--output` 等)可出現在命令之前或之後,
且可與命令旗標交錯(`teai members --has-work --output table`);
gitea.py 的旗標剖析較寬鬆,兩者命令列介面以此行為對齊。
遷移策略: 遷移策略:
1. 以 gitea.py 為行為基準:同帳號同時跑兩者,輸出應一致(交叉驗證)。 1. 以 gitea.py 為行為基準:同帳號同時跑兩者,輸出應一致(交叉驗證)。
+302
View File
@@ -0,0 +1,302 @@
// cmd/xcheck 是 #7 的交叉驗證工具(不屬於 teai 本體,PR 內附驗證說明)。
//
// 以真實 Gitea API 資料源實作 workflow.Source,跑 Go 版 ScanStalled,
// 再與 gitea.py stalled(行為基準)的 JSON 輸出逐欄位比對。
// 建立限制:與 teai 本體一致,僅標準庫。
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"gitea.alterminal.com/alterminal/teai/internal/workflow"
)
// apiSource 以 Gitea API 實作 workflow.Source。
type apiSource struct {
base string
token string
hc *http.Client
}
func (s *apiSource) get(path string, params map[string]string) ([]byte, int, error) {
u := s.base + path
if len(params) > 0 {
q := url.Values{}
for k, v := range params {
q.Set(k, v)
}
u += "?" + q.Encode()
}
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return nil, 0, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "token "+s.token)
resp, err := s.hc.Do(req)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
return body, resp.StatusCode, err
}
func (s *apiSource) getJSON(path string, params map[string]string, out any) error {
body, code, err := s.get(path, params)
if err != nil {
return err
}
if code != 200 {
return fmt.Errorf("GET %s: HTTP %d", path, code)
}
return json.Unmarshal(body, out)
}
// listAll 分頁拉取清單類 API(Gitea 上限 50/頁)。
func (s *apiSource) listAll(path string, params map[string]string, out any) error {
var items []json.RawMessage
page := 1
for {
q := map[string]string{"page": fmt.Sprint(page), "limit": "50"}
for k, v := range params {
q[k] = v
}
var chunk json.RawMessage
if err := s.getJSON(path, q, &chunk); err != nil {
return err
}
var arr []json.RawMessage
if err := json.Unmarshal(chunk, &arr); err != nil {
return fmt.Errorf("GET %s: 回傳非陣列", path)
}
items = append(items, arr...)
if len(arr) < 50 {
break
}
page++
}
var b strings.Builder
b.WriteByte('[')
for i, item := range items {
if i > 0 {
b.WriteByte(',')
}
b.Write(item)
}
b.WriteByte(']')
return json.Unmarshal([]byte(b.String()), out)
}
// CurrentUser 以 token 呼叫 /user 取實際帳號,與 gitea.py 的
// get_current_username() 同源(token 決定帳號,不接受環境變數覆寫,
// 失敗即報錯退出,不靜默退回預設值)。
func (s *apiSource) CurrentUser() (string, error) {
var user struct {
Username string `json:"username"`
Login string `json:"login"`
}
if err := s.getJSON("user", nil, &user); err != nil {
return "", err
}
if user.Username != "" {
return user.Username, nil
}
if user.Login != "" {
return user.Login, nil
}
return "", fmt.Errorf("無法從 Gitea API /user 取得目前帳號")
}
func (s *apiSource) MyOrganizations() ([]string, error) {
var orgs []struct {
Username string `json:"username"`
}
if err := s.listAll("user/orgs", nil, &orgs); err != nil {
return nil, err
}
names := make([]string, 0, len(orgs))
for _, o := range orgs {
if o.Username != "" {
names = append(names, o.Username)
}
}
return names, nil
}
func (s *apiSource) OrganizationRepositories(org string) ([]workflow.Repo, error) {
var repos []workflow.Repo
if err := s.listAll("orgs/"+org+"/repos", nil, &repos); err != nil {
return nil, err
}
return repos, nil
}
func (s *apiSource) OpenIssues(owner, repo string) ([]workflow.Issue, error) {
var issues []workflow.Issue
// 與 gitea.py 一致:type=issues 排除 PR;state=open。
if err := s.listAll(fmt.Sprintf("repos/%s/%s/issues", owner, repo), map[string]string{"type": "issues", "state": "open"}, &issues); err != nil {
return nil, err
}
return issues, nil
}
func (s *apiSource) OpenPulls(owner, repo string) ([]workflow.PullRequest, error) {
var pulls []workflow.PullRequest
if err := s.listAll(fmt.Sprintf("repos/%s/%s/pulls", owner, repo), map[string]string{"state": "open"}, &pulls); err != nil {
return nil, err
}
return pulls, nil
}
func (s *apiSource) IssueComments(owner, repo string, number int64) ([]workflow.Comment, error) {
var comments []workflow.Comment
if err := s.listAll(fmt.Sprintf("repos/%s/%s/issues/%d/comments", owner, repo, number), nil, &comments); err != nil {
return nil, err
}
return comments, nil
}
func (s *apiSource) IssueTimeline(owner, repo string, number int64) ([]workflow.TimelineEvent, error) {
var events []workflow.TimelineEvent
if err := s.listAll(fmt.Sprintf("repos/%s/%s/issues/%d/timeline", owner, repo, number), nil, &events); err != nil {
return nil, err
}
return events, nil
}
func (s *apiSource) TryGetIssue(owner, repo string, number int64) (workflow.Issue, bool, error) {
var issue workflow.Issue
body, code, err := s.get(fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, number), nil)
if err != nil {
return workflow.Issue{}, false, nil
}
if code != 200 {
return workflow.Issue{}, false, nil
}
if err := json.Unmarshal(body, &issue); err != nil {
return workflow.Issue{}, false, nil
}
return issue, true, nil
}
// loadEnv 讀 agents 倉庫的 .env(ACCESS_TOKEN、GITEA_API_DOMAIN)。
func loadEnv(path string) {
data, err := os.ReadFile(path)
if err != nil {
return
}
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
k, v, ok := strings.Cut(line, "=")
if !ok {
continue
}
k = strings.TrimSpace(k)
v = strings.Trim(strings.TrimSpace(v), "'\"")
if os.Getenv(k) == "" {
os.Setenv(k, v)
}
}
}
func main() {
// --xrefs 模式:從 stdin 讀文字,輸出解析後的引用目標(與 gitea.py
// _resolve_xref_targets 對照用)。組織與倉庫清單來自真實 API。
if len(os.Args) > 1 && os.Args[1] == "--xrefs" {
xrefsMain()
return
}
loadEnv(os.Getenv("HOME") + "/agents/.env")
domain := os.Getenv("GITEA_API_DOMAIN")
token := os.Getenv("ACCESS_TOKEN")
if domain == "" || token == "" {
fmt.Fprintln(os.Stderr, "缺少 GITEA_API_DOMAIN/ACCESS_TOKEN")
os.Exit(1)
}
src := &apiSource{
base: "https://" + domain + "/api/v1/",
token: token,
hc: &http.Client{Timeout: 30 * time.Second},
}
username, err := src.CurrentUser()
if err != nil {
fmt.Fprintln(os.Stderr, "CurrentUser:", err)
os.Exit(1)
}
hours := 4.0
items, scanErr := workflow.ScanStalled(src, username, hours, time.Now())
if scanErr != nil {
fmt.Fprintln(os.Stderr, "ScanStalled:", scanErr)
os.Exit(1)
}
// json.Marshal* 會把 <、>、& 轉義成 \u003c 等(含自訂 MarshalJSON 的輸出),
// 與 gitea.py(ensure_ascii=False)位元組不相容;必須停用 HTML 轉義。
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(items); err != nil {
fmt.Fprintln(os.Stderr, "Encode:", err)
os.Exit(1)
}
fmt.Print(buf.String())
}
// xrefsMain 對 stdin 的每行文字解析引用目標並輸出 JSON。
func xrefsMain() {
loadEnv(os.Getenv("HOME") + "/agents/.env")
domain := os.Getenv("GITEA_API_DOMAIN")
token := os.Getenv("ACCESS_TOKEN")
if domain == "" || token == "" {
fmt.Fprintln(os.Stderr, "缺少 GITEA_API_DOMAIN/ACCESS_TOKEN")
os.Exit(1)
}
src := &apiSource{
base: "https://" + domain + "/api/v1/",
token: token,
hc: &http.Client{Timeout: 30 * time.Second},
}
orgs, err := src.MyOrganizations()
if err != nil {
fmt.Fprintln(os.Stderr, "MyOrganizations:", err)
os.Exit(1)
}
myOrgs := map[string]bool{}
for _, o := range orgs {
myOrgs[o] = true
}
data, _ := io.ReadAll(os.Stdin)
repos, _ := src.OrganizationRepositories("alterminal")
names := make([]string, 0, len(repos))
for _, r := range repos {
names = append(names, r.Name)
}
targets, err := workflow.ResolveXrefTargets("alterminal", "agents", []string{string(data)}, myOrgs, func(string) ([]string, error) {
return names, nil
})
if err != nil {
fmt.Fprintln(os.Stderr, "ResolveXrefTargets:", err)
os.Exit(1)
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(targets); err != nil {
fmt.Fprintln(os.Stderr, "Encode:", err)
os.Exit(1)
}
fmt.Print(buf.String())
}
+81 -6
View File
@@ -15,6 +15,7 @@ import (
"flag" "flag"
"fmt" "fmt"
"io" "io"
"runtime/debug"
"sort" "sort"
"strings" "strings"
"time" "time"
@@ -23,8 +24,24 @@ import (
) )
// Version 是目前開發中的版本號。採用語意化版本;正式發佈前以 0 開頭。 // Version 是目前開發中的版本號。採用語意化版本;正式發佈前以 0 開頭。
// 僅作為 fallback:以 `go install module@version` 或納入其他 module 建置時,
// buildVersion 會改用 build info 內的 module 版本(見 runVersion)。
var Version = "0.1.0-dev" var Version = "0.1.0-dev"
// buildVersion 回傳應顯示的版本字串。go install pkg@tag 建置的二元檔
// 會在 Main.Version 帶入 tag(如 v0.1.0);clone 目錄內本機建置則帶
// pseudo-version(如 v0.1.1-0.<時間戳>-<commit>,工作樹有修改時再附加
// "+dirty"),同樣直接顯示。Main.Version 為 "(devel)" 或空(go test 環境、
// 無 VCS 資訊的 tarball 建置)時,才退回開發版本號 Version。
func buildVersion() string {
if info, ok := debug.ReadBuildInfo(); ok {
if v := info.Main.Version; v != "" && v != "(devel)" {
return v
}
}
return Version
}
// ExitCode 是 Run 回傳的行程結束碼。 // ExitCode 是 Run 回傳的行程結束碼。
type ExitCode int type ExitCode int
@@ -348,24 +365,79 @@ func dispatch(env *Env, name string, args []string) int {
// 用法,靜默成功結束即可。 // 用法,靜默成功結束即可。
var errHelp = errors.New("help requested") var errHelp = errors.New("help requested")
// parseFlags 剖析命令旗標:-h/--help 回 errHelp(由 exitCodeFor 視為成功), // parseFlags 剖析命令旗標,允許旗標與位置參數交錯(#25):Go 標準
// 其他剖析錯誤回 ErrUsage。 // flag 在遇到第一個非旗標參數後即停止剖析,其後的旗標會被當成位置
// 參數。做法:先掃描 args 把「旗標(含其值)」與「位置參數」分離成
// 兩串,再以旗標串呼叫 fs.Parse,最後以第二次 Parse 把位置參數設回
// fs.Args(Parse 遇到 "--" 即停止並收下其餘引數,第一次剖析已設好
// 的旗標值不受影響)。
// -h/--help 回 errHelp(由 exitCodeFor 視為成功),其他剖析錯誤回 ErrUsage。
func parseFlags(fs *flag.FlagSet, args []string) error { func parseFlags(fs *flag.FlagSet, args []string) error {
if err := fs.Parse(args); err != nil { var flags, positional []string
for i := 0; i < len(args); i++ {
arg := args[i]
if arg == "--" {
// "--" 之後全部是位置參數(不再剖析旗標;同標準 flag)。
positional = append(positional, args[i+1:]...)
break
}
if len(arg) < 2 || arg[0] != '-' {
positional = append(positional, arg)
continue
}
flags = append(flags, arg)
// 判斷旗標是否需要「下一個引數」當值(布林旗標與 inline
// 形式 --name=value 不需要)。未知或格式錯誤的旗標不消費
// 下一個引數,交給 fs.Parse 產生標準錯誤訊息。
numMinuses := 1
if arg[1] == '-' {
numMinuses = 2
}
name := arg[numMinuses:]
if name == "" || name[0] == '-' || name[0] == '=' {
continue // ---x/--=…:bad flag syntax,由 fs.Parse 報錯
}
flagName, _, hasInline := strings.Cut(name, "=")
if !hasInline {
if fl := fs.Lookup(flagName); fl != nil && !isBoolFlag(fl) && i+1 < len(args) {
i++
flags = append(flags, args[i])
}
}
}
if err := fs.Parse(flags); err != nil {
if errors.Is(err, flag.ErrHelp) { if errors.Is(err, flag.ErrHelp) {
return errHelp return errHelp
} }
return &ErrUsage{Msg: err.Error()} return &ErrUsage{Msg: err.Error()}
} }
if len(positional) > 0 {
if err := fs.Parse(append([]string{"--"}, positional...)); err != nil {
if errors.Is(err, flag.ErrHelp) {
return errHelp
}
return &ErrUsage{Msg: err.Error()}
}
}
return nil return nil
} }
// isBoolFlag 回傳旗標是否為布林型(不需要值;同 flag 包內部判斷)。
func isBoolFlag(fl *flag.Flag) bool {
bf, ok := fl.Value.(interface{ IsBoolFlag() bool })
return ok && bf.IsBoolFlag()
}
// exitCodeFor 把命令錯誤映射到結束碼:用法錯誤 → 2,API 錯誤 → 3, // exitCodeFor 把命令錯誤映射到結束碼:用法錯誤 → 2,API 錯誤 → 3,
// 其他(內部)→ 1。 // 其他(內部)→ 1。errHelp(命令的 -h/--help)視為成功(#25:
// 與 parseFlags 註解宣稱一致,FlagSet 已印出用法說明)。
func exitCodeFor(err error) ExitCode { func exitCodeFor(err error) ExitCode {
if err == nil { if err == nil {
return ExitOK return ExitOK
} }
if err == errHelp {
return ExitOK
}
var usage *ErrUsage var usage *ErrUsage
if errors.As(err, &usage) { if errors.As(err, &usage) {
return ExitUsage return ExitUsage
@@ -377,9 +449,12 @@ func exitCodeFor(err error) ExitCode {
return ExitInternal return ExitInternal
} }
// runVersion 輸出版本資訊。 // runVersion 輸出版本資訊;不接受任何參數。
func runVersion(env *Env, args []string) error { func runVersion(env *Env, args []string) error {
fmt.Fprintf(env.Out, "teai version %s\n", Version) if len(args) > 0 {
return &ErrUsage{Msg: "version 不接受參數"}
}
fmt.Fprintf(env.Out, "teai version %s\n", buildVersion())
return nil return nil
} }
+4 -2
View File
@@ -51,8 +51,10 @@ func TestRunVersion(t *testing.T) {
func TestRunUnknownCommand(t *testing.T) { func TestRunUnknownCommand(t *testing.T) {
_, stderr, code := run("no-such-command") _, stderr, code := run("no-such-command")
if code != int(ExitUsage) { // 直接對照 README「輸出與結束碼」的數值(用法錯誤=2),
t.Errorf("未知命令應回 ExitUsage(%d),得到 %d", int(ExitUsage), code) // 不以常數互比,避免常數與規格再次脫鉤(#10)。
if code != 2 {
t.Errorf("未知命令應回 2(README 用法錯誤),得到 %d", code)
} }
if !strings.Contains(stderr, "unknown command") { if !strings.Contains(stderr, "unknown command") {
t.Errorf("未知命令應在 stderr 說明,得到:%q", stderr) t.Errorf("未知命令應在 stderr 說明,得到:%q", stderr)
+249 -16
View File
@@ -14,6 +14,9 @@ import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"os"
"os/exec"
"path/filepath"
"strconv" "strconv"
"strings" "strings"
@@ -23,10 +26,11 @@ import (
func init() { func init() {
register := func(c *command) { commands[c.name] = c } register := func(c *command) { commands[c.name] = c }
register(&command{name: "issues", usage: "issues 管理(list/view/create/close/comment)", run: runIssues}) register(&command{name: "issues", usage: "issues 管理(list/view/create/close/comment;list 支援 --labels 過濾)", run: runIssues})
register(&command{name: "pulls", usage: "PR 管理(list/view/create/merge/comment;無子命令=工作流清單)", run: runPullsDaily}) register(&command{name: "pulls", usage: "PR 管理(list/view/create/merge/approve/close/checkout/comment;無子命令=工作流清單)", run: runPullsDaily})
register(&command{name: "comment", usage: "對 issue 或 PR 留言(--repo owner/repo <number> --body …)", run: runCommentDirect})
register(&command{name: "labels", usage: "標籤管理(list/create)", run: runLabels}) register(&command{name: "labels", usage: "標籤管理(list/create)", run: runLabels})
register(&command{name: "milestones", usage: "里程碑管理(list/create)", run: runMilestones}) register(&command{name: "milestones", usage: "里程碑(跨倉庫總覽;list/create 管理單倉庫)", run: runMilestones})
register(&command{name: "releases", usage: "發佈清單(list)", run: runReleases}) register(&command{name: "releases", usage: "發佈清單(list)", run: runReleases})
register(&command{name: "repos", usage: "倉庫查詢(list)", run: runRepos}) register(&command{name: "repos", usage: "倉庫查詢(list)", run: runRepos})
register(&command{name: "api", usage: "任意 API 呼叫(--method/--data;寫入動詞需 --yes)", run: runAPIDirect}) register(&command{name: "api", usage: "任意 API 呼叫(--method/--data;寫入動詞需 --yes)", run: runAPIDirect})
@@ -122,12 +126,13 @@ func runIssues(env *Env, args []string) error {
} }
} }
// runIssuesList:teai issues list --repo owner/repo [--state open|closed|all] // runIssuesList:teai issues list --repo owner/repo [--state open|closed|all] [--labels a,b]
func runIssuesList(env *Env, args []string) error { func runIssuesList(env *Env, args []string) error {
fs := flag.NewFlagSet("teai issues list", flag.ContinueOnError) fs := flag.NewFlagSet("teai issues list", flag.ContinueOnError)
fs.SetOutput(env.Err) fs.SetOutput(env.Err)
repo := fs.String("repo", "", "倉庫(owner/repo,必填)") repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
state := fs.String("state", "open", "狀態:open|closed|all") state := fs.String("state", "open", "狀態:open|closed|all")
labels := fs.String("labels", "", "標籤過濾(逗號分隔,可選;多標籤為 AND)")
if err := parseFlags(fs, args); err != nil { if err := parseFlags(fs, args); err != nil {
return err return err
} }
@@ -141,11 +146,19 @@ func runIssuesList(env *Env, args []string) error {
if owner == "" { if owner == "" {
return &ErrUsage{Msg: "issues list 需要 --repo owner/repo"} return &ErrUsage{Msg: "issues list 需要 --repo owner/repo"}
} }
var labelList []string
if strings.TrimSpace(*labels) != "" {
for _, l := range strings.Split(*labels, ",") {
if l = strings.TrimSpace(l); l != "" {
labelList = append(labelList, l)
}
}
}
ops, err := newOpsClient(env) ops, err := newOpsClient(env)
if err != nil { if err != nil {
return err return err
} }
issues, err := ops.ListIssues(context.Background(), owner, name, *state) issues, err := ops.ListIssues(context.Background(), owner, name, *state, labelList)
if err != nil { if err != nil {
return err return err
} }
@@ -316,6 +329,8 @@ func runIssuesClose(env *Env, args []string) error {
} }
// runComment:teai issues comment / teai pulls comment 共用。 // runComment:teai issues comment / teai pulls comment 共用。
// 相容 tea 用法:留言可作為位置參數(tea comment --repo a/b <index> "內容"),
// 亦可 teai 慣用的 --body;兩者同時給時位置參數優先(與 tea 行為一致)。
func runComment(env *Env, args []string, isPR bool) error { func runComment(env *Env, args []string, isPR bool) error {
name := "issues comment" name := "issues comment"
if isPR { if isPR {
@@ -324,7 +339,7 @@ func runComment(env *Env, args []string, isPR bool) error {
fs := flag.NewFlagSet("teai "+name, flag.ContinueOnError) fs := flag.NewFlagSet("teai "+name, flag.ContinueOnError)
fs.SetOutput(env.Err) fs.SetOutput(env.Err)
repo := fs.String("repo", "", "倉庫(owner/repo,必填)") repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
body := fs.String("body", "", "留言內容(必填)") body := fs.String("body", "", "留言內容(可改用位置參數)")
yes := fs.Bool("yes", false, "確認寫入") yes := fs.Bool("yes", false, "確認寫入")
if err := parseFlags(fs, args); err != nil { if err := parseFlags(fs, args); err != nil {
return err return err
@@ -336,16 +351,21 @@ func runComment(env *Env, args []string, isPR bool) error {
if owner == "" { if owner == "" {
return &ErrUsage{Msg: name + " 需要 --repo owner/repo"} return &ErrUsage{Msg: name + " 需要 --repo owner/repo"}
} }
if strings.TrimSpace(*body) == "" { // 位置參數:<number> [body…];尾端多餘引數以空格接成一則留言(tea 相容)。
return &ErrUsage{Msg: name + " 需要 --body"} if fs.NArg() < 1 {
} return &ErrUsage{Msg: name + " 需要恰好一個編號(可選加留言位置參數)"}
if fs.NArg() != 1 {
return &ErrUsage{Msg: name + " 需要恰好一個編號"}
} }
num, err := parseNumber(fs.Arg(0)) num, err := parseNumber(fs.Arg(0))
if err != nil { if err != nil {
return err return err
} }
text := strings.TrimSpace(*body)
if fs.NArg() > 1 {
text = strings.TrimSpace(strings.Join(fs.Args()[1:], " "))
}
if text == "" {
return &ErrUsage{Msg: name + " 需要留言內容(--body 或位置參數)"}
}
if err := requireYes(*yes, name); err != nil { if err := requireYes(*yes, name); err != nil {
return err return err
} }
@@ -353,7 +373,7 @@ func runComment(env *Env, args []string, isPR bool) error {
if err != nil { if err != nil {
return err return err
} }
comment, err := ops.AddComment(context.Background(), owner, rname, num, *body) comment, err := ops.AddComment(context.Background(), owner, rname, num, text)
if err != nil { if err != nil {
return err return err
} }
@@ -381,13 +401,26 @@ func runPullsDaily(env *Env, args []string) error {
return runPullsCreate(env, rest) return runPullsCreate(env, rest)
case "merge": case "merge":
return runPullsMerge(env, rest) return runPullsMerge(env, rest)
case "approve":
return runPullsApprove(env, rest)
case "close":
return runPullsClose(env, rest)
case "checkout":
return runPullsCheckout(env, rest)
case "comment": case "comment":
return runComment(env, rest, true) return runComment(env, rest, true)
default: default:
return &ErrUsage{Msg: fmt.Sprintf("pulls 未知子命令 %q(可用:list | view | create | merge | comment;或無子命令=工作流清單)", sub)} return &ErrUsage{Msg: fmt.Sprintf("pulls 未知子命令 %q(可用:list | view | create | merge | approve | close | checkout | comment;或無子命令=工作流清單)", sub)}
} }
} }
// runCommentDirect:teai comment --repo owner/repo <number> <body> [--yes]。
// tea 的通用留言指令:issue 與 PR 共用同一端點(Gitea 以 number 定位,
// issues/<n>/comments 對兩者皆有效),故不需 --type 旗標。
func runCommentDirect(env *Env, args []string) error {
return runComment(env, args, false)
}
// runPullsList:teai pulls list --repo owner/repo [--state open|closed|all] // runPullsList:teai pulls list --repo owner/repo [--state open|closed|all]
func runPullsList(env *Env, args []string) error { func runPullsList(env *Env, args []string) error {
fs := flag.NewFlagSet("teai pulls list", flag.ContinueOnError) fs := flag.NewFlagSet("teai pulls list", flag.ContinueOnError)
@@ -560,6 +593,179 @@ func runPullsMerge(env *Env, args []string) error {
}, gitea.Values{num, "merged"}) }, gitea.Values{num, "merged"})
} }
// runPullsApprove:teai pulls approve --repo owner/repo [--body …] --yes <number>。
// tea 相容:意見也可作為位置參數(teai pulls approve --repo a/b <n> "驗證通過。")。
func runPullsApprove(env *Env, args []string) error {
fs := flag.NewFlagSet("teai pulls approve", flag.ContinueOnError)
fs.SetOutput(env.Err)
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
body := fs.String("body", "", "審核意見(可改用位置參數)")
yes := fs.Bool("yes", false, "確認寫入")
if err := parseFlags(fs, args); err != nil {
return err
}
owner, name, err := splitRepoFlag(*repo)
if err != nil {
return err
}
if owner == "" {
return &ErrUsage{Msg: "pulls approve 需要 --repo owner/repo"}
}
if fs.NArg() < 1 {
return &ErrUsage{Msg: "pulls approve 需要恰好一個編號(可選加意見位置參數)"}
}
num, err := parseNumber(fs.Arg(0))
if err != nil {
return err
}
text := strings.TrimSpace(*body)
if fs.NArg() > 1 {
text = strings.TrimSpace(strings.Join(fs.Args()[1:], " "))
}
if err := requireYes(*yes, "pulls approve"); err != nil {
return err
}
ops, err := newOpsClient(env)
if err != nil {
return err
}
review, err := ops.ApprovePull(context.Background(), owner, name, num, text)
if err != nil {
return err
}
return printer(env).PrintOne([]gitea.Field{
{Name: "number"}, {Name: "state"}, {Name: "author"}, {Name: "body"},
}, gitea.Values{review.Number, review.State, review.Author(), review.Body})
}
// runPullsClose:teai pulls close --repo owner/repo --yes <number>。
// 關閉不合併;工作流約定 merge 才是正途(AGENTS.md 6.2),本指令提供語義對等。
func runPullsClose(env *Env, args []string) error {
fs := flag.NewFlagSet("teai pulls close", flag.ContinueOnError)
fs.SetOutput(env.Err)
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
yes := fs.Bool("yes", false, "確認寫入")
if err := parseFlags(fs, args); err != nil {
return err
}
owner, name, err := splitRepoFlag(*repo)
if err != nil {
return err
}
if owner == "" {
return &ErrUsage{Msg: "pulls close 需要 --repo owner/repo"}
}
if fs.NArg() != 1 {
return &ErrUsage{Msg: "pulls close 需要恰好一個編號"}
}
num, err := parseNumber(fs.Arg(0))
if err != nil {
return err
}
if err := requireYes(*yes, "pulls close"); err != nil {
return err
}
ops, err := newOpsClient(env)
if err != nil {
return err
}
pr, err := ops.ClosePull(context.Background(), owner, name, num)
if err != nil {
return err
}
return printer(env).PrintOne([]gitea.Field{
{Name: "number"}, {Name: "title"}, {Name: "state"}, {Name: "url"},
}, gitea.Values{pr.Number, pr.Title, pr.State, pr.HTMLURL})
}
// runPullsCheckout:teai pulls checkout --repo owner/repo <number> [--dir <path>]。
// 唯讀輔助指令:取得 PR head 資訊,在本機以 git 取得工作副本——
// 同倉庫分支 → git fetch --quiet origin <ref> && git checkout -B <ref> FETCH_HEAD
// (在 --dir 指定的既有 git 工作樹內執行;預設當前目錄);
// 跨倉庫 head → git clone --branch <ref> <clone_url> <dir>(--dir 必填,目錄不得已存在)。
// teai 不碰認證:clone 走 https 公開網址,私有倉庫時請自備 git 認證(credential helper)。
func runPullsCheckout(env *Env, args []string) error {
fs := flag.NewFlagSet("teai pulls checkout", flag.ContinueOnError)
fs.SetOutput(env.Err)
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
dir := fs.String("dir", "", "工作樹目錄(預設當前目錄;跨倉庫 head 時必填且不得已存在)")
if err := parseFlags(fs, args); err != nil {
return err
}
owner, name, err := splitRepoFlag(*repo)
if err != nil {
return err
}
if owner == "" {
return &ErrUsage{Msg: "pulls checkout 需要 --repo owner/repo"}
}
if fs.NArg() != 1 {
return &ErrUsage{Msg: "pulls checkout 需要恰好一個編號"}
}
num, err := parseNumber(fs.Arg(0))
if err != nil {
return err
}
ops, err := newOpsClient(env)
if err != nil {
return err
}
info, err := ops.PullHeadInfo(context.Background(), owner, name, num)
if err != nil {
return err
}
if info.Ref == "" {
return fmt.Errorf("PR #%d 缺少 head 分支資訊", num)
}
workDir := *dir
if workDir == "" {
workDir = "."
}
// git 指令一律固定參數(不經 shell、不插入使用者字串),分支名僅作為
// git 自身剖析的引數傳入;錯誤訊息往 env.Err,成功輸出到 env.Out。
// 注意:git clone 的目標目錄是位置參數,cmd.Dir 不可指向不存在目錄,
// 故 clone 一律在當前目錄執行(--dir 以絕對路徑傳入)。
runGit := func(dir string, args ...string) error {
cmd := exec.Command("git", args...)
cmd.Dir = dir
cmd.Stdout = env.Out
cmd.Stderr = env.Err
return cmd.Run()
}
if info.Repo == "" {
// 同倉庫:fetch 指定分支並建立/更新本地分支。
if err := runGit(workDir, "fetch", "--quiet", "origin", "--", info.Ref); err != nil {
return fmt.Errorf("git fetch origin %s 失敗(在 %s):%w", info.Ref, workDir, err)
}
if err := runGit(workDir, "checkout", "-q", "-B", info.Ref, "FETCH_HEAD"); err != nil {
return fmt.Errorf("git checkout -B %s 失敗:%w", info.Ref, err)
}
return printer(env).PrintOne([]gitea.Field{
{Name: "number"}, {Name: "branch"}, {Name: "workdir"},
}, gitea.Values{num, info.Ref, workDir})
}
// 跨倉庫 head:clone 到 --dir(不得已存在)。
if *dir == "" {
return &ErrUsage{Msg: "pulls checkout:跨倉庫 head(" + info.Repo + ")需要 --dir <目錄>"}
}
if st, err := os.Stat(*dir); err == nil && st.IsDir() {
return &ErrUsage{Msg: "pulls checkout:--dir 已存在(跨倉庫 head 需要新目錄):" + *dir}
}
if info.CloneURL == "" {
return fmt.Errorf("PR #%d 的 head 倉庫 %s 未提供 clone 網址", num, info.Repo)
}
abs, err := filepath.Abs(*dir)
if err != nil {
return &ErrUsage{Msg: "pulls checkout:無效的 --dir:" + err.Error()}
}
if err := runGit(".", "clone", "--quiet", "--branch", info.Ref, "--", info.CloneURL, abs); err != nil {
return fmt.Errorf("git clone %s 失敗:%w", info.CloneURL, err)
}
return printer(env).PrintOne([]gitea.Field{
{Name: "number"}, {Name: "branch"}, {Name: "repo"}, {Name: "workdir"},
}, gitea.Values{num, info.Ref, info.Repo, *dir})
}
// ---- labels ---- // ---- labels ----
// runLabels:teai labels list --repo owner/repo|teai labels create … --yes // runLabels:teai labels list --repo owner/repo|teai labels create … --yes
@@ -650,10 +856,12 @@ func runLabelsCreate(env *Env, args []string) error {
// ---- milestones ---- // ---- milestones ----
// runMilestones:teai milestones list|create … // runMilestones:teai milestones [list|create] …;不帶子命令時輸出
// 跨倉庫里程碑總覽(#31,對應 gitea.py milestones)。帶 --repo 直接
// 跟在 milestones 之後時維持現行單倉庫 list 語義。
func runMilestones(env *Env, args []string) error { func runMilestones(env *Env, args []string) error {
if len(args) == 0 { if len(args) == 0 {
return &ErrUsage{Msg: "milestones 需要子命令:list | create"} return runMilestonesOverview(env)
} }
sub, rest := args[0], args[1:] sub, rest := args[0], args[1:]
switch sub { switch sub {
@@ -662,7 +870,32 @@ func runMilestones(env *Env, args []string) error {
case "create": case "create":
return runMilestonesCreate(env, rest) return runMilestonesCreate(env, rest)
default: default:
return &ErrUsage{Msg: fmt.Sprintf("milestones 未知子命令 %q(可用:list | create)", sub)} if !strings.HasPrefix(sub, "-") {
return &ErrUsage{Msg: fmt.Sprintf("milestones 未知子命令 %q(可用:list | create;或不帶參數輸出跨倉庫總覽)", sub)}
}
// milestones 之後直接跟旗標(非子命令):帶 --repo → 整串轉發,
// 維持現行單倉庫 list 語義(--state 等旗標一併生效);否則為
// 跨倉庫總覽(總覽不接受任何命令旗標,空 FlagSet 讓未知旗標
// 報用法錯誤)。
hasRepo := false
for _, a := range args {
if a == "--repo" || strings.HasPrefix(a, "--repo=") {
hasRepo = true
break
}
}
if hasRepo {
return runMilestonesList(env, args)
}
fs := flag.NewFlagSet("teai milestones", flag.ContinueOnError)
fs.SetOutput(env.Err)
if err := parseFlags(fs, args); err != nil {
return err
}
if fs.NArg() != 0 {
return &ErrUsage{Msg: "milestones 不接受位置參數(子命令:list | create)"}
}
return runMilestonesOverview(env)
} }
} }
+54 -5
View File
@@ -53,8 +53,9 @@ func TestIssuesListRequiresRepo(t *testing.T) {
t.Errorf("不應發出任何請求") t.Errorf("不應發出任何請求")
}) })
_, stderr, code := run("issues", "list") _, stderr, code := run("issues", "list")
if code != int(ExitUsage) { // 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
t.Errorf("缺 --repo 應回 ExitUsage,得到 %d", code) if code != 2 {
t.Errorf("缺 --repo 應回 2(README 用法錯誤),得到 %d", code)
} }
if !strings.Contains(stderr, "--repo") { if !strings.Contains(stderr, "--repo") {
t.Errorf("錯誤訊息應提及 --repo,得到:%s", stderr) t.Errorf("錯誤訊息應提及 --repo,得到:%s", stderr)
@@ -110,8 +111,9 @@ func TestWriteCommandsRequireYes(t *testing.T) {
t.Errorf("%s:未帶 --yes 不得發出請求(%s %s)", tc.name, r.Method, r.URL.Path) t.Errorf("%s:未帶 --yes 不得發出請求(%s %s)", tc.name, r.Method, r.URL.Path)
}) })
_, stderr, code := run(tc.args...) _, stderr, code := run(tc.args...)
if code != int(ExitUsage) { // 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
t.Errorf("%s 未帶 --yes 應回 ExitUsage(2),得到 %d", tc.name, code) if code != 2 {
t.Errorf("%s 未帶 --yes 應回 2(README 用法錯誤),得到 %d", tc.name, code)
} }
if !strings.Contains(stderr, "--yes") { if !strings.Contains(stderr, "--yes") {
t.Errorf("%s 錯誤訊息應提及 --yes,得到:%s", tc.name, stderr) t.Errorf("%s 錯誤訊息應提及 --yes,得到:%s", tc.name, stderr)
@@ -218,6 +220,52 @@ func TestLabelsMilestonesReleasesList(t *testing.T) {
} }
} }
// TestStateAllSendsExplicitParam 是 #33 的回歸測試:issues/milestones
// 端點省略 state 時 API 預設 open,closed 項目會漏列,因此 --state all
// 必須明確帶 state=all;pulls 端點雖省略時也回全部,同樣明確帶上。
func TestStateAllSendsExplicitParam(t *testing.T) {
cases := []struct {
args []string
resp string
wantOut string
}{
{
args: []string{"issues", "list", "--repo", "a/b", "--state", "all"},
resp: `[{"number":30,"title":"open","state":"open","user":{"login":"ceo"},"updated_at":"t"},{"number":12,"title":"closed","state":"closed","user":{"login":"ceo"},"updated_at":"t"}]`,
wantOut: `"title":"closed"`,
},
{
args: []string{"pulls", "list", "--repo", "a/b", "--state", "all"},
resp: `[{"number":5,"title":"open PR","state":"open","user":{"login":"ceo"},"head":{"ref":"f"},"base":{"ref":"main"},"updated_at":"t"},{"number":2,"title":"closed PR","state":"closed","user":{"login":"ceo"},"head":{"ref":"f2"},"base":{"ref":"main"},"updated_at":"t"}]`,
wantOut: `"title":"closed PR"`,
},
{
args: []string{"milestones", "list", "--repo", "a/b", "--state", "all"},
resp: `[{"title":"v2","state":"open","description":"","due_on":""},{"title":"v1","state":"closed","description":"","due_on":""}]`,
wantOut: `"title":"v1"`,
},
}
for _, tc := range cases {
t.Run(strings.Join(tc.args, " "), func(t *testing.T) {
var gotQuery string
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
gotQuery = r.URL.RawQuery
fmt.Fprint(w, tc.resp)
})
stdout, _, code := run(tc.args...)
if code != 0 {
t.Fatalf("%v 應回 0,得到 %d", tc.args, code)
}
if !strings.Contains(gotQuery, "state=all") {
t.Errorf("%v 應明確帶 state=all(省略時 issues/milestones 端點預設 open),得到查詢 %q", tc.args, gotQuery)
}
if !strings.Contains(stdout, tc.wantOut) {
t.Errorf("%v 輸出應含 closed 項目 %s,得到:%s", tc.args, tc.wantOut, stdout)
}
})
}
}
// TestAPIDirectPassthrough 驗證 teai api 原樣輸出、GET 免 --yes、 // TestAPIDirectPassthrough 驗證 teai api 原樣輸出、GET 免 --yes、
// POST 未帶 --yes 被擋。 // POST 未帶 --yes 被擋。
func TestAPIDirectPassthrough(t *testing.T) { func TestAPIDirectPassthrough(t *testing.T) {
@@ -235,7 +283,8 @@ func TestAPIDirectPassthrough(t *testing.T) {
} }
_, stderr, code := run("api", "--method", "POST", "/version") _, stderr, code := run("api", "--method", "POST", "/version")
if code != int(ExitUsage) || !strings.Contains(stderr, "--yes") { // 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
if code != 2 || !strings.Contains(stderr, "--yes") {
t.Errorf("POST 未帶 --yes 應回 2 並提及 --yes,得到 %d:%s", code, stderr) t.Errorf("POST 未帶 --yes 應回 2 並提及 --yes,得到 %d:%s", code, stderr)
} }
} }
@@ -0,0 +1,289 @@
// dailyops_parity_commands_test.go — #40 的驗收測試:補齊 tea 對等指令
// pulls approve/close/checkout、通用 comment、issues list --labels 過濾。
// 寫入命令未帶 --yes 不得發出任何請求;帶 --yes 時打對端點與 payload。
package cli
import (
"fmt"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
// TestParityWriteCommandsRequireYes 驗證新增寫入命令未帶 --yes:
// 回 2 且不發請求(#40 驗收:寫入閘門慣例)。
func TestParityWriteCommandsRequireYes(t *testing.T) {
cases := []struct {
name string
args []string
}{
{"pulls approve", []string{"pulls", "approve", "--repo", "a/b", "1"}},
{"pulls close", []string{"pulls", "close", "--repo", "a/b", "1"}},
{"comment direct", []string{"comment", "--repo", "a/b", "1", "內容"}},
{"comment direct body flag", []string{"comment", "--repo", "a/b", "--body", "內容", "1"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
t.Errorf("%s:未帶 --yes 不得發出請求(%s %s)", tc.name, r.Method, r.URL.Path)
})
_, stderr, code := run(tc.args...)
if code != 2 {
t.Errorf("%s 未帶 --yes 應回 2,得到 %d", tc.name, code)
}
if !strings.Contains(stderr, "--yes") {
t.Errorf("%s 錯誤訊息應提及 --yes,得到:%s", tc.name, stderr)
}
})
}
}
// TestPullsApprovePostsReview 驗證 pulls approve --yes:
// POST /repos/{owner}/{repo}/pulls/{n}/reviews,payload 帶 event=APPROVED 與意見;
// 意見可用位置參數(tea 相容:teai pulls approve --repo a/b <n> "驗證通過。")。
func TestPullsApprovePostsReview(t *testing.T) {
var gotMethod, gotPath, gotBody string
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path
buf := make([]byte, 512)
n, _ := r.Body.Read(buf)
gotBody = string(buf[:n])
fmt.Fprint(w, `{"ID":42,"number":13,"state":"APPROVED","body":"驗證通過。","submitted_at":"t","user":{"login":"max"}}`)
})
stdout, _, code := run("pulls", "approve", "--repo", "alterminal/teai", "--yes", "13", "驗證通過。")
if code != 0 {
t.Fatalf("approve --yes 應回 0,得到 %d", code)
}
if gotMethod != "POST" || !strings.HasSuffix(gotPath, "/repos/alterminal/teai/pulls/13/reviews") {
t.Errorf("應 POST /repos/alterminal/teai/pulls/13/reviews,得到 %s %s", gotMethod, gotPath)
}
if !strings.Contains(gotBody, `"event":"APPROVED"`) || !strings.Contains(gotBody, "驗證通過。") {
t.Errorf("body 應含 event=APPROVED 與意見,得到:%s", gotBody)
}
if !strings.Contains(stdout, `"state":"APPROVED"`) {
t.Errorf("輸出應含 APPROVED,得到:%s", stdout)
}
}
// TestPullsClosePatchesState 驗證 pulls close --yes:
// PATCH /repos/{owner}/{repo}/pulls/{n},payload 帶 state=closed。
func TestPullsClosePatchesState(t *testing.T) {
var gotMethod, gotPath, gotBody string
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path
buf := make([]byte, 512)
n, _ := r.Body.Read(buf)
gotBody = string(buf[:n])
fmt.Fprint(w, `{"number":13,"title":"PR","state":"closed","html_url":"https://x/13"}`)
})
_, _, code := run("pulls", "close", "--repo", "alterminal/teai", "--yes", "13")
if code != 0 {
t.Fatalf("close --yes 應回 0,得到 %d", code)
}
if gotMethod != "PATCH" || !strings.HasSuffix(gotPath, "/repos/alterminal/teai/pulls/13") {
t.Errorf("應 PATCH /repos/alterminal/teai/pulls/13,得到 %s %s", gotMethod, gotPath)
}
if !strings.Contains(gotBody, `"state":"closed"`) {
t.Errorf("body 應含 state=closed,得到:%s", gotBody)
}
}
// TestCommentDirectPostsComment 驗證通用 comment(tea 相容形式):
// --repo a/b <number> <body> --yes → POST issues/<n>/comments,
// issue 與 PR 共用(不需要 type 旗標)。
func TestCommentDirectPostsComment(t *testing.T) {
var gotMethod, gotPath, gotBody string
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
gotMethod, gotPath = r.Method, r.URL.Path
buf := make([]byte, 512)
n, _ := r.Body.Read(buf)
gotBody = string(buf[:n])
fmt.Fprint(w, `{"body":"已依評論更新:commit abc1234。","created_at":"t","user":{"login":"max"}}`)
})
stdout, _, code := run("comment", "--repo", "alterminal/teai", "--yes", "13", "已依評論更新:commit abc1234。")
if code != 0 {
t.Fatalf("comment --yes 應回 0,得到 %d", code)
}
if gotMethod != "POST" || !strings.HasSuffix(gotPath, "/repos/alterminal/teai/issues/13/comments") {
t.Errorf("應 POST /repos/alterminal/teai/issues/13/comments,得到 %s %s", gotMethod, gotPath)
}
if !strings.Contains(gotBody, "已依評論更新:commit abc1234。") {
t.Errorf("body 應含留言內容,得到:%s", gotBody)
}
if !strings.Contains(stdout, "已依評論更新") {
t.Errorf("輽出應含留言,得到:%s", stdout)
}
}
// TestCommentDirectBodyFlag 驗證 comment 也接受 --body(teai 慣用),
// 且位置參數與 --body 同時存在時位置參數優先。
func TestCommentDirectBodyFlag(t *testing.T) {
var gotBody string
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
buf := make([]byte, 512)
n, _ := r.Body.Read(buf)
gotBody = string(buf[:n])
fmt.Fprint(w, `{"body":"x","created_at":"t","user":{"login":"max"}}`)
})
if _, _, code := run("comment", "--repo", "a/b", "--body", "旗標版", "--yes", "5"); code != 0 {
t.Fatalf("--body 版應回 0,得到 %d", code)
}
if !strings.Contains(gotBody, "旗標版") {
t.Errorf("body 應為 --body 值,得到:%s", gotBody)
}
if _, _, code := run("comment", "--repo", "a/b", "--body", "旗標版", "--yes", "5", "位置版"); code != 0 {
t.Fatalf("位置參數版應回 0,得到 %d", code)
}
if !strings.Contains(gotBody, "位置版") || strings.Contains(gotBody, "旗標版") {
t.Errorf("位置參數應優先於 --body,得到:%s", gotBody)
}
}
// TestIssuesListLabelsFilter 驗證 issues list --labels:
// 查詢參數帶 labels=a,b(多標籤 AND 語義),輸出仍為 JSON 陣列。
func TestIssuesListLabelsFilter(t *testing.T) {
var gotQuery string
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
gotQuery = r.URL.RawQuery
fmt.Fprint(w, `[{"number":9,"title":"标签過濾","state":"open","user":{"login":"ceo"},"updated_at":"t"}]`)
})
stdout, _, code := run("issues", "list", "--repo", "alterminal/teai", "--labels", "bug, help wanted")
if code != 0 {
t.Fatalf("--labels 應回 0,得到 %d", code)
}
if !strings.Contains(gotQuery, "labels=bug%2Chelp+wanted") && !strings.Contains(gotQuery, "labels=bug%2C+help+wanted") {
t.Errorf("查詢應帶 labels=bug,help+wanted(URL 編碼後),得到 %q", gotQuery)
}
if !strings.Contains(stdout, `"number":9`) {
t.Errorf("輽出應含過濾後的 issue,得到:%s", stdout)
}
}
// TestPullsCheckoutSameRepo 驗證 checkout 同倉庫分支:
// 在 --dir 的 git 工作樹 fetch origin <ref> 並 checkout -B <ref>。
func TestPullsCheckoutSameRepo(t *testing.T) {
// 建立裸「origin」倉庫與分支 feat/x。
origin := t.TempDir()
gitRun := func(args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = origin
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v 失敗:%v\n%s", args, err, out)
}
}
gitRun("init", "-q", "-b", "main", ".")
gitRun("config", "user.email", "t@t")
gitRun("config", "user.name", "t")
gitRun("commit", "--allow-empty", "-m", "init")
gitRun("checkout", "-q", "-b", "feat/x")
gitRun("commit", "--allow-empty", "-m", "x1")
gitRun("checkout", "-q", "main")
// 工作樹 clone 自 origin(file:// 協定讓 fetch 生效)。
work := t.TempDir()
if out, err := exec.Command("git", "clone", "-q", "file://"+origin, work).CombinedOutput(); err != nil {
t.Fatalf("clone 失敗:%v\n%s", err, out)
}
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"number":7,"title":"PR","state":"open","head":{"ref":"feat/x","repo":{"full_name":"alterminal/teai","clone_url":"https://gitea.alterminal.com/alterminal/teai.git"}},"base":{"ref":"main"}}`)
})
stdout, _, code := run("pulls", "checkout", "--repo", "alterminal/teai", "--dir", work, "7")
if code != 0 {
t.Fatalf("checkout 應回 0,得到 %d", code)
}
brOut, err := exec.Command("git", "-C", work, "branch", "--show-current").Output()
if err != nil || strings.TrimSpace(string(brOut)) != "feat/x" {
t.Errorf("工作樹應在 feat/x,得到 %q(err=%v)", string(brOut), err)
}
if !strings.Contains(stdout, `"branch":"feat/x"`) {
t.Errorf("輽出應含 branch 欄位,得到:%s", stdout)
}
}
// TestPullsCheckoutCrossRepo 驗證 checkout 跨倉庫 head:
// 需 --dir(新目錄),git clone --branch <ref> <clone_url> <dir>。
func TestPullsCheckoutCrossRepo(t *testing.T) {
// 假伺服器同時當 git remote:把 PR head 指向本地裸倉庫。
origin := t.TempDir()
gitRun := func(args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = origin
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v 失敗:%v\n%s", args, err, out)
}
}
gitRun("init", "-q", "-b", "main", "--bare", ".")
seed := t.TempDir()
cmd := exec.Command("git", "clone", "-q", "file://"+origin, seed)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("clone seed 失敗:%v\n%s", err, out)
}
for _, args := range [][]string{
{"config", "user.email", "t@t"},
{"config", "user.name", "t"},
{"commit", "--allow-empty", "-m", "init"},
{"checkout", "-q", "-b", "feat/y"},
{"commit", "--allow-empty", "-m", "y1"},
{"push", "-q", "origin", "feat/y"},
} {
c := exec.Command("git", args...)
c.Dir = seed
if out, err := c.CombinedOutput(); err != nil {
t.Fatalf("git %v 失敗:%v\n%s", args, err, out)
}
}
target := filepath.Join(t.TempDir(), "wk")
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, `{"number":8,"title":"PR","state":"open","head":{"ref":"feat/y","repo":{"full_name":"other/fork","clone_url":"file://%s"}},"base":{"ref":"main"}}`, origin)
})
stdout, _, code := run("pulls", "checkout", "--repo", "alterminal/teai", "--dir", target, "8")
if code != 0 {
t.Fatalf("checkout 跨倉庫應回 0,得到 %d", code)
}
brOut, err := exec.Command("git", "-C", target, "branch", "--show-current").Output()
if err != nil || strings.TrimSpace(string(brOut)) != "feat/y" {
t.Errorf("工作樹應在 feat/y,得到 %q(err=%v)", string(brOut), err)
}
if !strings.Contains(stdout, `"repo":"other/fork"`) {
t.Errorf("輽出應含 head 倉庫,得到:%s", stdout)
}
}
// TestPullsCheckoutCrossRepoRequiresDir 驗證跨倉庫 head 未帶 --dir:
// 用法錯誤(exit 2)。
func TestPullsCheckoutCrossRepoRequiresDir(t *testing.T) {
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"number":8,"title":"PR","state":"open","head":{"ref":"feat/y","repo":{"full_name":"other/fork","clone_url":"https://x/y.git"}},"base":{"ref":"main"}}`)
})
_, stderr, code := run("pulls", "checkout", "--repo", "alterminal/teai", "8")
if code != 2 {
t.Errorf("跨倉庫 head 未帶 --dir 應回 2,得到 %d", code)
}
if !strings.Contains(stderr, "--dir") {
t.Errorf("錯誤訊息應提及 --dir,得到:%s", stderr)
}
}
// TestIssuesCommentPositionalBody 驗證 issues comment 也吃位置參數留言
// (tea comment 相容语法在子命令下的行為)。
func TestIssuesCommentPositionalBody(t *testing.T) {
var gotBody string
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
buf := make([]byte, 512)
n, _ := r.Body.Read(buf)
gotBody = string(buf[:n])
fmt.Fprint(w, `{"body":"x","created_at":"t","user":{"login":"max"}}`)
})
if _, _, code := run("issues", "comment", "--repo", "a/b", "--yes", "3", "多餘", "引數", "串留言"); code != 0 {
t.Fatalf("issues comment 位置參數應回 0,得到 %d", code)
}
if !strings.Contains(gotBody, "多餘 引數 串留言") {
t.Errorf("尾端引數應串成留言,得到:%s", gotBody)
}
}
var _ = os.Getenv // 保持 import 一致(checkout 測試用 exec,此檔亦引用 os 於需要時)
+66 -15
View File
@@ -10,20 +10,22 @@ import (
) )
func TestExitCodeMapping(t *testing.T) { func TestExitCodeMapping(t *testing.T) {
// want 直接寫 README「輸出與結束碼」的數值(0/2/3;內部錯誤 1),
// 不以常數互比,避免常數與規格再次脫鉤(#10)。
cases := []struct { cases := []struct {
name string name string
err error err error
want ExitCode want int
}{ }{
{"usage error", &ErrUsage{Msg: "bad flag"}, ExitUsage}, {"usage error", &ErrUsage{Msg: "bad flag"}, 2},
{"api error 401", &gitea.ErrAPI{StatusCode: 401, Op: "GET /api/v1/user"}, ExitAPI}, {"api error 401", &gitea.ErrAPI{StatusCode: 401, Op: "GET /api/v1/user"}, 3},
{"api error transport", &gitea.ErrAPI{Op: "GET /api/v1/user", Err: errString("dial tcp")}, ExitAPI}, {"api error transport", &gitea.ErrAPI{Op: "GET /api/v1/user", Err: errString("dial tcp")}, 3},
{"wrapped api error", wrapped(&gitea.ErrAPI{StatusCode: 500}), ExitAPI}, {"wrapped api error", wrapped(&gitea.ErrAPI{StatusCode: 500}), 3},
{"other error", errString("boom"), ExitInternal}, {"other error", errString("boom"), 1},
{"nil maps to OK", nil, ExitOK}, {"nil maps to OK", nil, 0},
} }
for _, tc := range cases { for _, tc := range cases {
if got := exitCodeFor(tc.err); got != tc.want { if got := int(exitCodeFor(tc.err)); got != tc.want {
t.Errorf("%s: exitCodeFor = %d, want %d", tc.name, got, tc.want) t.Errorf("%s: exitCodeFor = %d, want %d", tc.name, got, tc.want)
} }
} }
@@ -68,16 +70,16 @@ func TestRunExitCodes(t *testing.T) {
}) })
} }
func TestParseGlobals(t *testing.T) { func TestExtractGlobals(t *testing.T) {
g := defaultGlobals() g := defaultGlobals()
rest, err := parseGlobals(&g, []string{ rest, err := extractGlobals(&g, []string{
"--url", "https://example.com", "--url", "https://example.com",
"--token=tok", "--token=tok",
"--config", "/tmp/c.yml", "--config", "/tmp/c.yml",
"--output", "table", "--output", "table",
"--timeout", "45s", "--timeout", "45s",
"next", "next",
}) }, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -95,16 +97,65 @@ func TestParseGlobals(t *testing.T) {
} }
} }
func TestParseGlobalsStopsAtCommand(t *testing.T) { func TestExtractGlobalsAfterCommand(t *testing.T) {
// 全域選項出現在命令之後也應抽出(README:teai next --output table)。
g := defaultGlobals() g := defaultGlobals()
rest, err := parseGlobals(&g, []string{"version", "--output", "table"}) rest, err := extractGlobals(&g, []string{"version", "--output", "table"}, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
// 命令之後的選項屬於命令,不屬於全域。 if len(rest) != 1 || rest[0] != "version" {
if len(rest) != 3 || rest[0] != "version" { t.Fatalf("rest = %v, want [version]", rest)
}
if g.Output != gitea.FormatTable {
t.Fatalf("output = %v, want table", g.Output)
}
}
func TestExtractGlobalsKeepsCommandFlags(t *testing.T) {
// 非全域選項屬於子命令:原樣依序交回,不能攔成 ErrUsage。
cases := [][]string{
{"members", "--has-work"},
{"pulls", "--mine"},
{"pulls", "--reviewer"},
{"pulls", "--repo", "alterminal/teai"},
{"members", "--has-work", "--output", "table"},
{"pulls", "--mine", "--repo", "alterminal/teai", "--output", "table"},
}
for _, args := range cases {
g := defaultGlobals()
rest, err := extractGlobals(&g, args, nil)
if err != nil {
t.Fatalf("extractGlobals(%v) 不應報錯:%v", args, err)
}
want := args
if strings.HasSuffix(strings.Join(args, " "), "--output table") {
want = args[:len(args)-2]
}
if len(rest) != len(want) {
t.Fatalf("extractGlobals(%v) rest = %v, want %v", args, rest, want)
}
for i := range want {
if rest[i] != want[i] {
t.Fatalf("extractGlobals(%v) rest = %v, want %v", args, rest, want)
}
}
}
}
func TestExtractGlobalsDoubleDashStops(t *testing.T) {
g := defaultGlobals()
rest, err := extractGlobals(&g, []string{"--output", "table", "--", "--url", "x"}, nil)
if err != nil {
t.Fatal(err)
}
// -- 之後全部交回,--url 不再視為全域選項。
if len(rest) != 2 || rest[0] != "--url" || rest[1] != "x" {
t.Fatalf("rest = %v", rest) t.Fatalf("rest = %v", rest)
} }
if g.Output != gitea.FormatTable {
t.Fatalf("output = %v, want table", g.Output)
}
} }
// TestExtractGlobalsReservedFlags 驗證 #18:與全域同名的命令旗標 // TestExtractGlobalsReservedFlags 驗證 #18:與全域同名的命令旗標
+160
View File
@@ -0,0 +1,160 @@
// interleaved_flags_test.go — #25 的回歸測試:命令旗標放在位置參數
// (path/編號/名稱)之後也必須被剖析,不得被當成位置參數。
// 涵蓋 parseFlags 走的命令(issues/pulls view、api、stalled)與
// 原本直接 fs.Parse 的命令(login default/remove、members)。
package cli
import (
"fmt"
"net/http"
"os"
"strings"
"testing"
)
// TestAPIFlagsAfterPath 驗證 #25 重現步驟一:teai api <path> --method POST
// --data '{}' --yes 的旗標在 path 之後仍被剖析(POST 送達伺服器而非 exit 2)。
func TestAPIFlagsAfterPath(t *testing.T) {
var gotMethod string
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
gotMethod = r.Method
fmt.Fprint(w, `{}`)
})
_, _, code := run("api", "/version", "--method", "POST", "--data", `{}`, "--yes")
if code != 0 {
t.Fatalf("api 旗標在 path 之後應回 0(#25),得到 %d", code)
}
if gotMethod != "POST" {
t.Fatalf("應送出 POST,得到 %s", gotMethod)
}
}
// TestIssuesViewCommentsFlagAfterNumber 驗證 #25 重現步驟二:
// teai issues view --repo owner/repo <編號> --comments 的 --comments
// 在編號之後仍生效(有打 /comments 端點)。
func TestIssuesViewCommentsFlagAfterNumber(t *testing.T) {
var commentsHit bool
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/comments"):
commentsHit = true
fmt.Fprint(w, `[]`)
case strings.HasSuffix(r.URL.Path, "/issues/8"):
fmt.Fprint(w, `{"number":8,"title":"t","state":"open","user":{"login":"ceo"},"body":"","html_url":"u","labels":[],"updated_at":"t"}`)
default:
fmt.Fprint(w, `[]`)
}
})
stdout, _, code := run("issues", "view", "--repo", "alterminal/teai", "8", "--comments")
if code != 0 {
t.Fatalf("issues view 編號在前旗標在後應回 0(#25),得到 %d", code)
}
if !commentsHit {
t.Fatalf("--comments 在編號之後應觸發 /comments 請求;輸出:%s", stdout)
}
}
// TestPullsViewCommentsFlagAfterNumber 同上,驗證 pulls view。
func TestPullsViewCommentsFlagAfterNumber(t *testing.T) {
var commentsHit bool
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/comments"):
commentsHit = true
fmt.Fprint(w, `[]`)
case strings.HasSuffix(r.URL.Path, "/pulls/13"):
fmt.Fprint(w, `{"number":13,"title":"t","state":"open","user":{"login":"ceo"},"body":"","html_url":"u","labels":[],"updated_at":"t"}`)
default:
fmt.Fprint(w, `[]`)
}
})
_, _, code := run("pulls", "view", "--repo", "alterminal/teai", "13", "--comments")
if code != 0 {
t.Fatalf("pulls view 編號在前旗標在後應回 0(#25),得到 %d", code)
}
if !commentsHit {
t.Fatal("--comments 在編號之後應觸發 /comments 請求")
}
}
// TestStalledHoursFlagAfterPositional 驗證 stalled 即使混入位置參數
// 也不誤剖析:--hours 在位置參數後仍被剖析,而 stalled 本身不接受
// 位置參數 → 應回 2(用法錯誤)而非誤把 --hours 當位置參數。
func TestStalledHoursFlagAfterPositional(t *testing.T) {
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `[]`)
})
_, stderr, code := run("stalled", "9", "--hours", "3")
if code != 2 {
t.Fatalf("stalled 帶位置參數應回 2,得到 %d", code)
}
if !strings.Contains(stderr, "位置參數") {
t.Fatalf("錯誤訊息應提及位置參數,得到:%s", stderr)
}
// 對照組:--hours 值非法(剖析層錯誤)應回 2,而非把旗標當位置參數。
_, stderr, code = run("stalled", "--hours", "abc")
if code != 2 || !strings.Contains(stderr, "invalid value") {
t.Fatalf("stalled --hours abc 應回 2 且提及 invalid value,得到 %d:%s", code, stderr)
}
// 交錯但無多餘位置參數:--hours 值不會被誤收。
_, stderr, code = run("stalled", "--hours")
if code != 2 || !strings.Contains(stderr, "flag needs an argument") {
t.Fatalf("stalled --hours 缺值應回 2 且提及 flag needs an argument,得到 %d:%s", code, stderr)
}
}
// TestLoginDefaultNameOnly 驗證 login default <名稱>:位置參數在旗標
// 之後(--config 在前)仍正確收取一個名稱。
func TestLoginDefaultNameOnly(t *testing.T) {
cfg := `logins:
- name: a
url: https://a.example.com
token: ta
default: true
- name: b
url: https://b.example.com
token: tb
default: false
`
prefix, _ := loginTestEnv(t, cfg)
stdout, _, code := run(append(prefix, "login", "default", "b")...)
if code != 0 || !strings.Contains(stdout, `"name":"b"`) {
t.Fatalf("login default b 應回 0 並輸出 b:code=%d out=%s", code, stdout)
}
// 多給一個位置參數仍應報用法錯誤(不受交錯支援影響)。
_, stderr, code := run(append(prefix, "login", "default", "b", "c")...)
if code != 2 || !strings.Contains(stderr, "exactly one") {
t.Fatalf("兩個名稱應回 2,得到 %d:%s", code, stderr)
}
}
// TestMemberHelpExitZero 驗證命令的 -h 結束碼為 0(#25 順帶修正:
// errHelp 視為成功)。
func TestMemberHelpExitZero(t *testing.T) {
_, _, code := run("members", "-h")
if code != 0 {
t.Fatalf("members -h 應回 0,得到 %d", code)
}
}
// TestLoginRemoveFlagInterleaved 驗證 login remove <名稱> --yes:
// --yes 在名稱之後仍視為旗標(未帶時走確認流程會讀 stdin)。
func TestLoginRemoveFlagInterleaved(t *testing.T) {
prefix, configPath := loginTestEnv(t, `logins:
- name: a
url: https://a.example.com
token: ta
default: true
`)
old := loginStdin
loginStdin = strings.NewReader("y\n") // 若 --yes 失效會讀到這行
defer func() { loginStdin = old }()
_, _, code := run(append(prefix, "login", "remove", "a", "--yes")...)
if code != 0 {
t.Fatalf("login remove a --yes 應回 0,得到 %d", code)
}
data, _ := os.ReadFile(configPath)
if strings.Contains(string(data), "token: ta") {
t.Fatalf("--yes 在名稱之後應生效(直接刪除):\n%s", data)
}
}
+8 -8
View File
@@ -93,8 +93,8 @@ func printLoginList(env *Env, logins []gitea.LoginEntry) error {
func runLoginList(env *Env, args []string) error { func runLoginList(env *Env, args []string) error {
fs := flag.NewFlagSet("teai login list", flag.ContinueOnError) fs := flag.NewFlagSet("teai login list", flag.ContinueOnError)
fs.SetOutput(env.Err) fs.SetOutput(env.Err)
if err := fs.Parse(args); err != nil { if err := parseFlags(fs, args); err != nil {
return &ErrUsage{Msg: err.Error()} return err
} }
if fs.NArg() > 0 { if fs.NArg() > 0 {
return &ErrUsage{Msg: fmt.Sprintf("unexpected argument %q", fs.Arg(0))} return &ErrUsage{Msg: fmt.Sprintf("unexpected argument %q", fs.Arg(0))}
@@ -121,8 +121,8 @@ func runLoginAdd(env *Env, args []string) error {
nameFlag := fs.String("name", "", "登入名稱(省略時取 URL 主機)") nameFlag := fs.String("name", "", "登入名稱(省略時取 URL 主機)")
tokenFlag := fs.String("token", "", "API token(省略時自 stdin 讀一行)") tokenFlag := fs.String("token", "", "API token(省略時自 stdin 讀一行)")
defaultFlag := fs.Bool("default", true, "設為預設登入") defaultFlag := fs.Bool("default", true, "設為預設登入")
if err := fs.Parse(args); err != nil { if err := parseFlags(fs, args); err != nil {
return &ErrUsage{Msg: err.Error()} return err
} }
if fs.NArg() > 0 { if fs.NArg() > 0 {
return &ErrUsage{Msg: fmt.Sprintf("unexpected argument %q", fs.Arg(0))} return &ErrUsage{Msg: fmt.Sprintf("unexpected argument %q", fs.Arg(0))}
@@ -224,8 +224,8 @@ func verifyToken(env *Env, siteURL, token string) (string, error) {
func runLoginDefault(env *Env, args []string) error { func runLoginDefault(env *Env, args []string) error {
fs := flag.NewFlagSet("teai login default", flag.ContinueOnError) fs := flag.NewFlagSet("teai login default", flag.ContinueOnError)
fs.SetOutput(env.Err) fs.SetOutput(env.Err)
if err := fs.Parse(args); err != nil { if err := parseFlags(fs, args); err != nil {
return &ErrUsage{Msg: err.Error()} return err
} }
if fs.NArg() != 1 { if fs.NArg() != 1 {
return &ErrUsage{Msg: "login default requires exactly one login name"} return &ErrUsage{Msg: "login default requires exactly one login name"}
@@ -255,8 +255,8 @@ func runLoginRemove(env *Env, args []string) error {
fs := flag.NewFlagSet("teai login remove", flag.ContinueOnError) fs := flag.NewFlagSet("teai login remove", flag.ContinueOnError)
fs.SetOutput(env.Err) fs.SetOutput(env.Err)
yesFlag := fs.Bool("yes", false, "跳過確認") yesFlag := fs.Bool("yes", false, "跳過確認")
if err := fs.Parse(args); err != nil { if err := parseFlags(fs, args); err != nil {
return &ErrUsage{Msg: err.Error()} return err
} }
if fs.NArg() != 1 { if fs.NArg() != 1 {
return &ErrUsage{Msg: "login remove requires exactly one login name"} return &ErrUsage{Msg: "login remove requires exactly one login name"}
+12 -8
View File
@@ -145,8 +145,9 @@ func TestLoginAddRejected401NoWrite(t *testing.T) {
`) `)
_, stderr, code := run(append(prefix, _, stderr, code := run(append(prefix,
"--url", srv.URL, "login", "add", "--token", "bad-tok")...) "--url", srv.URL, "login", "add", "--token", "bad-tok")...)
if code != int(ExitAPI) { // 401 是 API 錯誤;對照 README「輸出與結束碼」=3(#10)。
t.Fatalf("401 should exit 3, got %d (stderr %s)", code, stderr) if code != 3 {
t.Fatalf("401 should exit 3 (README api error), got %d (stderr %s)", code, stderr)
} }
if !strings.Contains(stderr, "401") { if !strings.Contains(stderr, "401") {
t.Fatalf("stderr should mention 401: %s", stderr) t.Fatalf("stderr should mention 401: %s", stderr)
@@ -250,8 +251,9 @@ func TestLoginRemoveAsksConfirmation(t *testing.T) {
func TestLoginUnknownSubcommandUsage(t *testing.T) { func TestLoginUnknownSubcommandUsage(t *testing.T) {
prefix, _ := loginTestEnv(t, "") prefix, _ := loginTestEnv(t, "")
_, stderr, code := run(append(prefix, "login", "bogus")...) _, stderr, code := run(append(prefix, "login", "bogus")...)
if code != int(ExitUsage) { // 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
t.Fatalf("want exit 2, got %d", code) if code != 2 {
t.Fatalf("want exit 2 (README usage), got %d", code)
} }
if !strings.Contains(stderr, "unknown login subcommand") { if !strings.Contains(stderr, "unknown login subcommand") {
t.Fatalf("stderr: %s", stderr) t.Fatalf("stderr: %s", stderr)
@@ -261,8 +263,9 @@ func TestLoginUnknownSubcommandUsage(t *testing.T) {
func TestLoginNoSubcommandUsage(t *testing.T) { func TestLoginNoSubcommandUsage(t *testing.T) {
prefix, _ := loginTestEnv(t, "") prefix, _ := loginTestEnv(t, "")
_, stderr, code := run(append(prefix, "login")...) _, stderr, code := run(append(prefix, "login")...)
if code != int(ExitUsage) { // 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
t.Fatalf("want exit 2, got %d", code) if code != 2 {
t.Fatalf("want exit 2 (README usage), got %d", code)
} }
if !strings.Contains(stderr, "subcommand") { if !strings.Contains(stderr, "subcommand") {
t.Fatalf("stderr: %s", stderr) t.Fatalf("stderr: %s", stderr)
@@ -272,8 +275,9 @@ func TestLoginNoSubcommandUsage(t *testing.T) {
func TestLoginRemoveNotFound(t *testing.T) { func TestLoginRemoveNotFound(t *testing.T) {
prefix, _ := loginTestEnv(t, "logins: []\n") prefix, _ := loginTestEnv(t, "logins: []\n")
_, stderr, code := run(append(prefix, "login", "remove", "--yes", "ghost")...) _, stderr, code := run(append(prefix, "login", "remove", "--yes", "ghost")...)
if code != int(ExitInternal) { // ExitInternal 不在 README 保證範圍;此處固定為 1(內部錯誤,#10)。
t.Fatalf("want exit 1, got %d", code) if code != 1 {
t.Fatalf("want exit 1 (internal), got %d", code)
} }
if !strings.Contains(stderr, `login "ghost" not found`) { if !strings.Contains(stderr, `login "ghost" not found`) {
t.Fatalf("stderr: %s", stderr) t.Fatalf("stderr: %s", stderr)
+97
View File
@@ -0,0 +1,97 @@
// milestones_commands.go — 跨倉庫里程碑總覽命令的 CLI 接線(#31):
// teai milestones(不帶 --repo)。
//
// 核心邏輯在 internal/workflow(MilestoneOverview),本檔只做旗標
// 剖析、資料源接線與輸出格式化(與 stalled_commands.go 同模式)。
// 輸出與 gitea.py milestones 位元組相容(MilestoneEntry 自訂
// MarshalJSON;縮排 2、停用 HTML 轉義、空清單輸出 [],見 #26 慣例)。
package cli
import (
"fmt"
"time"
"gitea.alterminal.com/alterminal/teai/internal/gitea"
"gitea.alterminal.com/alterminal/teai/internal/workflow"
)
// newMilestoneSourceFunc 建立總覽的資料源;宣告為變數讓接線層測試
// 可注入假資料源(與 newStalledSourceFunc 同模式)。
var newMilestoneSourceFunc = newMilestoneSource
// newMilestoneSource 依全域選項建立 workflow.MilestoneSource(API 實作)。
func newMilestoneSource(env *Env) (workflow.MilestoneSource, error) {
token, _, err := gitea.ResolveToken(gitea.AuthOptions{
FlagToken: env.Globals.Token,
SiteURL: env.Globals.URL,
ConfigPath: env.Globals.ConfigPath,
})
if err != nil {
return nil, err
}
client, err := gitea.New(env.Globals.URL, token, env.Globals.Timeout)
if err != nil {
return nil, err
}
return &workflow.APIClient{Client: client}, nil
}
// milestonesNowFunc 回傳總覽的基準時刻;宣告為變數讓測試可固定時刻。
var milestonesNowFunc = time.Now
// milestoneEntryRow 把 MilestoneEntry 轉成 table 列(unassigned 僅 JSON
// 模式輸出完整摘要;table 給人工抽查用,取計數)。
func milestoneEntryRow(e workflow.MilestoneEntry) gitea.Values {
dueOn := ""
if e.DueOn != nil {
dueOn = *e.DueOn
}
dueHours := ""
if e.DueHours != nil {
dueHours = fmt.Sprintf("%.1f", *e.DueHours)
}
updatedAt := ""
if e.UpdatedAt != nil {
updatedAt = *e.UpdatedAt
}
id := ""
if e.ID != nil {
id = fmt.Sprintf("%d", *e.ID)
}
return gitea.Values{
e.Repo, id, e.Title, e.URL,
e.OpenIssues, e.ClosedIssues, dueOn, dueHours,
e.Overdue, len(e.Unassigned), updatedAt,
}
}
// runMilestonesOverview:teai milestones(跨倉庫總覽)。
// JSON 輸出與 gitea.py milestones 位元組相容;空清單輸出 [](#26 慣例:
// gitea.py 對空清單不輸出,teai 輸出 [] 供 JSON 消費者明確判斷)。
func runMilestonesOverview(env *Env) error {
src, err := newMilestoneSourceFunc(env)
if err != nil {
return err
}
entries, err := workflow.MilestoneOverview(src, env.Globals.URL, milestonesNowFunc())
if err != nil {
return err
}
p := printer(env)
if p.Format == gitea.FormatTable {
rows := make([]gitea.Values, 0, len(entries))
for i := range entries {
rows = append(rows, milestoneEntryRow(entries[i]))
}
return p.PrintList([]gitea.Field{
{Name: "repo"}, {Name: "id"}, {Name: "title"}, {Name: "url"},
{Name: "open_issues"}, {Name: "closed_issues"}, {Name: "due_on"},
{Name: "due_hours"}, {Name: "overdue"}, {Name: "unassigned"}, {Name: "updated_at"},
}, rows)
}
if len(entries) == 0 {
_, err := fmt.Fprintln(env.Out, "[]")
return err
}
return printJSON(env.Out, entries)
}
+188
View File
@@ -0,0 +1,188 @@
// milestones_commands_test.go — 跨倉庫里程碑總覽的 CLI 接線層測試(#31):
// 注入假 MilestoneSource,驗證 Run→dispatch→輸出完整路徑,不走網路
// (與 stalled_commands_test.go 同模式)。
package cli
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"gitea.alterminal.com/alterminal/teai/internal/workflow"
)
// stubMilestoneSource 以記憶體資料實作 workflow.MilestoneSource。
type stubMilestoneSource struct {
orgs []string
repos map[string][]workflow.Repo
milestones map[string][]workflow.Milestone
openIssues map[string][]workflow.Issue // key: owner/repo?milestone=<title>
}
func (s *stubMilestoneSource) MyOrganizations() ([]string, error) { return s.orgs, nil }
func (s *stubMilestoneSource) OrganizationRepositories(org string) ([]workflow.Repo, error) {
return s.repos[org], nil
}
func (s *stubMilestoneSource) OpenMilestones(owner, repo string) ([]workflow.Milestone, error) {
return s.milestones[owner+"/"+repo], nil
}
func (s *stubMilestoneSource) MilestoneOpenIssues(owner, repo, title string) ([]workflow.Issue, error) {
return s.openIssues[owner+"/"+repo+"?milestone="+title], nil
}
// newStubMilestoneEnv 注入假資料源並固定時刻。
func newStubMilestoneEnv(t *testing.T, src *stubMilestoneSource, frozen time.Time) {
t.Helper()
origSrc, origNow := newMilestoneSourceFunc, milestonesNowFunc
newMilestoneSourceFunc = func(env *Env) (workflow.MilestoneSource, error) { return src, nil }
milestonesNowFunc = func() time.Time { return frozen }
t.Cleanup(func() {
newMilestoneSourceFunc, milestonesNowFunc = origSrc, origNow
})
}
// stubPullIssue 以 JSON 建構帶 pull_request 標記的條目(pullMarker 未匯出,
// 測試從套件外以 API 回應的形狀建構,走 Issue.UnmarshalJSON 同一路徑)。
func stubPullIssue(t *testing.T) workflow.Issue {
t.Helper()
var issue workflow.Issue
err := json.Unmarshal([]byte(`{
"number": 32, "title": "文件", "state": "open",
"updated_at": "2026-09-08T00:00:00Z",
"html_url": "https://gitea.alterminal.com/alterminal/agents/pulls/32",
"user": {"username": "alex"},
"pull_request": {}
}`), &issue)
if err != nil {
t.Fatalf("建構 stub PR 條目失敗:%v", err)
}
return issue
}
// idPtr/msPtr 是測試用指標 helper(workflow 套件內同名函式未匯出)。
func idPtr(i int64) *int64 { return &i }
func msPtr(s string) *string { return &s }
// newStubMilestoneData 建構總覽情境:兩倉庫各一里程碑、一個未分派 PR。
func newStubMilestoneData(t *testing.T) *stubMilestoneSource {
due := "2026-09-09T00:00:00Z"
return &stubMilestoneSource{
orgs: []string{"alterminal"},
repos: map[string][]workflow.Repo{"alterminal": {
{Name: "agents"}, {Name: "teai"},
}},
milestones: map[string][]workflow.Milestone{
"alterminal/agents": {
{ID: idPtr(7), Title: "MVP", State: "open",
DueOn: &due, UpdatedAt: "2026-09-01T00:00:00Z",
OpenIssues: 1, ClosedIssues: 0},
},
"alterminal/teai": {
{ID: idPtr(3), Title: "CLI", State: "open",
DueOn: msPtr("2026-09-12T00:00:00Z"), UpdatedAt: "2026-09-05T00:00:00Z",
OpenIssues: 1, ClosedIssues: 2},
},
},
openIssues: map[string][]workflow.Issue{
"alterminal/agents?milestone=MVP": {stubPullIssue(t)},
},
}
}
// TestWiringMilestonesOverview 驗證 teai milestones 輸出跨倉庫總覽
// (JSON 縮排 2、鍵序與欄位齊 gitea.py)。
func TestWiringMilestonesOverview(t *testing.T) {
newStubMilestoneEnv(t, newStubMilestoneData(t), time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
stdout, _, code := run("milestones")
if code != 0 {
t.Fatalf("milestones 應回 0,得到 %d(stdout=%q)", code, stdout)
}
for _, want := range []string{
`"repo": "alterminal/agents"`,
`"title": "MVP"`,
`"overdue": true`,
`"type": "pull"`,
`"author": "alex"`,
} {
if !strings.Contains(stdout, want) {
t.Fatalf("milestones 輸出應含 %q,得到:\n%s", want, stdout)
}
}
// 排序:agents MVP(09-09)在 teai CLI(09-12)前。
if strings.Index(stdout, `"title": "MVP"`) > strings.Index(stdout, `"title": "CLI"`) {
t.Fatalf("期限近者應在前:\n%s", stdout)
}
}
// TestWiringMilestonesEmpty 驗證無里程碑 → [](#26 慣例)。
func TestWiringMilestonesEmpty(t *testing.T) {
newStubMilestoneEnv(t, &stubMilestoneSource{
orgs: []string{"alterminal"},
repos: map[string][]workflow.Repo{"alterminal": {{Name: "agents"}}},
milestones: map[string][]workflow.Milestone{},
openIssues: map[string][]workflow.Issue{},
}, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
stdout, _, code := run("milestones")
if code != 0 {
t.Fatalf("milestones 空清單應回 0,得到 %d", code)
}
if strings.TrimSpace(stdout) != "[]" {
t.Fatalf("無里程碑應輸出 [],得到 %q", stdout)
}
}
// TestWiringMilestonesTable 驗證 table 輸出(人工抽查用)。
func TestWiringMilestonesTable(t *testing.T) {
newStubMilestoneEnv(t, newStubMilestoneData(t), time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
stdout, _, code := run("milestones", "--output", "table")
if code != 0 {
t.Fatalf("milestones --output table 應回 0,得到 %d", code)
}
for _, want := range []string{"repo", "overdue", "MVP", "alterminal/agents"} {
if !strings.Contains(stdout, want) {
t.Fatalf("table 輸出應含 %q,得到:\n%s", want, stdout)
}
}
}
// TestWiringMilestonesRepoFlagCompat 驗證 teai milestones --repo a/b
// 維持現行單倉庫 list 語義(#31:帶 --repo 時不變)。
func TestWiringMilestonesRepoFlagCompat(t *testing.T) {
var gotPath, gotQuery string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath, gotQuery = r.URL.Path, r.URL.RawQuery
w.Write([]byte(`[{"title":"v1","state":"open","description":"","due_on":""}]`))
}))
t.Cleanup(srv.Close)
stdout, _, code := run("--url", srv.URL, "milestones", "--repo", "a/b")
if code != 0 {
t.Fatalf("milestones --repo a/b 應回 0,得到 %d", code)
}
if gotPath != "/api/v1/repos/a/b/milestones" {
t.Fatalf("應呼叫 /repos/a/b/milestones,得到 %s", gotPath)
}
if !strings.Contains(gotQuery, "state=open") {
t.Fatalf("查詢應含 state=open,得到 %q", gotQuery)
}
if !strings.Contains(stdout, `"title":"v1"`) {
t.Fatalf("輸出應含 title v1,得到:%s", stdout)
}
}
// TestWiringMilestonesUsage 驗證未知子命令與位置參數 → exit 2。
func TestWiringMilestonesUsage(t *testing.T) {
newStubMilestoneEnv(t, newStubMilestoneData(t), time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
if _, _, code := run("milestones", "bogus"); code != int(ExitUsage) {
t.Fatalf("milestones bogus 應回 ExitUsage,得到 %d", code)
}
if _, _, code := run("milestones", "extra", "arg"); code != int(ExitUsage) {
t.Fatalf("milestones 位置參數應回 ExitUsage,得到 %d", code)
}
// milestones list 仍照舊要求 --repo。
if _, _, code := run("milestones", "list"); code != int(ExitUsage) {
t.Fatalf("milestones list 缺 --repo 應回 ExitUsage,得到 %d", code)
}
}
+170
View File
@@ -0,0 +1,170 @@
// stalled_commands.go — 管理者巡邏命令的 CLI 接線(#7):
// stalled [--hours N] 與 xrefs <owner>/<repo> <number>。
//
// 核心邏輯在 internal/workflow(ScanStalled/ResolveIssueXrefs),
// 本檔只做旗標剖析、資料源接線與輸出格式化。輸出走得體架構的
// Printer(--output json|table);錯誤經 cli.exitCodeFor 映射結束碼
// (用法 2/API 3)。token 解析選序見 internal/gitea/auth.go。
package cli
import (
"encoding/json"
"flag"
"fmt"
"io"
"strconv"
"time"
"gitea.alterminal.com/alterminal/teai/internal/gitea"
"gitea.alterminal.com/alterminal/teai/internal/workflow"
)
func init() {
commands["stalled"] = &command{
name: "stalled",
usage: "停滯的 open issues/PR(管理者巡邏;--hours N 門檻,預設 4)",
run: runStalled,
}
commands["xrefs"] = &command{
name: "xrefs",
usage: "解析 issue/PR 內文與留言中的 #N/repo#N/owner/repo#N 引用",
run: runXrefs,
}
}
// newStalledSourceFunc 建立 stalled/xrefs 的資料源;宣告為變數讓
// 接線層測試可注入假資料源(不走網路),與 newScannerFunc 同模式。
var newStalledSourceFunc = newStalledSource
// newStalledSource 依全域選項建立 workflow.StalledSource(API 實作)。
func newStalledSource(env *Env) (workflow.StalledSource, error) {
token, _, err := gitea.ResolveToken(gitea.AuthOptions{
FlagToken: env.Globals.Token,
SiteURL: env.Globals.URL,
ConfigPath: env.Globals.ConfigPath,
})
if err != nil {
return nil, err
}
client, err := gitea.New(env.Globals.URL, token, env.Globals.Timeout)
if err != nil {
return nil, err
}
return &workflow.APIClient{Client: client}, nil
}
// stalledFields 是 stalled 的 table 欄位(JSON 模式輸出完整 Item,
// 欄位序與 gitea.py 一致,見 workflow.Item.MarshalJSON)。
func stalledFields() []gitea.Field {
return []gitea.Field{
{Name: "type"}, {Name: "repo"}, {Name: "number"}, {Name: "title"},
{Name: "last_comment_by"}, {Name: "last_activity_at"},
{Name: "stalled_hours"}, {Name: "reason"},
}
}
// stalledRow 把 Item 轉成 table 列(assignees/reviewers/child_activity
// 僅 JSON 模式輸出;table 給人工抽查用,取共同欄位)。
// stalled_hours 定點一位小數(fmt.Sprint(9.0) 會印 "9",與 JSON 的 9.0 不一致)。
func stalledRow(item workflow.Item) gitea.Values {
return gitea.Values{
item.Type, item.Repo, item.Number, item.Title,
item.LastCommentBy, workflow.FormatMoment(item.LastActivityAt),
strconv.FormatFloat(item.StalledHours, 'f', 1, 64), item.Reason,
}
}
// runStalled:teai stalled [--hours N]。
// 預設門檻 4 小時;--hours 需為正數(同 gitea.py _parse_hours)。
// JSON 輸出與 gitea.py stalled 位元組相容(workflow.Item 自訂 MarshalJSON;
// 這裡輸出前停用 HTML 轉義並縮排 2,對應 Python json.dumps(indent=2))。
func runStalled(env *Env, args []string) error {
fs := flag.NewFlagSet("teai stalled", flag.ContinueOnError)
fs.SetOutput(env.Err)
hours := fs.Float64("hours", workflow.StalledDefaultHours, "停滯門檻(小時,正數)")
if err := parseFlags(fs, args); err != nil {
return err
}
if fs.NArg() != 0 {
return &ErrUsage{Msg: "stalled 不接受位置參數"}
}
if *hours <= 0 {
return &ErrUsage{Msg: "--hours 需為正數(小時),例如 --hours 4"}
}
src, err := newStalledSourceFunc(env)
if err != nil {
return err
}
items, err := workflow.RunStalled(src, *hours, nowFunc())
if err != nil {
return err
}
p := printer(env)
if p.Format == gitea.FormatTable {
rows := make([]gitea.Values, 0, len(items))
for _, item := range items {
rows = append(rows, stalledRow(item))
}
return p.PrintList(stalledFields(), rows)
}
// JSON:空清單輸出 [](README:無停滯項目 → 空陣列);有項目時
// 縮排 2 且停用 HTML 轉義,與 gitea.py 的 _dump 位元組相容。
if len(items) == 0 {
_, err := fmt.Fprintln(env.Out, "[]")
return err
}
return printJSON(env.Out, items)
}
// runXrefs:teai xrefs <owner>/<repo> <number>。
// 編號不存在 → API 錯誤(結束碼 3);無引用 → []。
func runXrefs(env *Env, args []string) error {
fs := flag.NewFlagSet("teai xrefs", flag.ContinueOnError)
fs.SetOutput(env.Err)
if err := parseFlags(fs, args); err != nil {
return err
}
if fs.NArg() != 2 {
return &ErrUsage{Msg: "xrefs 需要 <owner>/<repo> <number> 兩個參數"}
}
owner, name, err := splitRepoFlag(args[0])
if err != nil {
return err
}
number, err := strconv.ParseInt(args[1], 10, 64)
if err != nil || number <= 0 {
return &ErrUsage{Msg: fmt.Sprintf("編號需為正整數,得到 %q", args[1])}
}
src, err := newStalledSourceFunc(env)
if err != nil {
return err
}
hits, err := workflow.ResolveIssueXrefs(src, owner, name, number)
if err != nil {
return err
}
p := printer(env)
rows := make([]gitea.Values, 0, len(hits))
for _, h := range hits {
rows = append(rows, gitea.Values{h.Owner, h.Repo, h.Number, h.Source})
}
return p.PrintList(
[]gitea.Field{
{Name: "owner"}, {Name: "repo"}, {Name: "number"}, {Name: "source"},
},
rows,
)
}
// nowFunc 回傳目前時刻;宣告為變數讓測試可固定時刻(stalled 判定用)。
var nowFunc = time.Now
// printJSON 以縮排 2、停用 HTML 轉義輸出 JSON(與 gitea.py 的
// json.dumps(ensure_ascii=False, indent=2) 位元組相容;HTML 轉義會把
// <、>、& 變 \u003c 等,破壞相容性)。
func printJSON(w io.Writer, v any) error {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
return enc.Encode(v)
}
+248
View File
@@ -0,0 +1,248 @@
// stalled_commands_test.go — stalled/xrefs CLI 接線層測試(#7):
// 注入假 StalledSource,驗證 Run→dispatch→flagset 完整路徑,
// 不走網路(與 workflow_commands_test.go 同模式)。
package cli
import (
"strings"
"testing"
"time"
"gitea.alterminal.com/alterminal/teai/internal/gitea"
"gitea.alterminal.com/alterminal/teai/internal/workflow"
)
// stubStalledSource 以記憶體資料實作 workflow.StalledSource。
type stubStalledSource struct {
username string
orgs []string
repos map[string][]workflow.Repo
issues map[string]map[int64]workflow.Issue
comments map[string][]workflow.Comment
getErr error
}
func (s *stubStalledSource) CurrentUser() (string, error) { return s.username, nil }
func (s *stubStalledSource) MyOrganizations() ([]string, error) {
return s.orgs, nil
}
func (s *stubStalledSource) OrganizationRepositories(org string) ([]workflow.Repo, error) {
return s.repos[org], nil
}
func (s *stubStalledSource) OpenIssues(owner, repo string) ([]workflow.Issue, error) {
var out []workflow.Issue
for _, i := range s.issues[owner+"/"+repo] {
out = append(out, i)
}
return out, nil
}
func (s *stubStalledSource) OpenPulls(owner, repo string) ([]workflow.PullRequest, error) {
return nil, nil
}
func (s *stubStalledSource) IssueComments(owner, repo string, number int64) ([]workflow.Comment, error) {
return s.comments[owner+"/"+repo+"/"+itoa(number)], nil
}
func (s *stubStalledSource) TryGetIssue(owner, repo string, number int64) (workflow.Issue, bool, error) {
i, ok := s.issues[owner+"/"+repo][number]
return i, ok, nil
}
func (s *stubStalledSource) IssueTimeline(owner, repo string, number int64) ([]workflow.TimelineEvent, error) {
return nil, nil
}
func (s *stubStalledSource) GetIssue(owner, repo string, number int64) (workflow.Issue, error) {
if s.getErr != nil {
return workflow.Issue{}, s.getErr
}
i, ok := s.issues[owner+"/"+repo][number]
if !ok {
return workflow.Issue{}, &gitea.ErrAPI{Op: "GET /repos/" + owner + "/" + repo + "/issues/" + itoa(number), StatusCode: 404}
}
return i, nil
}
func itoa(n int64) string {
if n == 0 {
return "0"
}
var b []byte
for n > 0 {
b = append([]byte{byte('0' + n%10)}, b...)
n /= 10
}
return string(b)
}
// newStubStalledEnv 注入假資料源並固定時刻。
func newStubStalledEnv(t *testing.T, src *stubStalledSource, frozen time.Time) {
t.Helper()
origSrc, origNow := newStalledSourceFunc, nowFunc
newStalledSourceFunc = func(env *Env) (workflow.StalledSource, error) { return src, nil }
nowFunc = func() time.Time { return frozen }
t.Cleanup(func() { newStalledSourceFunc, nowFunc = origSrc, origNow })
}
// isoAt 把相對分鐘轉成 ISO8601 字串(假資料用;錨點同 workflow 測試)。
func isoAt(minutes int) string {
return workflow.FormatMoment(time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC).Add(time.Duration(minutes) * time.Minute))
}
// newStubStalledData 建構 stalled 情境:agents#1 停滯 10 小時(no-assignee)。
func newStubStalledData() *stubStalledSource {
return &stubStalledSource{
username: "ceo",
orgs: []string{"alterminal"},
repos: map[string][]workflow.Repo{"alterminal": {{Name: "agents"}}},
issues: map[string]map[int64]workflow.Issue{
"alterminal/agents": {
1: {Number: 1, Title: "停滯項", State: "open",
CreatedAt: isoAt(-600), UpdatedAt: isoAt(-600),
Repository: &workflow.Repository{FullName: "alterminal/agents"}},
},
},
comments: map[string][]workflow.Comment{},
}
}
// TestWiringStalled 驗證 stalled 基本路徑:JSON 輸出含停滯欄位。
func TestWiringStalled(t *testing.T) {
newStubStalledEnv(t, newStubStalledData(), time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
stdout, _, code := run("stalled")
if code != 0 {
t.Fatalf("stalled 應回 0,得到 %d(stdout=%q)", code, stdout)
}
for _, want := range []string{`"type": "issue"`, `"reason": "no-assignee"`, `"stalled_hours": 10.0`} {
if !strings.Contains(stdout, want) {
t.Fatalf("stalled 輸出應含 %q,得到:\n%s", want, stdout)
}
}
}
// TestWiringStalledEmpty 驗證 stalled 無任何條目時輸出 []、exit 0(#37)。
func TestWiringStalledEmpty(t *testing.T) {
newStubStalledEnv(t, &stubStalledSource{
username: "ceo",
orgs: []string{"alterminal"},
repos: map[string][]workflow.Repo{"alterminal": {}},
issues: map[string]map[int64]workflow.Issue{},
comments: map[string][]workflow.Comment{},
}, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
stdout, _, code := run("stalled")
if code != 0 {
t.Fatalf("stalled 空情境應回 0,得到 %d(stdout=%q)", code, stdout)
}
if strings.TrimSpace(stdout) != "[]" {
t.Fatalf("stalled 無條目應輸出 [],得到 %q", stdout)
}
}
// TestWiringStalledHoursFlag 驗證 --hours 覆寫門檻與非正數被攔。
func TestWiringStalledHoursFlag(t *testing.T) {
freeze := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
newStubStalledEnv(t, newStubStalledData(), freeze)
// 門檻 20h → 10h 停滯未過門檻 → 空陣列。
stdout, _, code := run("stalled", "--hours", "20")
if code != 0 {
t.Fatalf("stalled --hours 20 應回 0,得到 %d", code)
}
if strings.TrimSpace(stdout) != "[]" {
t.Fatalf("無停滯項應輸出 [],得到 %q", stdout)
}
// 非正數 → exit 2。
_, stderr, code := run("stalled", "--hours", "-1")
if code != int(ExitUsage) {
t.Fatalf("stalled --hours -1 應回 ExitUsage(%d),得到 %d(stderr=%q)", int(ExitUsage), code, stderr)
}
// 位置參數 → exit 2。
_, _, code = run("stalled", "extra")
if code != int(ExitUsage) {
t.Fatalf("stalled extra 應回 ExitUsage(%d),得到 %d", int(ExitUsage), code)
}
}
// TestWiringStalledTable 驗證 table 輸出(README 範例)。
func TestWiringStalledTable(t *testing.T) {
newStubStalledEnv(t, newStubStalledData(), time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
stdout, _, code := run("stalled", "--output", "table")
if code != 0 {
t.Fatalf("stalled --output table 應回 0,得到 %d", code)
}
for _, want := range []string{"reason", "no-assignee", "停滯項"} {
if !strings.Contains(stdout, want) {
t.Fatalf("table 輸出應含 %q,得到:\n%s", want, stdout)
}
}
}
// TestWiringXrefs 驗證 xrefs 解析輸出(含 body/comment 出處)。
func TestWiringXrefs(t *testing.T) {
src := newStubStalledData()
src.issues["alterminal/agents"][1] = workflow.Issue{
Number: 1, Title: "父項", State: "open",
Body: "子項:agents#2",
Repository: &workflow.Repository{FullName: "alterminal/agents"},
}
src.issues["alterminal/agents"][2] = workflow.Issue{
Number: 2, Title: "子項", State: "open",
Repository: &workflow.Repository{FullName: "alterminal/agents"},
}
src.comments["alterminal/agents/1"] = []workflow.Comment{
{Body: "看 agents#2", User: &workflow.User{UserName: "alex"}},
}
newStubStalledEnv(t, src, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
stdout, _, code := run("xrefs", "alterminal/agents", "1")
if code != 0 {
t.Fatalf("xrefs 應回 0,得到 %d(stdout=%q)", code, stdout)
}
// Printer JSON 為單行緊湊格式(無縮排);命令清單類輸出一律如此。
for _, want := range []string{`"repo":"agents"`, `"number":2`, `"source":"body"`} {
if !strings.Contains(stdout, want) {
t.Fatalf("xrefs 輸出應含 %q,得到:\n%s", want, stdout)
}
}
}
// TestWiringXrefsEmpty 驗證無引用 → []。
func TestWiringXrefsEmpty(t *testing.T) {
src := newStubStalledData()
src.issues["alterminal/agents"][1] = workflow.Issue{
Number: 1, Title: "無引用", State: "open",
Body: "沒有任何引用",
Repository: &workflow.Repository{FullName: "alterminal/agents"},
}
newStubStalledEnv(t, src, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
stdout, _, code := run("xrefs", "alterminal/agents", "1")
if code != 0 {
t.Fatalf("xrefs 應回 0,得到 %d", code)
}
if strings.TrimSpace(stdout) != "[]" {
t.Fatalf("無引用應輸出 [],得到 %q", stdout)
}
}
// TestWiringXrefsUsage 驗證參數不足/格式錯誤 → exit 2。
func TestWiringXrefsUsage(t *testing.T) {
newStubStalledEnv(t, newStubStalledData(), time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
if _, _, code := run("xrefs"); code != int(ExitUsage) {
t.Fatalf("xrefs 無參數應回 ExitUsage,得到 %d", code)
}
if _, _, code := run("xrefs", "alterminal/agents"); code != int(ExitUsage) {
t.Fatalf("xrefs 缺編號應回 ExitUsage,得到 %d", code)
}
if _, _, code := run("xrefs", "not-a-repo", "1"); code != int(ExitUsage) {
t.Fatalf("xrefs repo 格式錯誤應回 ExitUsage,得到 %d", code)
}
if _, _, code := run("xrefs", "alterminal/agents", "abc"); code != int(ExitUsage) {
t.Fatalf("xrefs 編號非數字應回 ExitUsage,得到 %d", code)
}
}
// TestWiringXrefsNotFound 驗證 404 → exit 3(API 錯誤)。
func TestWiringXrefsNotFound(t *testing.T) {
src := newStubStalledData()
src.getErr = &gitea.ErrAPI{Op: "GET /repos/alterminal/agents/issues/99", StatusCode: 404}
newStubStalledEnv(t, src, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
_, stderr, code := run("xrefs", "alterminal/agents", "99")
if code != int(ExitAPI) {
t.Fatalf("xrefs 404 應回 ExitAPI(%d),得到 %d(stderr=%q)", int(ExitAPI), code, stderr)
}
}
+33
View File
@@ -0,0 +1,33 @@
// version_test.go 驗證版本字串解析:go test 環境 Main.Version 為 "(devel)"
// 時應退回開發版本號;tag 與 pseudo-version 行為由建置驗證涵蓋
// (go install pkg@tag 顯示 tag;clone 建置顯示 pseudo-version)。
package cli
import (
"strings"
"testing"
)
// TestBuildVersionFallsBackToDev 確認本地測試環境(Main.Version == "(devel)")
// 退回 Version;同時確保輸出是可讀版本字串(非空、無括號)。
func TestBuildVersionFallsBackToDev(t *testing.T) {
v := buildVersion()
if v == "" {
t.Fatalf("buildVersion 不應為空")
}
if strings.ContainsAny(v, "()") {
t.Errorf("buildVersion 不應含內部佔位(括號),得到:%q", v)
}
}
// TestRunVersionUsesBuildVersion 確認 version 命令輸出 buildVersion 的結果。
func TestRunVersionUsesBuildVersion(t *testing.T) {
stdout, _, code := run("version")
if code != 0 {
t.Fatalf("version 應回 0,得到 %d", code)
}
want := "teai version " + buildVersion()
if !strings.Contains(stdout, want) {
t.Errorf("version 輸出應含 %q,得到:%q", want, stdout)
}
}
+15 -10
View File
@@ -31,6 +31,11 @@ func init() {
// errNoRepoFlag 是 --repo 值格式錯誤。 // errNoRepoFlag 是 --repo 值格式錯誤。
var errNoRepoFlag = errors.New("--repo 需為 owner/repo 形式") var errNoRepoFlag = errors.New("--repo 需為 owner/repo 形式")
// newScannerFunc 建立工作流 Scanner;正式環境用 API client。
// 宣告為變數讓接線層測試可注入假 client(不走網路),
// 彌補 workflow 套件單元測試覆蓋不到 CLI 分派路徑的缺口。
var newScannerFunc = newWorkflowClient
// newWorkflowClient 依全域選項建立 workflow 所需的 API client。 // newWorkflowClient 依全域選項建立 workflow 所需的 API client。
func newWorkflowClient(env *Env) (*workflow.Scanner, error) { func newWorkflowClient(env *Env) (*workflow.Scanner, error) {
token, _, err := gitea.ResolveToken(gitea.AuthOptions{ token, _, err := gitea.ResolveToken(gitea.AuthOptions{
@@ -58,7 +63,7 @@ func runWhoami(env *Env, args []string) error {
if len(args) != 0 { if len(args) != 0 {
return &ErrUsage{Msg: "whoami 不接受參數"} return &ErrUsage{Msg: "whoami 不接受參數"}
} }
s, err := newWorkflowClient(env) s, err := newScannerFunc(env)
if err != nil { if err != nil {
return err return err
} }
@@ -77,7 +82,7 @@ func runOrgs(env *Env, args []string) error {
if len(args) != 0 { if len(args) != 0 {
return &ErrUsage{Msg: "orgs 不接受參數"} return &ErrUsage{Msg: "orgs 不接受參數"}
} }
s, err := newWorkflowClient(env) s, err := newScannerFunc(env)
if err != nil { if err != nil {
return err return err
} }
@@ -100,13 +105,13 @@ func runMembers(env *Env, args []string) error {
fs := flag.NewFlagSet("teai members", flag.ContinueOnError) fs := flag.NewFlagSet("teai members", flag.ContinueOnError)
fs.SetOutput(env.Err) fs.SetOutput(env.Err)
hasWork := fs.Bool("has-work", false, "只列出有未完成工作的成員") hasWork := fs.Bool("has-work", false, "只列出有未完成工作的成員")
if err := fs.Parse(args); err != nil { if err := parseFlags(fs, args); err != nil {
return &ErrUsage{Msg: err.Error()} return err
} }
if fs.NArg() != 0 { if fs.NArg() != 0 {
return &ErrUsage{Msg: "members 不接受位置參數"} return &ErrUsage{Msg: "members 不接受位置參數"}
} }
s, err := newWorkflowClient(env) s, err := newScannerFunc(env)
if err != nil { if err != nil {
return err return err
} }
@@ -126,7 +131,7 @@ func runMine(env *Env, args []string) error {
if len(args) != 0 { if len(args) != 0 {
return &ErrUsage{Msg: "mine 不接受參數"} return &ErrUsage{Msg: "mine 不接受參數"}
} }
s, err := newWorkflowClient(env) s, err := newScannerFunc(env)
if err != nil { if err != nil {
return err return err
} }
@@ -149,8 +154,8 @@ func runPulls(env *Env, args []string) error {
mine := fs.Bool("mine", false, "限定作者是目前帳號") mine := fs.Bool("mine", false, "限定作者是目前帳號")
reviewer := fs.Bool("reviewer", false, "限定自己是 requested reviewer") reviewer := fs.Bool("reviewer", false, "限定自己是 requested reviewer")
repo := fs.String("repo", "", "限定單一倉庫(owner/repo)") repo := fs.String("repo", "", "限定單一倉庫(owner/repo)")
if err := fs.Parse(args); err != nil { if err := parseFlags(fs, args); err != nil {
return &ErrUsage{Msg: err.Error()} return err
} }
if fs.NArg() != 0 { if fs.NArg() != 0 {
return &ErrUsage{Msg: "pulls 不接受位置參數"} return &ErrUsage{Msg: "pulls 不接受位置參數"}
@@ -166,7 +171,7 @@ func runPulls(env *Env, args []string) error {
} }
owner, name = parts[0], parts[1] owner, name = parts[0], parts[1]
} }
s, err := newWorkflowClient(env) s, err := newScannerFunc(env)
if err != nil { if err != nil {
return err return err
} }
@@ -199,7 +204,7 @@ func runNext(env *Env, args []string) error {
if len(args) != 0 { if len(args) != 0 {
return &ErrUsage{Msg: "next 不接受參數"} return &ErrUsage{Msg: "next 不接受參數"}
} }
s, err := newWorkflowClient(env) s, err := newScannerFunc(env)
if err != nil { if err != nil {
return err return err
} }
+233
View File
@@ -0,0 +1,233 @@
// workflow_commands_test.go — CLI 接線層測試:驗證 Run→dispatch→命令 flagset
// 的完整路徑。ceo 於 PR #13 審核指出帶旗標命令(members --has-work、
// pulls --mine/--reviewer)在 CLI 層全部 exit 2,workflow 單元測試覆蓋不到
// 這條路徑——本檔以注入假 client 的方式補上,不走網路。
package cli
import (
"strings"
"testing"
"gitea.alterminal.com/alterminal/teai/internal/workflow"
)
// stubClient 以記憶體資料實作 workflow.Client(最小集,僅供接線測試)。
type stubClient struct {
currentUser string
orgs []workflow.Org
teams map[string][]workflow.Team
members map[int64][]string
repos map[string][]workflow.Repo
issues map[string][]workflow.Issue
pulls map[string][]workflow.PullRequest
comments map[string][]workflow.Comment
}
func (c *stubClient) CurrentUser() (string, error) { return c.currentUser, nil }
func (c *stubClient) ListOrgs() ([]string, error) {
out := make([]string, 0, len(c.orgs))
for _, o := range c.orgs {
out = append(out, o.Account())
}
return out, nil
}
func (c *stubClient) ListTeams(org string) ([]workflow.Team, error) {
return c.teams[org], nil
}
func (c *stubClient) ListTeamMembers(teamID int64) ([]string, error) {
return c.members[teamID], nil
}
func (c *stubClient) ListOrgRepos(org string) ([]workflow.Repo, error) {
return c.repos[org], nil
}
func (c *stubClient) ListIssues(owner, repo string) ([]workflow.Issue, error) {
return c.issues[owner+"/"+repo], nil
}
func (c *stubClient) ListPulls(owner, repo string) ([]workflow.PullRequest, error) {
return c.pulls[owner+"/"+repo], nil
}
func (c *stubClient) ListComments(owner, repo string, number int64) ([]workflow.Comment, error) {
return c.comments[owner+"/"+repo], nil
}
// newStubEnv 注入假 client,回傳還原函式(測試結束時呼叫)。
func newStubEnv(t *testing.T, c *stubClient) {
t.Helper()
orig := newScannerFunc
newScannerFunc = func(env *Env) (*workflow.Scanner, error) {
return &workflow.Scanner{Client: c}, nil
}
t.Cleanup(func() { newScannerFunc = orig })
}
// newStubData 建構標準情境:alterminal 組織、Agents 團隊、teai 倉庫。
func newStubData() *stubClient {
return &stubClient{
currentUser: "alex",
orgs: []workflow.Org{{UserName: "alterminal"}},
teams: map[string][]workflow.Team{"alterminal": {{ID: 1, Name: "Agents"}}},
members: map[int64][]string{1: {"alex", "max", "queena"}},
repos: map[string][]workflow.Repo{"alterminal": {{Name: "teai"}}},
issues: map[string][]workflow.Issue{},
pulls: map[string][]workflow.PullRequest{},
comments: map[string][]workflow.Comment{},
}
}
// TestWiringMembersHasWork 驗證 members --has-work 不再被攔成 exit 2。
func TestWiringMembersHasWork(t *testing.T) {
newStubEnv(t, newStubData())
stdout, _, code := run("members", "--has-work")
if code != 0 {
t.Fatalf("members --has-work 應回 0,得到 %d(stdout=%q)", code, stdout)
}
// 無未完成工作 → 空輸出(每行一個帳號,無帳號即無輸出)。
if strings.TrimSpace(stdout) != "" {
t.Fatalf("無工作時 members --has-work 應無輸出,得到 %q", stdout)
}
}
// TestWiringPullsMine 驗證 pulls --mine 不再被攔成 exit 2。
func TestWiringPullsMine(t *testing.T) {
newStubEnv(t, newStubData())
stdout, _, code := run("pulls", "--mine")
if code != 0 {
t.Fatalf("pulls --mine 應回 0,得到 %d(stdout=%q)", code, stdout)
}
if strings.TrimSpace(stdout) != "[]" {
t.Fatalf("pulls --mine 空清單應輸出 [],得到 %q", stdout)
}
}
// TestWiringPullsReviewer 驗證 pulls --reviewer 不再被攔成 exit 2。
func TestWiringPullsReviewer(t *testing.T) {
newStubEnv(t, newStubData())
stdout, _, code := run("pulls", "--reviewer")
if code != 0 {
t.Fatalf("pulls --reviewer 應回 0,得到 %d(stdout=%q)", code, stdout)
}
if strings.TrimSpace(stdout) != "[]" {
t.Fatalf("pulls --reviewer 空清單應輸出 [],得到 %q", stdout)
}
}
// TestWiringPullsRepoFilter 驗證 --repo 旗標可解析且值可帶斜線。
func TestWiringPullsRepoFilter(t *testing.T) {
newStubEnv(t, newStubData())
_, _, code := run("pulls", "--repo", "alterminal/teai")
if code != 0 {
t.Fatalf("pulls --repo alterminal/teai 應回 0,得到 %d", code)
}
// --repo 值格式錯誤 → exit 2。
_, _, code = run("pulls", "--repo", "not-a-repo")
if code != int(ExitUsage) {
t.Fatalf("pulls --repo not-a-repo 應回 ExitUsage(%d),得到 %d", int(ExitUsage), code)
}
}
// TestWiringGlobalAfterCommandFlag 驗證命令旗標與全域選項交錯出現。
func TestWiringGlobalAfterCommandFlag(t *testing.T) {
newStubEnv(t, newStubData())
// members --has-work --output table:命令旗標在前、全域選項在後。
stdout, _, code := run("members", "--has-work", "--output", "table")
if code != 0 {
t.Fatalf("members --has-work --output table 應回 0,得到 %d", code)
}
if strings.Contains(stdout, "--has-work") {
t.Fatalf("全域剖析不應把 --has-work 當成全域選項處理:%q", stdout)
}
}
// TestWiringMembersAll 驗證 members 不帶旗標仍正常(回歸保護)。
func TestWiringMembersAll(t *testing.T) {
newStubEnv(t, newStubData())
stdout, _, code := run("members")
if code != 0 {
t.Fatalf("members 應回 0,得到 %d", code)
}
for _, want := range []string{"alex", "max", "queena"} {
if !strings.Contains(stdout, want) {
t.Fatalf("members 輸出應含 %q,得到 %q", want, stdout)
}
}
}
// TestWiringMine 驗證 mine 空清單輸出 [](與 gitea.py 空輸出的差異見 README)。
func TestWiringMine(t *testing.T) {
newStubEnv(t, newStubData())
stdout, _, code := run("mine")
if code != 0 {
t.Fatalf("mine 應回 0,得到 %d", code)
}
if strings.TrimSpace(stdout) != "[]" {
t.Fatalf("mine 空清單應輸出 [],得到 %q", stdout)
}
}
// TestWiringNextNull 驗證 next 無工作輸出 null、exit 0。
func TestWiringNextNull(t *testing.T) {
newStubEnv(t, newStubData())
stdout, _, code := run("next")
if code != 0 {
t.Fatalf("next 應回 0,得到 %d", code)
}
if strings.TrimSpace(stdout) != "null" {
t.Fatalf("next 無工作應輸出 null,得到 %q", stdout)
}
}
// TestWiringNextTable 驗證 teai next --output table(README 範例)。
func TestWiringNextTable(t *testing.T) {
newStubEnv(t, newStubData())
stdout, _, code := run("next", "--output", "table")
if code != 0 {
t.Fatalf("next --output table 應回 0,得到 %d", code)
}
if !strings.Contains(stdout, "(none)") {
t.Fatalf("next --output table 無工作應輸出 (none),得到 %q", stdout)
}
}
// TestWiringNextWithPull 驗證有工作時 next 輸出 JSON 物件(role=author)。
func TestWiringNextWithPull(t *testing.T) {
c := newStubData()
c.pulls["alterminal/teai"] = []workflow.PullRequest{{
Number: 13,
Title: "gitea.py 工作流命令 Go 化",
User: &workflow.User{UserName: "alex"},
}}
c.comments["alterminal/teai"] = []workflow.Comment{
{CreatedAt: "2026-09-10T00:44:00Z", User: &workflow.User{UserName: "ceo"}},
}
newStubEnv(t, c)
stdout, _, code := run("next")
if code != 0 {
t.Fatalf("next 應回 0,得到 %d", code)
}
for _, want := range []string{`"type":"pull"`, `"role":"author"`, `"number":13`} {
if !strings.Contains(stdout, want) {
t.Fatalf("next 輸出應含 %q,得到 %q", want, stdout)
}
}
}
// TestWiringWhoamiOrgs 驗證 whoami/orgs 的接線輸出。
func TestWiringWhoamiOrgs(t *testing.T) {
newStubEnv(t, newStubData())
stdout, _, code := run("whoami")
if code != 0 || !strings.Contains(stdout, "alex") {
t.Fatalf("whoami code=%d stdout=%q", code, stdout)
}
stdout, _, code = run("orgs")
if code != 0 || !strings.Contains(stdout, "alterminal") {
t.Fatalf("orgs code=%d stdout=%q", code, stdout)
}
}
// TestWiringVersionRejectsArgs 驗證 version 不接受參數(新剖析語義下仍 exit 2)。
func TestWiringVersionRejectsArgs(t *testing.T) {
_, _, code := run("version", "--wat")
if code != int(ExitUsage) {
t.Fatalf("version --wat 應回 ExitUsage(%d),得到 %d", int(ExitUsage), code)
}
}
+101 -13
View File
@@ -11,6 +11,7 @@ import (
"fmt" "fmt"
"net/url" "net/url"
"strconv" "strconv"
"strings"
"gitea.alterminal.com/alterminal/teai/internal/gitea" "gitea.alterminal.com/alterminal/teai/internal/gitea"
) )
@@ -119,8 +120,10 @@ type Pull struct {
// pullRef 是 PR 的 head/base 參照。 // pullRef 是 PR 的 head/base 參照。
type pullRef struct { type pullRef struct {
Ref string `json:"ref"` Ref string `json:"ref"`
SHA string `json:"sha"`
Repo *struct { Repo *struct {
FullName string `json:"full_name"` FullName string `json:"full_name"`
CloneURL string `json:"clone_url"`
} `json:"repo"` } `json:"repo"`
} }
@@ -165,14 +168,18 @@ func repoPath(owner, repo string) string {
} }
// ListIssues 列出倉庫 issues。state:open|closed|all(預設 open); // ListIssues 列出倉庫 issues。state:open|closed|all(預設 open);
// type=issues 排除 PR(Gitea 的 issues 端點會連 PR 一起回)。 // labels 非空時以逗號連接傳給 API 的 labels 參數(Gitea labels 過濾,
func (o *Ops) ListIssues(ctx context.Context, owner, repo, state string) ([]Issue, error) { // 多標籤為 AND 語義);type=issues 排除 PR(Gitea 的 issues 端點會連 PR 一起回)。
func (o *Ops) ListIssues(ctx context.Context, owner, repo, state string, labels []string) ([]Issue, error) {
if state == "" { if state == "" {
state = "open" state = "open"
} }
// state 一律明確傳給 API:issues/milestones 端點省略 state 時預設
// open(#33),closed 項目會漏列;all 也不能省略。
extra := url.Values{} extra := url.Values{}
if state != "all" { extra.Set("state", state)
extra.Set("state", state) if len(labels) > 0 {
extra.Set("labels", strings.Join(labels, ","))
} }
// type=issues:排除 PR(PR 在此端點帶 pull_request 欄位)。 // type=issues:排除 PR(PR 在此端點帶 pull_request 欄位)。
extra.Set("type", "issues") extra.Set("type", "issues")
@@ -246,10 +253,10 @@ func (o *Ops) ListPulls(ctx context.Context, owner, repo, state string) ([]Pull,
if state == "" { if state == "" {
state = "open" state = "open"
} }
// state 一律明確傳給 API:pulls 端點省略 state 時雖回全部,仍明確
// 帶上,避免依賴端點預設值(#33)。
extra := url.Values{} extra := url.Values{}
if state != "all" { extra.Set("state", state)
extra.Set("state", state)
}
var pulls []Pull var pulls []Pull
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/pulls", gitea.ListOptions{Extra: extra}, &pulls); err != nil { if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/pulls", gitea.ListOptions{Extra: extra}, &pulls); err != nil {
return nil, err return nil, err
@@ -259,12 +266,93 @@ func (o *Ops) ListPulls(ctx context.Context, owner, repo, state string) ([]Pull,
// GetPull 取得單一 PR。 // GetPull 取得單一 PR。
func (o *Ops) GetPull(ctx context.Context, owner, repo string, number int64) (*Pull, error) { func (o *Ops) GetPull(ctx context.Context, owner, repo string, number int64) (*Pull, error) {
var pull Pull var pr Pull
path := repoPath(owner, repo) + "/pulls/" + strconv.FormatInt(number, 10) path := repoPath(owner, repo) + "/pulls/" + strconv.FormatInt(number, 10)
if err := o.Client.GetJSON(ctx, path, &pull); err != nil { if err := o.Client.GetJSON(ctx, path, &pr); err != nil {
return nil, err return nil, err
} }
return &pull, nil return &pr, nil
}
// Review 是 pull request 審核的精簡欄位。
type Review struct {
ID int64 `json:"ID"`
Number int64 `json:"number"`
State string `json:"state"`
Body string `json:"body"`
Submitted string `json:"submitted_at"`
User *User `json:"user"`
}
// Author 回傳審核者帳號。
func (r *Review) Author() string { return r.User.Name() }
// ApprovePull 核准 PR(POST /repos/{owner}/{repo}/pulls/{n}/reviews,event=APPROVED)。
// body 是審核意見,可為空。
func (o *Ops) ApprovePull(ctx context.Context, owner, repo string, number int64, body string) (*Review, error) {
payload := map[string]any{
"event": "APPROVED",
"body": body,
}
var review Review
path := repoPath(owner, repo) + "/pulls/" + strconv.FormatInt(number, 10) + "/reviews"
if err := o.Client.DoJSON(ctx, "POST", path, "", payload, &review); err != nil {
return nil, err
}
return &review, nil
}
// ClosePull 關閉 PR 不合併(PATCH /repos/{owner}/{repo}/pulls/{n},state=closed)。
func (o *Ops) ClosePull(ctx context.Context, owner, repo string, number int64) (*Pull, error) {
payload := map[string]any{"state": "closed"}
var pr Pull
path := repoPath(owner, repo) + "/pulls/" + strconv.FormatInt(number, 10)
if err := o.Client.DoJSON(ctx, "PATCH", path, "", payload, &pr); err != nil {
return nil, err
}
return &pr, nil
}
// HeadInfo 是 PR head 參照的完整資訊(checkout 用:同倉庫分支 or 跨倉庫 clone 網址)。
type HeadInfo struct {
// Ref 是 head 分支名。
Ref string
// Repo 是 head 所屬倉庫(owner/name);與目標倉庫相同時為空。
Repo string
// CloneURL 是 head 倉庫的 https clone 網址;同倉庫時為空。
CloneURL string
// SHA 是 head commit(暫不使用,保留給未來 reset/rebase 用)。
SHA string
}
// PullHeadInfo 取得 PR 的 head 資訊。同倉庫分支 → Repo/CloneURL 為空、只剩 Ref;
// 跨倉庫 fork → Ref+Repo+CloneURL 齊備,checkout 改以 clone --branch Ref CloneURL。
func (o *Ops) PullHeadInfo(ctx context.Context, owner, repo string, number int64) (*HeadInfo, error) {
pr, err := o.GetPull(ctx, owner, repo, number)
if err != nil {
return nil, err
}
info := &HeadInfo{Ref: pr.HeadRef()}
if pr.Head != nil {
info.SHA = pr.Head.SHA
if pr.Head.Repo != nil {
full := pr.Head.Repo.FullName
same := full != "" && full == owner+"/"+repo
if !same {
info.Repo = full
info.CloneURL = pr.Head.Repo.CloneURL
}
}
}
return info, nil
}
// String 依 head 來源輸出人類可讀描述(輸出用)。
func (h *HeadInfo) String() string {
if h.Repo != "" {
return h.Repo + "#" + h.Ref
}
return h.Ref
} }
// CreatePull 建立 PR。 // CreatePull 建立 PR。
@@ -320,10 +408,10 @@ func (o *Ops) ListMilestones(ctx context.Context, owner, repo, state string) ([]
if state == "" { if state == "" {
state = "open" state = "open"
} }
// state 一律明確傳給 API:milestones 端點省略 state 時預設 open
// (#33),closed 項目會漏列。
extra := url.Values{} extra := url.Values{}
if state != "all" { extra.Set("state", state)
extra.Set("state", state)
}
var ms []Milestone var ms []Milestone
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/milestones", gitea.ListOptions{Extra: extra}, &ms); err != nil { if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/milestones", gitea.ListOptions{Extra: extra}, &ms); err != nil {
return nil, err return nil, err
+100
View File
@@ -122,3 +122,103 @@ func (a *APIClient) ListComments(owner, repo string, number int64) ([]Comment, e
} }
return comments, nil return comments, nil
} }
// ── StalledSource 面向(#7 CLI 接線)────────────────────────────────────
// APIClient 在 Client 之外同時實作 StalledSource(Source + CurrentUser +
// GetIssue),讓 stalled/xrefs 命令與既有命令共用同一個 HTTP 用戶端。
// 清單類方法直接委派 Client 同名操作,語義一致(type=issues、state=open)。
// GetIssue 單一 issue 查詢(PR 亦經此端點,帶 pull_request 標記);
// 失敗(含 404)回 *gitea.ErrAPI,由 CLI 映射結束碼 3。
func (a *APIClient) GetIssue(owner, repo string, number int64) (Issue, error) {
var issue Issue
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) +
"/issues/" + strconv.FormatInt(number, 10)
if err := a.Client.GetJSON(context.Background(), path, &issue); err != nil {
return Issue{}, err
}
return issue, nil
}
// TryGetIssue 寬容版單一 issue 查詢:失敗(含 404)回 (零值, false, nil),
// 供 stalled 父追蹤項掃描靜默略過不存在的子項(Source 介面契約)。
func (a *APIClient) TryGetIssue(owner, repo string, number int64) (Issue, bool, error) {
issue, err := a.GetIssue(owner, repo, number)
if err != nil {
return Issue{}, false, nil
}
return issue, true, nil
}
// IssueTimeline 回傳 issue 的 timeline 事件(Source 面向;對應 gitea.py
// _direct_last_activity 拉取的 repos/{o}/{r}/issues/{n}/timeline)。
// 分頁由 ListAll 處理(與 gitea.py api_get_list 的 limit=50 逐頁一致)。
func (a *APIClient) IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error) {
var events []TimelineEvent
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) +
"/issues/" + strconv.FormatInt(number, 10) + "/timeline"
if err := a.Client.ListAll(context.Background(), path, gitea.ListOptions{}, &events); err != nil {
return nil, err
}
return events, nil
}
// MyOrganizations 委派 ListOrgs(Source 面向)。
func (a *APIClient) MyOrganizations() ([]string, error) { return a.ListOrgs() }
// OrganizationRepositories 委派 ListOrgRepos(Source 面向)。
func (a *APIClient) OrganizationRepositories(org string) ([]Repo, error) {
return a.ListOrgRepos(org)
}
// OpenIssues 委派 ListIssues(Source 面向;已排除 PR)。
func (a *APIClient) OpenIssues(owner, repo string) ([]Issue, error) {
return a.ListIssues(owner, repo)
}
// OpenPulls 委派 ListPulls(Source 面向)。
func (a *APIClient) OpenPulls(owner, repo string) ([]PullRequest, error) {
return a.ListPulls(owner, repo)
}
// IssueComments 委派 ListComments(Source 面向)。
func (a *APIClient) IssueComments(owner, repo string, number int64) ([]Comment, error) {
return a.ListComments(owner, repo, number)
}
// ── MilestoneSource 面向(#31 跨倉庫里程碑總覽)────────────────────────
// APIClient 在 StalledSource 之外另實作 MilestoneSource,讓 milestones
// 總覽命令與既有命令共用同一個 HTTP 用戶端;查詢參數對照 gitea.py 的
// list_open_milestones_for_repository/_milestone_open_issues。
// OpenMilestones 回傳倉庫的 open 里程碑(GET /repos/{o}/{r}/milestones?state=open)。
func (a *APIClient) OpenMilestones(owner, repo string) ([]Milestone, error) {
var ms []Milestone
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) + "/milestones"
opts := gitea.ListOptions{Extra: url.Values{"state": {"open"}}}
if err := a.Client.ListAll(context.Background(), path, opts, &ms); err != nil {
return nil, err
}
return ms, nil
}
// MilestoneOpenIssues 回傳掛在指定里程碑(依名稱過濾,Gitea 以
// milestones=<title> 查詢)的 open 條目。刻意**不**帶 type=issues——
// PR 亦屬里程碑條目,保留兩者供覆蓋檢查(同 gitea.py
// _milestone_open_issues;PR 帶 pull_request 標記由 workflow 判別)。
func (a *APIClient) MilestoneOpenIssues(owner, repo, milestoneTitle string) ([]Issue, error) {
var issues []Issue
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) + "/issues"
opts := gitea.ListOptions{Extra: url.Values{
"state": {"open"},
"milestones": {milestoneTitle},
}}
if err := a.Client.ListAll(context.Background(), path, opts, &issues); err != nil {
return nil, err
}
return issues, nil
}
// 編譯期確認 APIClient 同時實作 Client、StalledSource 與 MilestoneSource。
var _ StalledSource = (*APIClient)(nil)
var _ MilestoneSource = (*APIClient)(nil)
+256
View File
@@ -0,0 +1,256 @@
// milestones.go — 跨倉庫里程碑總覽(teai #31;gitea.py milestones 的對應實作)。
//
// 各倉庫 open milestone 概況(管理者巡邏用,agents AGENTS.md 10.1):期限近者
// 在前的排序、逾期判定、未分派條目摘要與活躍度(updated_at 取里程碑本身與
// 其 open 條位的最大值)。判定與輸出規則以 AGENTS.md 為單一來源,行為基準是
// gitea.py 的 list_milestone_overview,本檔只實作、不改義。
package workflow
import (
"fmt"
"sort"
"strconv"
"strings"
"time"
)
// Milestone 是里程碑物件(僅取總覽會用到的欄位)。
// ID 與 DueOn 用指標:Gitea 回 null/缺漏時輸出 null
// (對應 gitea.py milestone.get("id")/get("due_on") 的 None 語義)。
type Milestone struct {
ID *int64 `json:"id"`
Title string `json:"title"`
State string `json:"state"`
DueOn *string `json:"due_on"`
UpdatedAt string `json:"updated_at"`
OpenIssues int64 `json:"open_issues"`
ClosedIssues int64 `json:"closed_issues"`
}
// MilestoneSource 是跨倉庫里程碑總覽需要的資料源(CLI 層以 API 實作;
// 測試注入假資料,與 Source/StalledSource 同模式)。
type MilestoneSource interface {
// MyOrganizations 回傳目前帳號所屬組織清單。
MyOrganizations() ([]string, error)
// OrganizationRepositories 回傳組織的倉庫清單。
OrganizationRepositories(org string) ([]Repo, error)
// OpenMilestones 回傳倉庫的 open 里程碑。
OpenMilestones(owner, repo string) ([]Milestone, error)
// MilestoneOpenIssues 回傳掛在指定里程碑(依名稱過濾)的 open
// issue 與 PR。刻意不設 type 過濾——兩者都保留供覆蓋檢查
//(同 gitea.py _milestone_open_issues 的查詢參數;PR 帶
// pull_request 標記,由本套件判別)。
MilestoneOpenIssues(owner, repo, milestoneTitle string) ([]Issue, error)
}
// UnassignedEntry 是里程碑 open 條目中未分派者的摘要。
type UnassignedEntry struct {
Type string
Number int64
Title string
URL string
// Author 僅 pull 條目輸出(且作者已知時;對應 gitea.py 只在
// _pr_author_username 非空時放 author 鍵)。
Author string
}
// MarshalJSON 輸出鍵集與鍵序與 gitea.py 一致的物件。
func (u UnassignedEntry) MarshalJSON() ([]byte, error) {
var b strings.Builder
b.WriteString(`{"type":`)
writeJSON(&b, u.Type)
b.WriteString(`,"number":`)
fmt.Fprintf(&b, "%d", u.Number)
b.WriteString(`,"title":`)
writeJSON(&b, u.Title)
b.WriteString(`,"url":`)
writeJSON(&b, u.URL)
if u.Author != "" {
b.WriteString(`,"author":`)
writeJSON(&b, u.Author)
}
b.WriteString(`}`)
return []byte(b.String()), nil
}
// MilestoneEntry 是總覽的單筆輸出(欄位對應 gitea.py list_milestone_overview
// 的 dict 鍵序:repo、id、title、url、open_issues、closed_issues、due_on、
// due_hours、overdue、unassigned、updated_at)。
type MilestoneEntry struct {
Repo string
ID *int64
Title string
URL string
OpenIssues int64
ClosedIssues int64
DueOn *string
DueHours *float64
Overdue bool
Unassigned []UnassignedEntry
UpdatedAt *string
}
// MarshalJSON 輸出鍵集與鍵序與 gitea.py 完全一致的物件
// (與 Item/stalled 的做法相同:手寫鍵序,null/浮點格式對齊 Python)。
func (e MilestoneEntry) MarshalJSON() ([]byte, error) {
var b strings.Builder
b.WriteString(`{"repo":`)
writeJSON(&b, e.Repo)
b.WriteString(`,"id":`)
if e.ID != nil {
fmt.Fprintf(&b, "%d", *e.ID)
} else {
b.WriteString("null")
}
b.WriteString(`,"title":`)
writeJSON(&b, e.Title)
b.WriteString(`,"url":`)
writeJSON(&b, e.URL)
b.WriteString(`,"open_issues":`)
fmt.Fprintf(&b, "%d", e.OpenIssues)
b.WriteString(`,"closed_issues":`)
fmt.Fprintf(&b, "%d", e.ClosedIssues)
b.WriteString(`,"due_on":`)
writeJSON(&b, e.DueOn)
b.WriteString(`,"due_hours":`)
if e.DueHours != nil {
// Python round(x, 1) 的 json 輸出是 48.0/10.4(定點一位小數)。
b.WriteString(strconv.FormatFloat(round1(*e.DueHours), 'f', 1, 64))
} else {
b.WriteString("null")
}
b.WriteString(`,"overdue":`)
b.WriteString(strconv.FormatBool(e.Overdue))
b.WriteString(`,"unassigned":`)
writeJSON(&b, e.Unassigned)
b.WriteString(`,"updated_at":`)
writeJSON(&b, e.UpdatedAt)
b.WriteString(`}`)
return []byte(b.String()), nil
}
// MilestoneOverview 收集跨組織各倉庫的 open 里程碑概況,依(due_on,
// 無則視為最遠)由近到遠排序(穩定排序:同 due_on 者保持掃描順序,
// 對應 Python list.sort 的穩定性)。webBase 是站點網址前綴
// (scheme://host),空字串時 url 欄位輸出 ""(同 gitea.py 在
// GITEA_WEB_DOMAIN 缺漏時的行為)。
func MilestoneOverview(src MilestoneSource, webBase string, now time.Time) ([]MilestoneEntry, error) {
orgs, err := src.MyOrganizations()
if err != nil {
return nil, err
}
out := []MilestoneEntry{}
for _, org := range orgs {
repos, err := src.OrganizationRepositories(org)
if err != nil {
return nil, err
}
for _, repo := range repos {
if repo.Name == "" || repo.Empty {
continue
}
ms, err := src.OpenMilestones(org, repo.Name)
if err != nil {
return nil, err
}
for i := range ms {
entry, err := milestoneEntry(src, org, repo.Name, &ms[i], webBase, now)
if err != nil {
return nil, err
}
out = append(out, entry)
}
}
}
// gitea.py 的排序鍵:(due_on is None, due_on or "")——有期限者在前、
// 期限近者在前;無期限者在後。
sort.SliceStable(out, func(a, bb int) bool {
x, y := out[a].DueOn, out[bb].DueOn
if (x == nil) != (y == nil) {
return y == nil
}
if x != nil {
return *x < *y
}
return false
})
return out, nil
}
// milestoneEntry 計算單一里程碑的總覽欄位(對應 gitea.py 迴圈體)。
func milestoneEntry(src MilestoneSource, org, repo string, m *Milestone, webBase string, now time.Time) (MilestoneEntry, error) {
// due_hours/overdue:due_on 缺漏或無法解析 → null/false。
// Python 以未捨入值判定 overdue(round 只作用於輸出),
// 邊界(如 0.04 小時 → overdue=true、due_hours=0.0)保持一致。
var dueHours *float64
overdue := false
if m.DueOn != nil {
if due, ok := parseMoment(*m.DueOn); ok {
raw := now.Sub(due).Hours()
dueHours = &raw
overdue = raw > 0
}
}
openEntries, err := src.MilestoneOpenIssues(org, repo, m.Title)
if err != nil {
return MilestoneEntry{}, err
}
// 未分派條目摘要(assignees 為空者);updated_at 取里程碑本身與
// 各 open 條目 updated_at 的最大值(供巡邏判斷活躍度)。
unassigned := []UnassignedEntry{}
moments := []time.Time{}
if updated, ok := parseMoment(m.UpdatedAt); ok {
moments = append(moments, updated)
}
for i := range openEntries {
entry := &openEntries[i]
if updated, ok := parseMoment(entry.UpdatedAt); ok {
moments = append(moments, updated)
}
if len(AssigneeNames(entry)) > 0 {
continue
}
summary := UnassignedEntry{
Type: "issue",
Number: entry.issueNumber(),
Title: entry.Title,
URL: entry.WebURL(),
}
if entry.PullRequest != nil {
summary.Type = "pull"
if author := entry.User.Name(); author != "" {
summary.Author = author
}
}
unassigned = append(unassigned, summary)
}
var updatedAt *string
if len(moments) > 0 {
s := FormatMoment(maxTime(moments))
updatedAt = &s
}
return MilestoneEntry{
Repo: org + "/" + repo,
ID: m.ID,
Title: m.Title,
URL: milestoneURL(webBase, org, repo, m.ID),
OpenIssues: m.OpenIssues,
ClosedIssues: m.ClosedIssues,
DueOn: m.DueOn,
DueHours: dueHours,
Overdue: overdue,
Unassigned: unassigned,
UpdatedAt: updatedAt,
}, nil
}
// milestoneURL 組里程碑網頁網址;webBase 空或 id 缺漏回 ""
// (對應 gitea.py _milestone_url 的兩個空值條件。Python 原版不做
// URL 跳脫——一般組織/倉庫名皆為安全字元,這裡保持一致以求位元組相容)。
func milestoneURL(webBase, org, repo string, id *int64) string {
if webBase == "" || id == nil {
return ""
}
return strings.TrimRight(webBase, "/") + "/" + org + "/" + repo +
"/milestone/" + strconv.FormatInt(*id, 10)
}
+262
View File
@@ -0,0 +1,262 @@
// milestones_test.go — MilestoneOverview 的單元測試(#31)。
//
// 資料源注入假實作(離線可測);鍵序、null 表示、排序與 overdue
// 判定對照 gitea.py list_milestone_overview 的 Python 語義。
package workflow
import (
"encoding/json"
"strings"
"testing"
"time"
)
// fakeMilestoneSource 以記憶體資料實作 MilestoneSource。
type fakeMilestoneSource struct {
orgs []string
repos map[string][]Repo
milestones map[string][]Milestone
openIssues map[string][]Issue // key: owner/repo?milestone=<title>
}
func (f *fakeMilestoneSource) MyOrganizations() ([]string, error) { return f.orgs, nil }
func (f *fakeMilestoneSource) OrganizationRepositories(org string) ([]Repo, error) {
return f.repos[org], nil
}
func (f *fakeMilestoneSource) OpenMilestones(owner, repo string) ([]Milestone, error) {
return f.milestones[owner+"/"+repo], nil
}
func (f *fakeMilestoneSource) MilestoneOpenIssues(owner, repo, title string) ([]Issue, error) {
return f.openIssues[owner+"/"+repo+"?milestone="+title], nil
}
func msPtr(s string) *string { return &s }
func idPtr(i int64) *int64 { return &i }
// newMilestoneFixture 建構情境:alterminal 兩倉庫、三里程碑
// (teai 有期限將至、agents 有逾期與無期限)。
func newMilestoneFixture() *fakeMilestoneSource {
return &fakeMilestoneSource{
orgs: []string{"alterminal"},
repos: map[string][]Repo{"alterminal": {
{Name: "agents", HasPullRequests: boolPtr(true)},
{Name: "teai", HasPullRequests: boolPtr(true)},
{Name: "empty-repo", Empty: true}, // 空倉庫應跳過
}},
milestones: map[string][]Milestone{
"alterminal/agents": {
{ID: idPtr(7), Title: "MVP", State: "open",
DueOn: msPtr("2026-09-09T00:00:00Z"), UpdatedAt: "2026-09-01T00:00:00Z",
OpenIssues: 3, ClosedIssues: 1},
{ID: idPtr(8), Title: "v1", State: "open",
DueOn: nil, UpdatedAt: "2026-09-02T00:00:00Z",
OpenIssues: 1, ClosedIssues: 0},
},
"alterminal/teai": {
{ID: idPtr(3), Title: "CLI", State: "open",
DueOn: msPtr("2026-09-12T00:00:00Z"), UpdatedAt: "2026-09-05T00:00:00Z",
OpenIssues: 2, ClosedIssues: 5},
},
},
openIssues: map[string][]Issue{
// agents MVP:一個未分派 issue、一個未分派 PR、一個已分派 issue。
"alterminal/agents?milestone=MVP": {
{Number: 31, Title: "總覽命令", State: "open",
UpdatedAt: "2026-09-10T01:00:00Z",
Repository: &Repository{FullName: "alterminal/agents"},
HTMLURL: "https://gitea.alterminal.com/alterminal/agents/issues/31"},
{Number: 32, Title: "文件", State: "open",
UpdatedAt: "2026-09-08T00:00:00Z",
Repository: &Repository{FullName: "alterminal/agents"},
HTMLURL: "https://gitea.alterminal.com/alterminal/agents/pulls/32",
PullRequest: &pullMarker{}, User: &User{UserName: "alex"}},
{Number: 33, Title: "已分派", State: "open",
UpdatedAt: "2026-09-07T00:00:00Z",
Repository: &Repository{FullName: "alterminal/agents"},
HTMLURL: "https://gitea.alterminal.com/alterminal/agents/issues/33",
Assignee: &User{UserName: "queena"}},
},
// agents v1(無期限):條目比里程碑本身新 → updated_at 取條目。
"alterminal/agents?milestone=v1": {
{Number: 40, Title: "無人理", State: "open",
UpdatedAt: "2026-09-09T23:30:00Z",
Repository: &Repository{FullName: "alterminal/agents"},
HTMLURL: "https://gitea.alterminal.com/alterminal/agents/issues/40"},
},
},
}
}
// TestMilestoneOverviewSortAndOverdue 驗證排序(期限近者在前、無期限在後)
// 與 overdue/due_hours 計算。
func TestMilestoneOverviewSortAndOverdue(t *testing.T) {
now := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
entries, err := MilestoneOverview(newMilestoneFixture(), "https://gitea.alterminal.com", now)
if err != nil {
t.Fatalf("MilestoneOverview: %v", err)
}
if len(entries) != 3 {
t.Fatalf("應有 3 筆(空倉庫跳過),得到 %d", len(entries))
}
// 排序:MVP(2026-09-09,已過期)→ CLI(2026-09-12)→ v1(無期限)。
wantOrder := []string{"alterminal/agents#MVP", "alterminal/teai#CLI", "alterminal/agents#v1"}
for i, want := range wantOrder {
got := entries[i].Repo + "#" + entries[i].Title
if got != want {
t.Errorf("第 %d 筆應為 %s,得到 %s", i, want, got)
}
}
// MVP:due 2026-09-09T00:00Z、now 09-10T08:00Z → 32 小時、逾期。
if !entries[0].Overdue {
t.Errorf("MVP 應逾期")
}
if entries[0].DueHours == nil || *entries[0].DueHours != 32.0 {
t.Errorf("MVP due_hours 應 32.0,得到 %v", entries[0].DueHours)
}
// CLI:未到期。
if entries[1].Overdue {
t.Errorf("CLI 不應逾期")
}
// v1:無期限 → null。
if entries[2].DueOn != nil || entries[2].DueHours != nil || entries[2].Overdue {
t.Errorf("v1 無期限應為 null/false,得到 %+v", entries[2])
}
}
// TestMilestoneOverviewUnassigned 驗證未分派條目摘要(issue 無 author、
// pull 帶 author)與 updated_at 取最大值。
func TestMilestoneOverviewUnassigned(t *testing.T) {
now := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
entries, err := MilestoneOverview(newMilestoneFixture(), "https://gitea.alterminal.com", now)
if err != nil {
t.Fatalf("MilestoneOverview: %v", err)
}
var mvp *MilestoneEntry
for i := range entries {
if entries[i].Title == "MVP" {
mvp = &entries[i]
}
}
if mvp == nil {
t.Fatalf("找不到 MVP")
}
// 未分派:#31(issue)、#32(PR, author=alex);#33 已分派不列。
if len(mvp.Unassigned) != 2 {
t.Fatalf("MVP 應有 2 筆未分派,得到 %d:%+v", len(mvp.Unassigned), mvp.Unassigned)
}
if mvp.Unassigned[0].Type != "issue" || mvp.Unassigned[0].Number != 31 {
t.Errorf("第一筆未分派應為 issue #31,得到 %+v", mvp.Unassigned[0])
}
if mvp.Unassigned[1].Type != "pull" || mvp.Unassigned[1].Number != 32 || mvp.Unassigned[1].Author != "alex" {
t.Errorf("第二筆未分派應為 pull #32(author=alex),得到 %+v", mvp.Unassigned[1])
}
// updated_at:max(里程碑 09-01, #31 09-10T01:00Z) → 後者。
if mvp.UpdatedAt == nil || *mvp.UpdatedAt != "2026-09-10T01:00:00+00:00" {
t.Errorf("MVP updated_at 應取條目最大值 2026-09-10T01:00:00+00:00,得到 %v", mvp.UpdatedAt)
}
// url 組法。
if mvp.URL != "https://gitea.alterminal.com/alterminal/agents/milestone/7" {
t.Errorf("MVP url 應為 milestone/7,得到 %s", mvp.URL)
}
}
// TestMilestoneOverviewJSONKeys 驗證 JSON 鍵集與鍵序與 gitea.py 一致,
// 以及 null/陣列空表示(unassigned 空 → [])。
func TestMilestoneOverviewJSONKeys(t *testing.T) {
now := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
entries, err := MilestoneOverview(newMilestoneFixture(), "", now)
if err != nil {
t.Fatalf("MilestoneOverview: %v", err)
}
// v1:無期限、無未分派條目 → due_on/due_hours/updated_at 的 null 表示、
// unassigned=[]、webBase 空 → url=""。
var v1 *MilestoneEntry
for i := range entries {
if entries[i].Title == "v1" {
v1 = &entries[i]
}
}
if v1 == nil {
t.Fatalf("找不到 v1")
}
// 手寫期望 JSON(縮排 2、鍵序照 gitea.py dict 實字序)。
b, err := json.Marshal(v1)
if err != nil {
t.Fatalf("Marshal: %v", err)
}
// 以逐鍵比對為準(MarshalIndent 因自訂 MarshalJSON 不縮排內層)。
var obj map[string]json.RawMessage
if err := json.Unmarshal(b, &obj); err != nil {
t.Fatalf("Unmarshal: %v", err)
}
wantKeys := []string{"repo", "id", "title", "url", "open_issues", "closed_issues",
"due_on", "due_hours", "overdue", "unassigned", "updated_at"}
// 鍵序:json.Unmarshal 到 map 會失序;改檢查原始字串的鍵出現順序。
pos := -1
for _, k := range wantKeys {
i := strings.Index(string(b), `"`+k+`":`)
if i < 0 {
t.Fatalf("輸出缺少鍵 %q:%s", k, b)
}
if i < pos {
t.Fatalf("鍵 %q 順序錯誤:%s", k, b)
}
pos = i
}
for _, kv := range []struct {
key string
want string
}{
{"repo", `"alterminal/agents"`},
{"due_on", `null`},
{"due_hours", `null`},
{"overdue", `false`},
{"url", `""`},
} {
if got := string(obj[kv.key]); got != kv.want {
t.Errorf("%s 應為 %s,得到 %s", kv.key, kv.want, got)
}
}
if !strings.Contains(string(b), `"number":40`) {
t.Errorf("未分派條目應含 number 40:%s", b)
}
// pull 條目的 author 鍵:有作者才輸出(無則不該出現 "author")。
if strings.Contains(string(obj["unassigned"]), `"author"`) {
t.Errorf("issue 條目不應有 author 鍵:%s", obj["unassigned"])
}
}
// TestMilestoneOverviewDueHoursRounding 驗證 due_hours 捨入到一位小數,
// 且 overdue 以未捨入值判定(0.04h → 0.0 但 overdue=true)。
func TestMilestoneOverviewDueHoursRounding(t *testing.T) {
src := &fakeMilestoneSource{
orgs: []string{"alterminal"},
repos: map[string][]Repo{"alterminal": {{Name: "r"}}},
milestones: map[string][]Milestone{
"alterminal/r": {
{ID: idPtr(1), Title: "edge", State: "open",
DueOn: msPtr("2026-09-10T07:57:36Z"), UpdatedAt: "2026-09-10T07:00:00Z"},
},
},
openIssues: map[string][]Issue{},
}
now := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
entries, err := MilestoneOverview(src, "", now)
if err != nil {
t.Fatalf("MilestoneOverview: %v", err)
}
if len(entries) != 1 {
t.Fatalf("應有 1 筆,得到 %d", len(entries))
}
// 144 秒 = 0.04 小時 → round1 → 0.0;未捨入 > 0 → overdue=true。
b, err := json.Marshal(entries[0])
if err != nil {
t.Fatalf("Marshal: %v", err)
}
if !strings.Contains(string(b), `"due_hours":0.0`) {
t.Errorf("due_hours 應捨入為 0.0:%s", b)
}
if !strings.Contains(string(b), `"overdue":true`) {
t.Errorf("overdue 應以未捨入值判定為 true:%s", b)
}
}
+19 -5
View File
@@ -136,7 +136,11 @@ func (s *Scanner) Members(hasWork bool) ([]string, error) {
return out, nil return out, nil
} }
// iterOrgRepos 產出 (org, repoName);空倉庫跳過(沒有內容可掃)。 // iterOrgRepos 產出 (org, repoName)。空倉庫(empty)**不**跳過:Gitea 允許
// 空倉庫持有 open issue(如「初始化項目」型工作),gitea.py 的
// for_all_repositories(list_my_followup_issues/for_all_organizations)
// 掃 issue 時不檢查 empty;只有 PR 掃描(iterOpenPulls)、stalled 與
// milestone overview 才跳過空倉庫。
func (s *Scanner) iterOrgRepos() ([][2]string, error) { func (s *Scanner) iterOrgRepos() ([][2]string, error) {
orgs, err := s.Orgs() orgs, err := s.Orgs()
if err != nil { if err != nil {
@@ -149,7 +153,7 @@ func (s *Scanner) iterOrgRepos() ([][2]string, error) {
return nil, err return nil, err
} }
for _, repo := range repos { for _, repo := range repos {
if repo.Name == "" || repo.Empty { if repo.Name == "" {
continue continue
} }
out = append(out, [2]string{org, repo.Name}) out = append(out, [2]string{org, repo.Name})
@@ -198,6 +202,16 @@ type orgIssue struct {
Issue Issue Issue Issue
} }
// commentsFor 取回 issue/PR 的留言;number 缺漏(0)時直接視為無留言,
// 不打 API(gitea.py 在 number 為 None 時跳過留言檢查的語義——
// 避免拿 0 去 issues/0/comments 觸發 404 中斷整個掃描)。
func (s *Scanner) commentsFor(owner, repo string, number int64) ([]Comment, error) {
if number <= 0 {
return nil, nil
}
return s.Client.ListComments(owner, repo, number)
}
// collectMemberIssues 跨組織收集分派給 members(至少一人)且最後一則留言 // collectMemberIssues 跨組織收集分派給 members(至少一人)且最後一則留言
// 不是 assignee 的 open issues(gitea.py 的 for_all_organizations)。 // 不是 assignee 的 open issues(gitea.py 的 for_all_organizations)。
func (s *Scanner) collectMemberIssues(members []string) ([]orgIssue, error) { func (s *Scanner) collectMemberIssues(members []string) ([]orgIssue, error) {
@@ -217,7 +231,7 @@ func (s *Scanner) collectMemberIssues(members []string) ([]orgIssue, error) {
if !AssigneeOverlaps(issue, members) { if !AssigneeOverlaps(issue, members) {
continue continue
} }
comments, err := s.Client.ListComments(owner, repo, issue.issueNumber()) comments, err := s.commentsFor(owner, repo, issue.issueNumber())
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -275,7 +289,7 @@ func (s *Scanner) Pulls(mine, reviewer bool) ([]PullItem, error) {
for _, rp := range repoPulls { for _, rp := range repoPulls {
for i := range rp.Pulls { for i := range rp.Pulls {
pr := &rp.Pulls[i] pr := &rp.Pulls[i]
comments, err := s.Client.ListComments(rp.Owner, rp.Repo, pr.Number) comments, err := s.commentsFor(rp.Owner, rp.Repo, pr.Number)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -331,7 +345,7 @@ func (s *Scanner) usernamesWithUnfinishedWork(members []string) (map[string]bool
for _, rp := range repoPulls { for _, rp := range repoPulls {
for i := range rp.Pulls { for i := range rp.Pulls {
pr := &rp.Pulls[i] pr := &rp.Pulls[i]
comments, err := s.Client.ListComments(rp.Owner, rp.Repo, pr.Number) comments, err := s.commentsFor(rp.Owner, rp.Repo, pr.Number)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+45
View File
@@ -164,6 +164,51 @@ func TestNextLayerFallbackToIssue(t *testing.T) {
} }
} }
// TestNextPicksIssueInEmptyRepo 回歸測試(#43):空倉庫(empty=true)中
// 分派給目前帳號的 open issue 應被第三層拾取——gitea.py 的
// for_all_repositories 掃 issue 不跳過空倉庫(「初始化項目」型工作)。
func TestNextPicksIssueInEmptyRepo(t *testing.T) {
s, fc := newTestScanner()
fc.repos["alterminal"] = []Repo{
{Name: "teai"},
{Name: "colony-tick-demo", Empty: true},
}
fc.issues["alterminal/colony-tick-demo"] = []Issue{
{
Number: 1, Title: "初始化項目", UpdatedAt: "2026-09-08T00:00:00Z",
Assignees: []User{*mkUser("alex")},
Repository: &Repository{FullName: "alterminal/colony-tick-demo"},
HTMLURL: "https://gitea.alterminal.com/alterminal/colony-tick-demo/issues/1",
},
}
work, err := s.Next()
if err != nil {
t.Fatal(err)
}
if work == nil || work.Type != "issue" || work.Number != 1 || work.Repo != "alterminal/colony-tick-demo" {
t.Errorf("應拾取空倉庫中的 issue #1,得到 %+v", work)
}
}
// TestMineIncludesEmptyRepoIssues 回歸測試(#43):mine 同樣不因倉庫為空而漏列。
func TestMineIncludesEmptyRepoIssues(t *testing.T) {
s, fc := newTestScanner()
fc.repos["alterminal"] = []Repo{
{Name: "teai"},
{Name: "colony-tick-demo", Empty: true},
}
fc.issues["alterminal/colony-tick-demo"] = []Issue{
{Number: 1, Title: "初始化項目", UpdatedAt: "2026-09-08T00:00:00Z", Assignees: []User{*mkUser("alex")}},
}
issues, err := s.Mine()
if err != nil {
t.Fatal(err)
}
if len(issues) != 1 || issues[0].Num() != 1 {
t.Errorf("mine 應列出空倉庫中的 issue #1,得到 %d 件", len(issues))
}
}
func TestNextNone(t *testing.T) { func TestNextNone(t *testing.T) {
s, _ := newTestScanner() s, _ := newTestScanner()
work, err := s.Next() work, err := s.Next()
+334
View File
@@ -0,0 +1,334 @@
// stalled_entry_test.go — RunStalled/ResolveIssueXrefs 高階入口的單元測試
// (#7 CLI 接線;資料源注入假實作,離線可測)。
package workflow
import (
"errors"
"fmt"
"strings"
"testing"
"time"
)
// fakeStalledSource 包 fakeSource 補上 StalledSource 面向。
type fakeStalledSource struct {
*fakeSource
username string
// getIssueErr 模擬 GetIssue 失敗(xrefs 的 404 路徑)。
getIssueErr error
// timeline[owner/repo/number]:issue timeline 事件(無則回空清單,
// 模擬 API 成功但無事件;timelineErr 模擬拉取失敗)。
timeline map[string][]TimelineEvent
timelineErr map[string]error
}
func (f *fakeStalledSource) CurrentUser() (string, error) { return f.username, nil }
func (f *fakeStalledSource) IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error) {
key := fmt.Sprintf("%s/%s/%d", owner, repo, number)
if err := f.timelineErr[key]; err != nil {
return nil, err
}
return f.timeline[key], nil
}
func (f *fakeStalledSource) GetIssue(owner, repo string, number int64) (Issue, error) {
if f.getIssueErr != nil {
return Issue{}, f.getIssueErr
}
i, ok := f.issues[owner+"/"+repo][number]
if !ok {
return Issue{}, &notFoundError{}
}
return i, nil
}
type notFoundError struct{}
func (e *notFoundError) Error() string { return "404" }
// newStalledFixture 建構掃描情境:alterminal 組織兩個倉庫,
// agents#1 是父追蹤項(引用 teai#2),teai#2 有較新留言。
func newStalledFixture() *fakeStalledSource {
return &fakeStalledSource{
fakeSource: &fakeSource{
orgs: []string{"alterminal"},
repos: map[string][]Repo{"alterminal": {
{Name: "agents", HasPullRequests: boolPtr(true)},
{Name: "teai", HasPullRequests: boolPtr(true)},
}},
issues: map[string]map[int64]Issue{
"alterminal/agents": {
1: {Number: 1, Title: "父追蹤項", State: "open",
Body: "子項:teai#2", CreatedAt: iso(-600), UpdatedAt: iso(-600),
Repository: &Repository{FullName: "alterminal/agents"}},
},
"alterminal/teai": {
2: {Number: 2, Title: "子項", State: "open",
CreatedAt: iso(-500), UpdatedAt: iso(-90),
Repository: &Repository{FullName: "alterminal/teai"}},
},
},
pulls: map[string][]PullRequest{},
comments: map[string][]Comment{
"alterminal/teai/2": {
{CreatedAt: iso(-90), User: &User{UserName: "alex"}, Body: "推進中"},
},
},
},
username: "ceo",
}
}
// TestRunStalledParentTracking 驗證 RunStalled:父追蹤項把子項活動
// 計入 last_activity(reason=parent-tracking),且門檻預設與覆寫皆可。
func TestRunStalledParentTracking(t *testing.T) {
src := newStalledFixture()
// 預設 4 小時門檻:子項 90 分鐘前有活動 → 父項 last_activity 同步,
// 未過門檻,清單為空。
items, err := RunStalled(src, 0, at(0))
if err != nil {
t.Fatalf("RunStalled: %v", err)
}
if len(items) != 0 {
t.Fatalf("預設門檻下不應有停滯項,得到 %d 筆", len(items))
}
// 門檻降到 1 小時:父追蹤項 last_activity 取子項活動(-90m)→
// 停滯 1.5h 列入(reason=parent-tracking、附 child_activity);
// 子項 teai#2 本身也停滯 1.5h(no-assignee)。
items, err = RunStalled(src, 1, at(0))
if err != nil {
t.Fatalf("RunStalled: %v", err)
}
if len(items) != 2 {
t.Fatalf("應有兩筆(父追蹤項+子項),得到 %d:%+v", len(items), items)
}
var parent *Item
for i := range items {
if items[i].Number == 1 {
parent = &items[i]
}
}
if parent == nil {
t.Fatalf("找不到 agents#1:%+v", items)
}
if parent.Reason != "parent-tracking" || parent.Repo != "alterminal/agents" {
t.Fatalf("agents#1 應為 parent-tracking,得到 %s(%s)", parent.Reason, parent.Repo)
}
if len(parent.ChildActivity) == 0 {
t.Fatalf("parent-tracking 應附 child_activity")
}
if parent.StalledHours != 1.5 {
t.Fatalf("last_activity 應取子項活動(-90m → 1.5h),得到 %.1f", parent.StalledHours)
}
}
// TestRunStalledNudgeCooldown 驗證催促冷卻:最後留言出自目前帳號
// 且在 24 小時內 → 不列入;冷卻過後再出現。
func TestRunStalledNudgeCooldown(t *testing.T) {
src := newStalledFixture()
setIssueBody(src, "alterminal", "agents", 1, "") // 移除子項引用
src.comments["alterminal/agents/1"] = []Comment{
{CreatedAt: iso(-2), User: &User{UserName: "ceo"}},
}
findOne := func(items []Item) bool {
for _, it := range items {
if it.Repo == "alterminal/agents" && it.Number == 1 {
return true
}
}
return false
}
items, err := RunStalled(src, 1, at(0))
if err != nil {
t.Fatalf("RunStalled: %v", err)
}
if findOne(items) {
t.Fatalf("催促冷卻期內(2 小時前留言)agents#1 不應列入,得到 %+v", items)
}
src.comments["alterminal/agents/1"] = []Comment{
{CreatedAt: iso(-30 * 60), User: &User{UserName: "ceo"}},
}
items, err = RunStalled(src, 1, at(0))
if err != nil {
t.Fatalf("RunStalled: %v", err)
}
if !findOne(items) {
t.Fatalf("冷卻(24h)過後 agents#1 應再出現,得到 %+v", items)
}
}
// TestResolveIssueXrefs 驗證 xrefs 入口:內文與留言的引用解析、
// 去重、出處標記與單段 repo 的存在性邊界。
func TestResolveIssueXrefs(t *testing.T) {
src := newStalledFixture()
setIssueBody(src, "alterminal", "agents", 1, "看 teai#2 與 #7,另見 alterminal/teai#2")
src.comments["alterminal/agents/1"] = []Comment{
{Body: "teai#2 已處理", User: &User{UserName: "alex"}, CreatedAt: iso(-10)},
{Body: "nope#9 不存在", User: &User{UserName: "max"}, CreatedAt: iso(-5)},
}
// fixture 的組織倉庫只有 agents → teai#2 單段不解析(repo 不在
// alterminal 組織清單);補上 teai 倉庫讓單段解析成立。
src.repos["alterminal"] = []Repo{
{Name: "agents", HasPullRequests: boolPtr(true)},
{Name: "teai", HasPullRequests: boolPtr(true)},
}
hits, err := ResolveIssueXrefs(src, "alterminal", "agents", 1)
if err != nil {
t.Fatalf("ResolveIssueXrefs: %v", err)
}
want := []XrefHit{
{Owner: "alterminal", Repo: "teai", Number: 2, Source: "body"},
{Owner: "alterminal", Repo: "agents", Number: 7, Source: "body"},
}
if len(hits) != len(want) {
t.Fatalf("應解析出 %d 筆(留言重複的 teai#2 去重、nope#9 略過),得到 %d:%+v",
len(want), len(hits), hits)
}
for i := range want {
if hits[i] != want[i] {
t.Fatalf("hits[%d] = %+v, want %+v", i, hits[i], want[i])
}
}
}
// TestResolveIssueXrefsCommentSource 驗證出處:僅出現在留言的引用
// 標記為 comment。
func TestResolveIssueXrefsCommentSource(t *testing.T) {
src := newStalledFixture()
setIssueBody(src, "alterminal", "agents", 1, "內文無引用")
src.comments["alterminal/agents/1"] = []Comment{
{Body: "追蹤 #9", User: &User{UserName: "alex"}, CreatedAt: iso(-10)},
}
hits, err := ResolveIssueXrefs(src, "alterminal", "agents", 1)
if err != nil {
t.Fatalf("ResolveIssueXrefs: %v", err)
}
if len(hits) != 1 || hits[0].Source != "comment" || hits[0].Number != 9 {
t.Fatalf("應輸出一筆 source=comment 的 #9,得到 %+v", hits)
}
}
// TestResolveIssueXrefsGetError 驗證 GetIssue 失敗(如 404)層層回傳,
// 由 CLI 映射結束碼。
func TestResolveIssueXrefsGetError(t *testing.T) {
src := newStalledFixture()
src.getIssueErr = &notFoundError{}
if _, err := ResolveIssueXrefs(src, "alterminal", "agents", 1); err == nil {
t.Fatalf("GetIssue 失敗應回傳錯誤")
}
}
func boolPtr(b bool) *bool { return &b }
// setIssueBody 修改 map 內 issue 的內文(map 元素不可定址,需整體重塞)。
func setIssueBody(src *fakeStalledSource, owner, repo string, number int64, body string) {
key := owner + "/" + repo
issue := src.issues[key][number]
issue.Body = body
src.issues[key][number] = issue
}
// TestResolveIssueXrefsEmptyBody 驗證無引用時輸出空(CLI 印 [])。
func TestResolveIssueXrefsEmptyBody(t *testing.T) {
src := newStalledFixture()
setIssueBody(src, "alterminal", "agents", 1, strings.Repeat("無引用內文", 3))
delete(src.comments, "alterminal/agents/1")
hits, err := ResolveIssueXrefs(src, "alterminal", "agents", 1)
if err != nil {
t.Fatalf("ResolveIssueXrefs: %v", err)
}
if len(hits) != 0 {
t.Fatalf("無引用應輸出空清單,得到 %+v", hits)
}
_ = time.Now // time 僅供 iso/at 使用;保留 import。
}
// TestRunStalledChildXrefRefresh 回歸測試(agents #38、teai #34):
// 子項 updated_at 被跨 issue 引用(comment_ref)刷新時,子項有效活動
// 應經 directLastActivity 排除引用事件後採計,父追蹤項的停滯時鐘
// 不被虛假刷新。
func TestRunStalledChildXrefRefresh(t *testing.T) {
src := newStalledFixture()
// 子項 teai#2:直接活動為 created(-500) 與留言(-90),
// updated_at 卻是 -10(他處留言提及刷新)。
issue := src.issues["alterminal/teai"][2]
issue.UpdatedAt = iso(-10)
src.issues["alterminal/teai"][2] = issue
// timeline:-10 的刷新是 comment_ref(引用事件,排除),
// -90 有直接事件(label)可對應 → 有效活動 -90。
src.timeline = map[string][]TimelineEvent{
"alterminal/teai/2": {
{Type: "label", CreatedAt: iso(-90)},
{Type: "comment_ref", CreatedAt: iso(-10)},
},
}
// 門檻 1 小時:父項 last_activity 取子項有效活動 -90 → 停滯 1.5h 列入;
// 若誤採被刷新的 -10,父項與子項都不會列入。
items, err := RunStalled(src, 1, at(0))
if err != nil {
t.Fatalf("RunStalled: %v", err)
}
if len(items) != 2 {
t.Fatalf("應有兩筆(父追蹤項+子項),得到 %d:%+v", len(items), items)
}
var parent *Item
for i := range items {
if items[i].Repo == "alterminal/agents" && items[i].Number == 1 {
parent = &items[i]
}
}
if parent == nil {
t.Fatalf("找不到 agents#1:%+v", items)
}
if parent.Reason != "parent-tracking" {
t.Fatalf("agents#1 應為 parent-tracking,得到 %s", parent.Reason)
}
if parent.StalledHours != 1.5 {
t.Fatalf("父項停滯應以子項有效活動(-90m → 1.5h)計,得到 %.1f", parent.StalledHours)
}
}
// TestRunStalledTimelineAllXrefFallback 回歸測試(agents #40、teai #34):
// issue 自身 updated_at 晚於全部已知直接活動、且 timeline 全為引用事件時,
// 回退已知直接活動的最晚時刻(不高估活動、不低估停滯);
// timeline 拉取失敗則保守沿用 updated_at。
func TestRunStalledTimelineAllXrefFallback(t *testing.T) {
src := newStalledFixture()
setIssueBody(src, "alterminal", "agents", 1, "") // 移除父項引用,teai#2 獨立判定
delete(src.comments, "alterminal/teai/2")
// agents#1 給一則近期留言,避免本身停滯(10h)干擾本測試的斷言。
src.comments["alterminal/agents/1"] = []Comment{
{CreatedAt: iso(-10), User: &User{UserName: "alex"}},
}
// teai#2:僅有 created(-500) 此一已知直接活動,
// updated_at -10 完全由他處提及刷新。
issue := src.issues["alterminal/teai"][2]
issue.UpdatedAt = iso(-10)
src.issues["alterminal/teai"][2] = issue
// 情境一:timeline 全為引用事件 → 回退 knownMax(created -500)
// → 停滯 8.3h,超過預設門檻 4h,列入。
src.timeline = map[string][]TimelineEvent{
"alterminal/teai/2": {{Type: "issue_ref", CreatedAt: iso(-10)}},
}
items, err := RunStalled(src, 0, at(0))
if err != nil {
t.Fatalf("RunStalled: %v", err)
}
if len(items) != 1 || items[0].Number != 2 {
t.Fatalf("全引用事件應回退直接活動 → teai#2 停滯 8.3h 列入,得到 %+v", items)
}
if items[0].StalledHours != 8.3 {
t.Fatalf("回退 created(-500) → 停滯應 8.3h,得到 %.1f", items[0].StalledHours)
}
// 情境二:timeline 拉取失敗 → 保守沿用 updated_at(-10) → 0.2h 未達門檻,不列入。
src.timeline = nil
src.timelineErr = map[string]error{"alterminal/teai/2": errors.New("boom")}
items, err = RunStalled(src, 0, at(0))
if err != nil {
t.Fatalf("RunStalled: %v", err)
}
if len(items) != 0 {
t.Fatalf("timeline 失敗應保守沿用 updated_at → 不列入,得到 %+v", items)
}
}
+24
View File
@@ -3,6 +3,8 @@ package workflow
import ( import (
"encoding/json" "encoding/json"
"regexp" "regexp"
"strings"
"time"
) )
// User 是 Gitea API 的使用者物件(僅取工作流判斷會用到的欄位)。 // User 是 Gitea API 的使用者物件(僅取工作流判斷會用到的欄位)。
@@ -65,6 +67,7 @@ type PRRef struct {
// Comment 是 issue/PR 的討論留言(PR 的留言也走 issues comments 端點)。 // Comment 是 issue/PR 的討論留言(PR 的留言也走 issues comments 端點)。
type Comment struct { type Comment struct {
Body string `json:"body"`
CreatedAt string `json:"created_at"` CreatedAt string `json:"created_at"`
User *User `json:"user"` User *User `json:"user"`
} }
@@ -82,6 +85,9 @@ type Issue struct {
Number int64 `json:"number"` Number int64 `json:"number"`
Index int64 `json:"index"` Index int64 `json:"index"`
Title string `json:"title"` Title string `json:"title"`
State string `json:"state"`
Body string `json:"body"`
ClosedAt string `json:"closed_at"`
HTMLURL string `json:"html_url"` HTMLURL string `json:"html_url"`
URL string `json:"url"` URL string `json:"url"`
UpdatedAt string `json:"updated_at"` UpdatedAt string `json:"updated_at"`
@@ -216,3 +222,21 @@ func (p *PullRequest) FullName() string {
} }
return repoFullNameFromURL(p.WebURL()) return repoFullNameFromURL(p.WebURL())
} }
// parseMoment 對應 gitea.py 的 _parse_iso8601:剖析 ISO8601 字串(Z 後綴、
// 小數秒、時區偏移皆可;無時區視為 UTC),失敗回 (零值, false)。
// 保留原時區偏移、不轉 UTC——Python datetime.isoformat() 會原樣輸出
// 「+08:00」這類偏移,轉了 UTC 輸出就變 +00:00,與基準位元組不相容。
// stalled 掃描的時刻判斷(last_activity、催促冷卻)都以這裡的語義為準。
func parseMoment(value string) (time.Time, bool) {
text := strings.TrimSpace(value)
if text == "" {
return time.Time{}, false
}
for _, layout := range []string{time.RFC3339Nano, time.RFC3339, "2006-01-02T15:04:05", "2006-01-02"} {
if t, err := time.Parse(layout, text); err == nil {
return t, true
}
}
return time.Time{}, false
}
+735
View File
@@ -0,0 +1,735 @@
// 套件 workflow 實作 gitea.py 工作流的核心判定邏輯(teai issue #7)。
//
// 行為基準是 alterminal/agents 的 scripts/lib/gitea.py:xref 解析
// (#N、repo#N、owner/repo#N)與 stalled 停滯掃描(reason 分類、催促冷卻、
// 父追蹤項把子項活動計入 last_activity)。判定規則以 AGENTS.md 為準,
// 本套件只實作、不改義。
//
// 資料以 Source 介面注入:CLI 層負責拉取 API,測試用假資料源,
// 邏輯本身離線可測(README 設計原則 4:可直接替換原型、交叉驗證)。
package workflow
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
)
// 常數與 gitea.py 保持一致(STALLED_DEFAULT_HOURS、NUDGE_COOLDOWN_HOURS)。
const (
// StalledDefaultHours 是 stalled 掃描的預設門檻(小時)。
StalledDefaultHours = 4.0
// NudgeCooldownHours 是「最後留言出自目前帳號」項目的催促冷卻(小時)。
NudgeCooldownHours = 24.0
)
// xrefTimelineTypes 對應 gitea.py 的 XREF_TIMELINE_TYPES:他處留言/issue
// 提及本編號時產生的 timeline 引用事件。這類事件會刷新 updated_at,但不是
// 本 issue 的直接活動,directLastActivity 會予以排除(agents issue #34)。
var xrefTimelineTypes = map[string]bool{"comment_ref": true, "issue_ref": true}
// xrefPattern 對應 gitea.py 的 XREF_PATTERN:#N、repo#N、owner/repo#N。
//
// 前面不得是文數字/底線/斜線(避免切進 alterminal/bear#47 的後半段);
// owner/repo 兩段之間必須有斜線(避免把 bear-cli#10 誤判成 cli#10)。
// Go 的 regexp 不支援 lookbehind,改在掃描時檢查前一字元。
var xrefPattern = regexp.MustCompile(`([A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)?)?#(\d+)`)
// Item 是 stalled 掃描的單筆輸出(欄位對應 gitea.py 的 find_stalled_work)。
type Item struct {
Type string
Repo string
Number int64
Title string
URL string
Assignees []string
Author string
Reviewers []string
LastCommentBy string
LastActivityAt time.Time
StalledHours float64
Reason string
ChildActivity []Child
}
// MarshalJSON 輸出鍵集與鍵序與 gitea.py 完全一致的物件:
// issue 帶 assignees;pull 帶 author 與 reviewers;
// child_activity 僅在有子項摘要時輸出。
func (i Item) MarshalJSON() ([]byte, error) {
var b strings.Builder
b.WriteString(`{"type":`)
writeJSON(&b, i.Type)
b.WriteString(`,"repo":`)
writeJSON(&b, i.Repo)
b.WriteString(`,"number":`)
fmt.Fprintf(&b, "%d", i.Number)
b.WriteString(`,"title":`)
writeJSON(&b, i.Title)
b.WriteString(`,"url":`)
writeJSON(&b, i.URL)
if i.Type == "pull" {
b.WriteString(`,"author":`)
writeJSON(&b, i.Author)
b.WriteString(`,"reviewers":`)
writeJSON(&b, i.Reviewers)
} else {
b.WriteString(`,"assignees":`)
writeJSON(&b, i.Assignees)
}
b.WriteString(`,"last_comment_by":`)
writeJSON(&b, i.LastCommentBy)
b.WriteString(`,"last_activity_at":`)
writeJSON(&b, FormatMoment(i.LastActivityAt))
b.WriteString(`,"stalled_hours":`)
// Python round(x, 1) 的 json 輸出是 48.0/10.4(repr 帶 .0);
// %g 會輸出 48,極大值還會變 1e+06,改定點一位小數。
b.WriteString(strconv.FormatFloat(i.StalledHours, 'f', 1, 64))
b.WriteString(`,"reason":`)
writeJSON(&b, i.Reason)
if len(i.ChildActivity) > 0 {
b.WriteString(`,"child_activity":`)
writeJSON(&b, i.ChildActivity)
}
b.WriteString(`}`)
return []byte(b.String()), nil
}
// FormatMoment 輸出與 Python datetime.isoformat() 一致的時刻字串
// (UTC 以 +00:00 表示,不用 Z;秒以下省略)。
func FormatMoment(t time.Time) string {
if t.Nanosecond() != 0 {
return t.Format("2006-01-02T15:04:05.999999999-07:00")
}
return t.Format("2006-01-02T15:04:05-07:00")
}
// writeJSON 以停用 HTML 轉義的編碼器輸出:Python json.dumps(ensure_ascii=False)
// 不會把 <、>、& 轉成 \u003c 等逸出,json.Marshal 預設會,造成位元組不相容。
// Encoder 會在結尾補換行, trim 掉。
func writeJSON(b *strings.Builder, v any) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return
}
b.Write(bytes.TrimSuffix(buf.Bytes(), []byte{'\n'}))
}
// Child 是父追蹤項的子項活動摘要。
type Child struct {
Repo string `json:"repo"`
Number int64 `json:"number"`
Title string `json:"title"`
State string `json:"state"`
// LastActivityAt 用指標:子項無可解析時刻時 Python 輸出 null(不是 "")。
LastActivityAt *string `json:"last_activity_at"`
}
// XrefTarget 是解析後的引用目標(owner、repo、number)。
type XrefTarget struct {
Owner string
Repo string
Number int64
}
// Source 是 stalled 掃描需要的資料源(CLI 層以 API 實作;測試注入假資料)。
type Source interface {
// MyOrganizations 回傳目前帳號所屬組織清單。
MyOrganizations() ([]string, error)
// OrganizationRepositories 回傳組織的倉庫清單。
OrganizationRepositories(org string) ([]Repo, error)
// OpenIssues 回傳倉庫的 open issues(Gitea 會混入 PR,由掃描端過濾)。
OpenIssues(owner, repo string) ([]Issue, error)
// OpenPulls 回傳倉庫的 open pull requests。
OpenPulls(owner, repo string) ([]PullRequest, error)
// IssueComments 回傳 issue/PR 的留言。
IssueComments(owner, repo string, number int64) ([]Comment, error)
// TryGetIssue 寬容版單一 issue 查詢:失敗(含 404)回 (零值, false, nil)。
TryGetIssue(owner, repo string, number int64) (Issue, bool, error)
// IssueTimeline 回傳 issue 的 timeline 事件(GET /repos/{o}/{r}/issues/{n}/timeline,
// 分頁)。directLastActivity 用來排除跨 issue 引用事件(agents issue #34)。
IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error)
}
// iterXrefs 產出文字中的 (prefix, number) 配對(對應 _iter_issue_xrefs)。
//
// Python 原版以 lookbehind (?<![\w/#]) 在匹配起點檢查前一「字元」,
// 且 \w 採 Unicode(中日韓、全形數字都算)。Go regexp 不支援 lookbehind,
// 改為掃描時檢查起點前一 rune:是文數字(Unicode)/底線/斜線/# 者略過,
// 並從起點的下一個 rune 重試——與 Python finditer 的逐位置語義一致,
// 否則「修復bear-cli#9」這種寫法會整段被丟棄(Python 只匹配後半 cli#9)。
func iterXrefs(text string) [][2]string {
var out [][2]string
pos := 0
for pos <= len(text) {
m := xrefPattern.FindStringIndex(text[pos:])
if m == nil {
break
}
start, end := pos+m[0], pos+m[1]
if start > 0 {
prev, _ := utf8.DecodeLastRuneInString(text[:start])
if isWordChar(prev) || prev == '/' || prev == '#' {
_, size := utf8.DecodeRuneInString(text[start:])
pos = start + size
continue
}
}
match := text[start:end]
i := strings.IndexByte(match, '#')
prefix := match[:i]
number := match[i+1:]
out = append(out, [2]string{prefix, number})
pos = end
}
return out
}
// isWordChar 對應 Python \w(Unicode):字母/數字/底線。
// 前一版只認 ASCII,中文緊鄰 #N 時(「修復#12」)與 Python 行為分歧。
func isWordChar(r rune) bool {
return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
}
// ResolveXrefTargets 把內文/留言中的引用解析成目標清單(對應 _resolve_xref_targets)。
//
// 單段 #N 指向父項所在倉庫;單段 repo#N 需 repo 存在於父項所屬組織
// (「PR#50」這類寫法因 repo 不存在而自動略過);owner/repo#N 需 owner
// 為目前帳號所屬組織(跨倉庫子項,如 bear-cli#9 → bear#35 的同組織判定)。
// 去重、保留出現順序。
func ResolveXrefTargets(org, repo string, texts []string, myOrgs map[string]bool, orgRepos func(org string) ([]string, error)) ([]XrefTarget, error) {
var resolved []XrefTarget
seen := map[XrefTarget]bool{}
var orgRepoSet map[string]bool
for _, text := range texts {
for _, pair := range iterXrefs(text) {
prefix, numberStr := pair[0], pair[1]
var number int64
if _, err := fmt.Sscanf(numberStr, "%d", &number); err != nil || number <= 0 {
continue
}
var target XrefTarget
switch {
case strings.Contains(prefix, "/"):
parts := strings.SplitN(prefix, "/", 2)
owner, name := parts[0], parts[1]
if owner != "" && name != "" && myOrgs[owner] {
target = XrefTarget{owner, name, number}
}
case prefix != "":
if orgRepoSet == nil {
names, err := orgRepos(org)
if err != nil {
return nil, err
}
orgRepoSet = map[string]bool{}
for _, n := range names {
orgRepoSet[n] = true
}
}
if orgRepoSet[prefix] {
target = XrefTarget{org, prefix, number}
}
default:
target = XrefTarget{org, repo, number}
}
if target != (XrefTarget{}) && !seen[target] {
seen[target] = true
resolved = append(resolved, target)
}
}
}
return resolved, nil
}
// childActivity 計算父追蹤項的子項活動(對應 _child_activity)。
//
// 只採計向下引用:子項建立時間需晚於父項(父項內文回指更早的規劃 issue
// 是上行引用,不採計)。資料源失敗(含編號不存在)靜默略過,不影響掃描。
func childActivity(src Source, org, repo string, parent Issue, comments []Comment, myOrgs map[string]bool, orgRepos func(string) ([]string, error)) (moments []time.Time, children []Child) {
texts := []string{parent.Body}
for _, c := range comments {
texts = append(texts, c.Body)
}
targets, err := ResolveXrefTargets(org, repo, texts, myOrgs, orgRepos)
if err != nil {
return nil, nil
}
for _, t := range targets {
child, ok, gerr := src.TryGetIssue(t.Owner, t.Repo, t.Number)
if gerr != nil || !ok {
continue
}
if t.Owner == org && t.Repo == repo && child.issueNumber() == parent.issueNumber() {
continue // 自我引用
}
parentCreated, pcOK := parseMoment(parent.CreatedAt)
childCreated, ccOK := parseMoment(child.CreatedAt)
if pcOK && ccOK && !childCreated.After(parentCreated) {
continue // 上行引用(父項回指更早或同時的 issue);時間未知則不排除
}
// 子項的直接活動:created_at、state 變更(closed_at)、留言(agents #32)。
// 原始 updated_at 不放入已知活動,另經 directLastActivity 核對後採計
//(與 considerIssue/considerPull 對本 issue 自身的處理同構)。
var ms []time.Time
if m, ok := parseMoment(child.CreatedAt); ok {
ms = append(ms, m)
}
if m, ok := parseMoment(child.ClosedAt); ok {
ms = append(ms, m)
}
if cs, cerr := src.IssueComments(t.Owner, t.Repo, t.Number); cerr == nil {
for _, c := range cs {
if m, ok := parseMoment(c.CreatedAt); ok {
ms = append(ms, m)
}
}
}
if childUpdated, ok := parseMoment(child.UpdatedAt); ok {
// 子項 updated_at 可能被 comment_ref/issue_ref 引用事件刷新
//(agents #38):走與本 issue 自身相同的 directLastActivity 排除
// 邏輯(同源判定,不漂移);timeline 失敗時保守沿用 updated_at。
if d, ok := directLastActivity(src, t.Owner, t.Repo, t.Number, childUpdated, true, ms); ok {
ms = append(ms, d)
}
}
var last *string
if len(ms) > 0 {
latest := maxTime(ms)
moments = append(moments, latest)
// 與 Item 相同用 FormatMoment(Python isoformat:UTC 記 +00:00);
// RFC3339 對 UTC 會輸出 Z,與基準不相容。
s := FormatMoment(latest)
last = &s
}
children = append(children, Child{
Repo: t.Owner + "/" + t.Repo,
Number: child.Number,
Title: child.Title,
State: child.State,
LastActivityAt: last,
})
}
return moments, children
}
// TimelineEvent 是 issue timeline 的單一事件(僅取判斷所需欄位;
// 對應 gitea.py _direct_last_activity 讀取的 timeline 物件)。
type TimelineEvent struct {
Type string `json:"type"`
CreatedAt string `json:"created_at"`
}
// directLastActivity 排除跨 issue 引用事件後,本 issue 的最後直接活動時刻
// (對應 gitea.py 的 _direct_last_activity;agents issues #34/#38/#40)。
//
// 他處留言/issue 提及本編號(comment_ref/issue_ref)也會刷新 updated_at,
// 直接採用會虛假刷新停滯時鐘(false negative)並低估 stalled_hours。
// updated_at 不晚於已知直接活動(留言、created_at、#32 納入的子項活動)時,
// updated_at 本身可信,不必多打一次 timeline API;只有 updated_at 晚於全部
// 已知活動時才拉 timeline 核對:排除引用類事件後取最晚事件時刻;若最晚的
// 都是引用事件(本 issue 無直接活動可對應 updated_at),則回退已知直接活動
// 的最晚時刻(agents #40)。timeline 拉取失敗時沿用 updated_at(不中斷掃描、
// 寧可少報不誤報缺失活動)。
func directLastActivity(src Source, org, repo string, number int64, updatedAt time.Time, hasUpdated bool, known []time.Time) (time.Time, bool) {
if !hasUpdated {
return time.Time{}, false
}
var knownMax *time.Time
for i := range known {
if known[i].IsZero() {
continue
}
if knownMax == nil || known[i].After(*knownMax) {
m := known[i]
knownMax = &m
}
}
if knownMax == nil || !updatedAt.After(*knownMax) {
return updatedAt, true
}
timeline, err := src.IssueTimeline(org, repo, number)
if err != nil {
return updatedAt, true
}
var moments []time.Time
for _, e := range timeline {
if xrefTimelineTypes[e.Type] {
continue
}
if m, ok := parseMoment(e.CreatedAt); ok {
moments = append(moments, m)
}
}
if len(moments) == 0 {
// timeline 全為引用事件:updated_at 完全由他處提及刷新,本 issue 沒有
// 可對應的直接活動。回退已知直接活動的最晚時刻,避免把被刷新的
// updated_at 當活動、低估停滯時數(agents #40);連已知活動都沒有時才
// 保守沿用 updated_at(不中斷掃描、寧可少報不誤報缺失活動)。
if knownMax != nil {
return *knownMax, true
}
return updatedAt, true
}
latest := maxTime(moments)
if latest.Before(updatedAt) {
return latest, true
}
return updatedAt, true
}
func maxTime(ts []time.Time) time.Time {
best := ts[0]
for _, t := range ts[1:] {
if t.After(best) {
best = t
}
}
return best
}
// ScanStalled 掃描跨組織的停滯 open issues/PR(對應 find_stalled_work)。
//
// 判定:最後活動(留言時間與本身 updated_at 取較晚者,父追蹤項再加計
// 子項活動)距今超過 threshold 小時。刻意包含拾取死角形態:最後一則留言
// 出自 assignee/PR 作者本人且超過時限——工作休眠、無人催促。最後留言
// 出自目前帳號(username)的項目在冷卻期間不列入(已催促過);冷卻後
// 仍停滯會再出現。輸出依停滯時間由長到短排序。
func ScanStalled(src Source, username string, threshold float64, now time.Time) ([]Item, error) {
orgs, err := src.MyOrganizations()
if err != nil {
return nil, err
}
myOrgs := make(map[string]bool, len(orgs))
for _, o := range orgs {
myOrgs[o] = true
}
orgRepos := func(org string) ([]string, error) {
repos, err := src.OrganizationRepositories(org)
if err != nil {
return nil, err
}
names := make([]string, 0, len(repos))
for _, r := range repos {
if r.Name != "" {
names = append(names, r.Name)
}
}
return names, nil
}
var items []Item
for _, org := range orgs {
repos, err := src.OrganizationRepositories(org)
if err != nil {
continue
}
for _, r := range repos {
if r.Name == "" || r.Empty {
continue
}
// 停用 PR 的倉庫沒有 PR 可掃;issues 照常(gitea.py _iter_open_issues 不檢查此欄位)。
scanPulls := r.HasPullRequests == nil || *r.HasPullRequests
issues, err := src.OpenIssues(org, r.Name)
if err != nil {
continue
}
for _, issue := range issues {
if issue.PullRequest != nil {
continue
}
comments, err := src.IssueComments(org, r.Name, issue.Number)
if err != nil {
continue
}
item, ok := considerIssue(src, org, r.Name, issue, comments, username, threshold, now, myOrgs, orgRepos)
if ok {
items = append(items, item)
}
}
if !scanPulls {
continue
}
pulls, err := src.OpenPulls(org, r.Name)
if err != nil {
continue
}
for _, pr := range pulls {
comments, err := src.IssueComments(org, r.Name, pr.Number)
if err != nil {
continue
}
if item, ok := considerPull(src, org, r.Name, pr, comments, username, threshold, now); ok {
items = append(items, item)
}
}
}
}
sort.SliceStable(items, func(i, j int) bool {
return items[i].StalledHours > items[j].StalledHours
})
return items, nil
}
// considerIssue 對單一 issue 套用停滯判定(對應 _consider 的 issue 分支)。
func considerIssue(src Source, org, repo string, issue Issue, comments []Comment, username string, threshold float64, now time.Time, myOrgs map[string]bool, orgRepos func(string) ([]string, error)) (Item, bool) {
childMoments, children := childActivity(src, org, repo, issue, comments, myOrgs, orgRepos)
assignees := AssigneeNames(&issue)
// 已知直接活動:留言、created_at、#32 納入的子項活動。
var known []time.Time
if m, ok := parseMoment(issue.CreatedAt); ok {
known = append(known, m)
}
for _, c := range comments {
if m, ok := parseMoment(c.CreatedAt); ok {
known = append(known, m)
}
}
known = append(known, childMoments...)
// 跨 issue 引用(comment_ref/issue_ref)也會刷新 updated_at(agents #34):
// updated_at 晚於全部已知直接活動時,先排除引用事件核對後才採用,
// 避免停滯時鐘被虛假刷新或低估 stalled_hours。
var moments []time.Time
if m, ok := parseMoment(issue.UpdatedAt); ok {
if d, ok2 := directLastActivity(src, org, repo, issue.issueNumber(), m, ok, known); ok2 {
moments = append(moments, d)
}
}
moments = append(moments, known...)
if len(moments) == 0 {
return Item{}, false
}
lastActivity := maxTime(moments)
stalled := now.Sub(lastActivity).Hours()
if stalled < threshold {
return Item{}, false
}
last := LastComment(comments)
lastCommentBy := ""
if last != nil {
lastCommentBy = last.Author()
}
if lastCommentBy == username {
if m, ok := parseMoment(last.CreatedAt); ok && now.Sub(m).Hours() < NudgeCooldownHours {
return Item{}, false
}
}
reason := "waiting-outside"
switch {
case len(assignees) == 0:
reason = "no-assignee"
case lastCommentBy != "" && containsString(assignees, lastCommentBy):
reason = "assignee-idle"
case lastCommentBy == "":
reason = "no-commenter"
}
if len(children) > 0 && anyOpen(children) {
reason = "parent-tracking"
}
item := Item{
Type: "issue", Repo: issue.FullName(), Number: issue.issueNumber(),
Title: issue.Title, URL: issue.WebURL(),
Assignees: assignees,
LastCommentBy: lastCommentBy, LastActivityAt: lastActivity,
StalledHours: round1(stalled), Reason: reason,
}
if len(children) > 0 {
item.ChildActivity = children
}
return item, true
}
// considerPull 對單一 PR 套用停滯判定(對應 _consider 的 pull 分支)。
func considerPull(src Source, org, repo string, pr PullRequest, comments []Comment, username string, threshold float64, now time.Time) (Item, bool) {
reviewers := ReviewerNames(&pr)
author := pr.Author()
// 已知直接活動:留言、created_at。
var known []time.Time
if m, ok := parseMoment(pr.CreatedAt); ok {
known = append(known, m)
}
for _, c := range comments {
if m, ok := parseMoment(c.CreatedAt); ok {
known = append(known, m)
}
}
// 跨 issue 引用也會刷新 PR 的 updated_at(agents #34):與 issue 同一道
// directLastActivity 排除邏輯(同源判定,不漂移)。
var moments []time.Time
if m, ok := parseMoment(pr.UpdatedAt); ok {
if d, ok2 := directLastActivity(src, org, repo, pr.Number, m, ok, known); ok2 {
moments = append(moments, d)
}
}
moments = append(moments, known...)
if len(moments) == 0 {
return Item{}, false
}
lastActivity := maxTime(moments)
stalled := now.Sub(lastActivity).Hours()
if stalled < threshold {
return Item{}, false
}
last := LastComment(comments)
lastCommentBy := ""
if last != nil {
lastCommentBy = last.Author()
}
if lastCommentBy == username {
if m, ok := parseMoment(last.CreatedAt); ok && now.Sub(m).Hours() < NudgeCooldownHours {
return Item{}, false
}
}
reason := "no-commenter"
switch {
case len(reviewers) == 0:
reason = "no-reviewer"
case lastCommentBy == author:
reason = "author-idle"
case lastCommentBy != "" && containsString(reviewers, lastCommentBy):
reason = "reviewer-idle"
}
item := Item{
Type: "pull", Repo: pr.FullName(), Number: pr.Number,
Title: pr.Title, URL: pr.WebURL(),
Author: author, Reviewers: reviewers,
LastCommentBy: lastCommentBy, LastActivityAt: lastActivity,
StalledHours: round1(stalled), Reason: reason,
}
return item, true
}
func anyOpen(children []Child) bool {
for _, c := range children {
if c.State == "open" {
return true
}
}
return false
}
// round1 舍入到小數一位(對應 Python round(x, 1))。
// 經 strconv 的十進位正確舍入(半偶數),與 Python 的浮點 round 行為一致,
// 避免 (x*10+0.5) 截斷在 .x5 邊界產生偏差。
func round1(v float64) float64 {
r, err := strconv.ParseFloat(strconv.FormatFloat(v, 'f', 1, 64), 64)
if err != nil {
return v
}
return r
}
// ── CLI 接線用的高階入口(#7:teai stalled/teai xrefs)─────────────────
// StalledSource 是 stalled/xrefs 命令需要的完整資料源:
// Source(掃描用讀取)加上目前帳號與單一 issue 查詢。
// APIClient(giteaapi.go)實作此介面;測試以假資料源注入。
type StalledSource interface {
Source
// CurrentUser 回傳目前帳號名(催促冷卻判定用)。
CurrentUser() (string, error)
// GetIssue 嚴格版單一 issue/PR 查詢;失敗回錯誤(xrefs 命令用,
// 404 應回 ErrAPI 由 CLI 映射結束碼 3)。
GetIssue(owner, repo string, number int64) (Issue, error)
}
// RunStalled 是 teai stalled 的核心:解析目前帳號後跑 ScanStalled。
// hours <= 0 時採 StalledDefaultHours(對應 gitea.py stalled [--hours N]
// 的預設 4 小時);旗標層已先攔下非正數,這裡是防禦。
func RunStalled(src StalledSource, hours float64, now time.Time) ([]Item, error) {
if hours <= 0 {
hours = StalledDefaultHours
}
username, err := src.CurrentUser()
if err != nil {
return nil, err
}
return ScanStalled(src, username, hours, now)
}
// XrefHit 是 teai xrefs 的單筆輸出:解析後的目標加上出處
// (README 規格:"body"=內文、"comment"=留言)。
type XrefHit struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
Number int64 `json:"number"`
Source string `json:"source"`
}
// ResolveIssueXrefs 是 teai xrefs 的核心:取回單一 issue/PR 的內文與
// 全部留言,解析其中的 #N、repo#N、owner/repo#N 引用(規則同
// ResolveXrefTargets:單段 repo 僅在父項所屬組織有該倉庫時解析、
// owner/repo#N 僅在 owner 為所屬組織時解析),去重並保留出現順序,
// 每筆附首次出現的出處(內文先於留言)。stalled 的父追蹤項判定
// 內部用同一套解析,不重複實作。
func ResolveIssueXrefs(src StalledSource, owner, repo string, number int64) ([]XrefHit, error) {
issue, err := src.GetIssue(owner, repo, number)
if err != nil {
return nil, err
}
comments, err := src.IssueComments(owner, repo, number)
if err != nil {
return nil, err
}
orgs, err := src.MyOrganizations()
if err != nil {
return nil, err
}
myOrgs := make(map[string]bool, len(orgs))
for _, o := range orgs {
myOrgs[o] = true
}
// 組織倉庫清單跨呼叫快取,避免逐則留言重打 API。
orgRepoCache := map[string][]string{}
orgRepos := func(org string) ([]string, error) {
if names, ok := orgRepoCache[org]; ok {
return names, nil
}
repos, err := src.OrganizationRepositories(org)
if err != nil {
return nil, err
}
names := make([]string, 0, len(repos))
for _, r := range repos {
if r.Name != "" {
names = append(names, r.Name)
}
}
orgRepoCache[org] = names
return names, nil
}
type sourceText struct {
text string
source string
}
texts := []sourceText{{issue.Body, "body"}}
for _, c := range comments {
texts = append(texts, sourceText{c.Body, "comment"})
}
var hits []XrefHit
seen := map[XrefTarget]bool{}
for _, t := range texts {
targets, err := ResolveXrefTargets(owner, repo, []string{t.text}, myOrgs, orgRepos)
if err != nil {
return nil, err
}
for _, target := range targets {
if seen[target] {
continue
}
seen[target] = true
hits = append(hits, XrefHit{
Owner: target.Owner, Repo: target.Repo,
Number: target.Number, Source: t.source,
})
}
}
return hits, nil
}
+554
View File
@@ -0,0 +1,554 @@
// workflow 套件的單元測試(teai issue #7 驗收:xref 邊界案例與 stalled 判定)。
//
// fakeSource 以假資料實作 Source 介面,邏輯離線可測;
// 語義對照組是 alterminal/agents scripts/lib/gitea.py。
package workflow
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"testing"
"time"
)
func at(minutes int) time.Time {
return time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC).Add(time.Duration(minutes) * time.Minute)
}
// fakeSource 是注入假資料的 Source。
type fakeSource struct {
orgs []string
repos map[string][]Repo
// issues[owner/repo][number]
issues map[string]map[int64]Issue
// pulls[owner/repo]
pulls map[string][]PullRequest
// comments[owner/repo/number]
comments map[string][]Comment
// timelines[owner/repo/number]:issue timeline 事件(nil → 空 timeline)。
timelines map[string][]TimelineEvent
}
func (f *fakeSource) MyOrganizations() ([]string, error) { return f.orgs, nil }
func (f *fakeSource) OrganizationRepositories(org string) ([]Repo, error) {
return f.repos[org], nil
}
func (f *fakeSource) OpenIssues(owner, repo string) ([]Issue, error) {
var out []Issue
for _, i := range f.issues[owner+"/"+repo] {
out = append(out, i)
}
// 對齊真實 API:issues 依 id(=number)遞增回傳,消除 map 迭代隨機性。
sort.Slice(out, func(a, b int) bool { return out[a].Number < out[b].Number })
return out, nil
}
func (f *fakeSource) OpenPulls(owner, repo string) ([]PullRequest, error) {
return f.pulls[owner+"/"+repo], nil
}
func (f *fakeSource) IssueComments(owner, repo string, number int64) ([]Comment, error) {
return f.comments[fmt.Sprintf("%s/%s/%d", owner, repo, number)], nil
}
func (f *fakeSource) IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error) {
return f.timelines[fmt.Sprintf("%s/%s/%d", owner, repo, number)], nil
}
func (f *fakeSource) TryGetIssue(owner, repo string, number int64) (Issue, bool, error) {
i, ok := f.issues[owner+"/"+repo][number]
if !ok {
return Issue{}, false, nil
}
return i, true, nil
}
func repoWith(name string, hasPR bool) []Repo {
h := hasPR
return []Repo{{Name: name, HasPullRequests: &h}}
}
// iso 把相對分鐘轉成 parseMoment 可剖析的 ISO8601 字串(假資料用)。
func iso(minutes int) string { return FormatMoment(at(minutes)) }
func mustResolve(t *testing.T, org, repo string, texts []string, myOrgs map[string]bool, orgRepos func(string) ([]string, error)) []XrefTarget {
t.Helper()
targets, err := ResolveXrefTargets(org, repo, texts, myOrgs, orgRepos)
if err != nil {
t.Fatalf("ResolveXrefTargets: %v", err)
}
return targets
}
// TestIterXrefsEdges 驗證 regex 邊界:lookbehind 等價實作與兩段式斜線限制。
func TestIterXrefsEdges(t *testing.T) {
cases := []struct {
name string
text string
want [][2]string
}{
{"單段 #N", "父項:#3。", [][2]string{{"3"}, {"", "3"}}[1:]},
{"單段 repo#N 存在", "見 agents#10", [][2]string{{"agents", "10"}}},
{"PR#50 寫法不是 repo", "PR#50 與 issue#49", [][2]string{{"PR", "50"}, {"issue", "49"}}},
{"owner/repo#N", "alterminal/agents#32", [][2]string{{"alterminal/agents", "32"}}},
{"斜線後不切半段", "alterminal/bear#47 只應匹配整段", [][2]string{{"alterminal/bear", "47"}}},
{"連字號 repo 名", "bear-cli#9", [][2]string{{"bear-cli", "9"}}},
{"路徑後的 #N 不匹配", "see https://x/a/#frag not #5", [][2]string{{"", "5"}}},
// Python \w 是 Unicode:CJK 緊鄰 #N 時整體視為 \w,lookbehind 擋下。
{"CJK 緊鄰 #N 略過", "修復#12的問題,見 #5", [][2]string{{"", "5"}}},
{"CJK 緊鄰 repo#N 整段略過", "修復agents#12", nil},
{"CJK 緊鄰連字號 repo 匹配後半", "修復bear-cli#9 見 #5", [][2]string{{"cli", "9"}, {"", "5"}}},
{"連續井號", "##5", nil},
{"全形數字後 #N", "12#5", nil},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := iterXrefs(tc.text)
if len(got) != len(tc.want) {
t.Fatalf("iterXrefs(%q) = %v, want %v", tc.text, got, tc.want)
}
for i := range got {
if got[i] != tc.want[i] {
t.Fatalf("iterXrefs(%q)[%d] = %v, want %v", tc.text, i, got[i], tc.want[i])
}
}
})
}
}
// TestResolveXrefTargets 驗證三種形態的解析與單段 repo 的存在性邊界(#7 驗收)。
func TestResolveXrefTargets(t *testing.T) {
myOrgs := map[string]bool{"alterminal": true}
orgRepos := func(string) ([]string, error) { return []string{"agents", "teai", "bear-cli"}, nil }
texts := []string{"父項:#3,子項 teai#7,跨倉 alterminal/bear#35,不存在 nope#9,PR#50"}
got := mustResolve(t, "alterminal", "agents", texts, myOrgs, orgRepos)
want := []XrefTarget{
{Owner: "alterminal", Repo: "agents", Number: 3},
{Owner: "alterminal", Repo: "teai", Number: 7},
{Owner: "alterminal", Repo: "bear", Number: 35},
}
if len(got) != len(want) {
t.Fatalf("got %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("got[%d] %v, want %v", i, got[i], want[i])
}
}
}
// TestResolveXrefTargetsOwnerNotMyOrg owner/repo#N 的 owner 非所屬組織 → 不解析。
func TestResolveXrefTargetsOwnerNotMyOrg(t *testing.T) {
myOrgs := map[string]bool{"alterminal": true}
orgRepos := func(string) ([]string, error) { return nil, nil }
got := mustResolve(t, "alterminal", "agents", []string{"other/repo#1"}, myOrgs, orgRepos)
if len(got) != 0 {
t.Fatalf("owner 非所屬組織應略過,got %v", got)
}
}
// TestResolveXrefTargetsDedup 同一目標重複出現只保留第一個。
func TestResolveXrefTargetsDedup(t *testing.T) {
myOrgs := map[string]bool{"alterminal": true}
orgRepos := func(string) ([]string, error) { return []string{"teai"}, nil }
got := mustResolve(t, "alterminal", "agents", []string{"#7 又 teai#7"}, myOrgs, orgRepos)
if len(got) != 2 {
t.Fatalf("應兩筆(#7 同倉庫、teai#7 跨倉庫),got %v", got)
}
}
// TestScanStalledIssueReasons 驗證 issue 的 reason 分類與排序。
func TestScanStalledIssueReasons(t *testing.T) {
now := at(0)
src := &fakeSource{
orgs: []string{"alterminal"},
repos: map[string][]Repo{
"alterminal": repoWith("agents", true),
},
issues: map[string]map[int64]Issue{
"alterminal/agents": {
1: {Number: 1, Title: "無分派者", State: "open", CreatedAt: iso(-600), UpdatedAt: iso(-600), Repository: &Repository{FullName: "alterminal/agents"}, URL: "u1"},
2: {Number: 2, Title: "分派者自己最後留言", State: "open", User: &User{UserName: "ceo"}, CreatedAt: iso(-600), UpdatedAt: iso(-300), Assignees: []User{{UserName: "ceo"}}, Repository: &Repository{FullName: "alterminal/agents"}, URL: "u2"},
3: {Number: 3, Title: "無留言", State: "open", CreatedAt: iso(-600), UpdatedAt: iso(-300), Assignees: []User{{UserName: "ceo"}}, Repository: &Repository{FullName: "alterminal/agents"}, URL: "u3"},
4: {Number: 4, Title: "等外部回應", State: "open", CreatedAt: iso(-600), UpdatedAt: iso(-300), Assignees: []User{{UserName: "ceo"}}, Repository: &Repository{FullName: "alterminal/agents"}, URL: "u4"},
5: {Number: 5, Title: "太新不在門檻內", State: "open", CreatedAt: iso(-30), UpdatedAt: iso(-30), Assignees: []User{{UserName: "ceo"}}, Repository: &Repository{FullName: "alterminal/agents"}, URL: "u5"},
},
},
comments: map[string][]Comment{
"alterminal/agents/2": {{User: &User{UserName: "ceo"}, CreatedAt: iso(-300)}},
"alterminal/agents/4": {{User: &User{UserName: "dan"}, CreatedAt: iso(-300)}},
},
}
got, err := ScanStalled(src, "admin", 4.0, now)
if err != nil {
t.Fatalf("ScanStalled: %v", err)
}
// 1: no-assignee(10h)、2: assignee-idle(5h)、3: no-commenter(5h)、4: waiting-outside(5h)、5: 不列入
if len(got) != 4 {
t.Fatalf("應 4 筆,got %d:%v", len(got), got)
}
byNumber := map[int64]Item{}
for _, it := range got {
byNumber[it.Number] = it
}
for n, wantReason := range map[int64]string{1: "no-assignee", 2: "assignee-idle", 3: "no-commenter", 4: "waiting-outside"} {
if byNumber[n].Reason != wantReason {
t.Errorf("issue %d reason = %q, want %q", n, byNumber[n].Reason, wantReason)
}
}
if got[0].Number != 1 || got[0].StalledHours != 10 {
t.Errorf("排序應由長到短,首筆 issue 1(10h),got %v", got[0])
}
if byNumber[2].LastCommentBy != "ceo" {
t.Errorf("issue 2 last_comment_by 應為 ceo,got %q", byNumber[2].LastCommentBy)
}
}
// TestScanStalledNudgeCooldown 最後留言出自掃描者本人 → 24 小時內冷卻不列入。
func TestScanStalledNudgeCooldown(t *testing.T) {
now := at(0)
src := &fakeSource{
orgs: []string{"alterminal"},
repos: map[string][]Repo{"alterminal": repoWith("agents", true)},
issues: map[string]map[int64]Issue{
"alterminal/agents": {
1: {Number: 1, State: "open", CreatedAt: iso(-600), UpdatedAt: iso(-600), Assignees: []User{{UserName: "max"}}, Repository: &Repository{FullName: "alterminal/agents"}},
},
},
comments: map[string][]Comment{
// admin(掃描者)10 小時前催促過 → 冷卻中,不列入。
"alterminal/agents/1": {{User: &User{UserName: "admin"}, CreatedAt: iso(-600)}},
},
}
got, err := ScanStalled(src, "admin", 4.0, now)
if err != nil {
t.Fatalf("ScanStalled: %v", err)
}
if len(got) != 0 {
t.Fatalf("催促冷卻中的項目不應列入,got %v", got)
}
// 冷卻過了(25 小時前催促)→ 重新列入。
src.comments["alterminal/agents/1"] = []Comment{{User: &User{UserName: "admin"}, CreatedAt: iso(-1500)}}
got, err = ScanStalled(src, "admin", 4.0, now)
if err != nil {
t.Fatalf("ScanStalled: %v", err)
}
if len(got) != 1 || got[0].Reason != "waiting-outside" {
t.Fatalf("冷卻後應重新列入,got %v", got)
}
}
// TestScanStalledParentTracking 父追蹤項:子項活動計入 last_activity、reason 標記。
func TestScanStalledParentTracking(t *testing.T) {
now := at(0)
// 父項與子項都 5 小時沒動:父項 last_activity 計入子項活動後同為 5h,
// 應以 parent-tracking 列入並附子項摘要;子項本身則是 assignee-idle。
src := &fakeSource{
orgs: []string{"alterminal"},
repos: map[string][]Repo{"alterminal": repoWith("teai", true)},
issues: map[string]map[int64]Issue{
"alterminal/teai": {
3: {Number: 3, Title: "父", State: "open", Body: "子項:#7", CreatedAt: iso(-700), UpdatedAt: iso(-300), Assignees: []User{{UserName: "ceo"}}, Repository: &Repository{FullName: "alterminal/teai"}},
7: {Number: 7, Title: "子", State: "open", CreatedAt: iso(-650), UpdatedAt: iso(-300), Assignees: []User{{UserName: "max"}}, Repository: &Repository{FullName: "alterminal/teai"}},
},
},
comments: map[string][]Comment{
"alterminal/teai/7": {{User: &User{UserName: "max"}, CreatedAt: iso(-300)}},
},
}
got, err := ScanStalled(src, "admin", 4.0, now)
if err != nil {
t.Fatalf("ScanStalled: %v", err)
}
var parent3, child7 *Item
for i := range got {
switch got[i].Number {
case 3:
parent3 = &got[i]
case 7:
child7 = &got[i]
}
}
if child7 == nil {
t.Fatalf("子項 7 應列入(5h 無活動),got %v", got)
}
if child7.Reason != "assignee-idle" {
t.Errorf("子項 7 reason = %q, want assignee-idle", child7.Reason)
}
if parent3 == nil {
t.Fatalf("父項 3 應列入,got %v", got)
}
if parent3.Reason != "parent-tracking" {
t.Errorf("父項 3 reason = %q, want parent-tracking", parent3.Reason)
}
if len(parent3.ChildActivity) != 1 || parent3.ChildActivity[0].Number != 7 {
t.Errorf("父項 3 應附子項摘要,got %v", parent3.ChildActivity)
}
if parent3.StalledHours != 5 {
t.Errorf("父項 3 stalled_hours = %v, want 5", parent3.StalledHours)
}
// 子項 1 小時前恢復活動 → 父項 last_activity 跟著更新,未達門檻不列入;
// 子項本身也不停滯。整份輸出應為空。
child := src.issues["alterminal/teai"][7]
child.UpdatedAt = iso(-60)
src.issues["alterminal/teai"][7] = child
src.comments["alterminal/teai/7"] = []Comment{{User: &User{UserName: "max"}, CreatedAt: iso(-60)}}
got, err = ScanStalled(src, "admin", 4.0, now)
if err != nil {
t.Fatalf("ScanStalled: %v", err)
}
if len(got) != 0 {
t.Fatalf("子項推進中 → 父項不應誤報停滯,got %v", got)
}
}
// TestScanStalledParentTrackingNotChild 上行引用:引用對象早於父項 → 非子項,不採計。
func TestScanStalledParentTrackingNotChild(t *testing.T) {
now := at(0)
src := &fakeSource{
orgs: []string{"alterminal"},
repos: map[string][]Repo{"alterminal": repoWith("teai", true)},
issues: map[string]map[int64]Issue{
"alterminal/teai": {
47: {Number: 47, State: "open", Body: "規劃見 #39(更早)", CreatedAt: iso(-700), UpdatedAt: iso(-600), Assignees: []User{{UserName: "ceo"}}, Repository: &Repository{FullName: "alterminal/teai"}},
39: {Number: 39, State: "open", CreatedAt: iso(-2000), UpdatedAt: iso(-60), Repository: &Repository{FullName: "alterminal/teai"}},
},
},
}
// timeline:#47 的 updated_at 對應直接事件(assignees)、#39 對應 label
//(agents #34 後 updated_at 需經 timeline 核對才採計;直接事件可對應 → 採用)。
// 必須在 ScanStalled 之前設定——掃描當下讀不到的事後修改無效。
src.timelines = map[string][]TimelineEvent{
"alterminal/teai/47": {{Type: "assignees", CreatedAt: iso(-600)}},
"alterminal/teai/39": {{Type: "label", CreatedAt: iso(-60)}},
}
got, err := ScanStalled(src, "admin", 4.0, now)
if err != nil {
t.Fatalf("ScanStalled: %v", err)
}
// #39 是上行引用,不採計 → 父項 47 停滯 10h(assignee-idle:ceo 分派、無留言)→ no-commenter。
var n47 *Item
for i := range got {
if got[i].Number == 47 {
n47 = &got[i]
}
}
if n47 == nil {
t.Fatalf("上行引用不採計 → 47 應停滯列入,got %v", got)
}
if n47.Reason != "no-commenter" {
t.Errorf("47 reason = %q, want no-commenter", n47.Reason)
}
if len(n47.ChildActivity) != 0 {
t.Errorf("上行引用不應產生子項摘要,got %v", n47.ChildActivity)
}
// #39 本身 updated 1 小時前 → 不列入。
for _, it := range got {
if it.Number == 39 {
t.Errorf("39 未達門檻不應列入:%v", it)
}
}
}
// TestScanStalledPullReasons 驗證 PR 的 reason 分類。
func TestScanStalledPullReasons(t *testing.T) {
now := at(0)
h := true
src := &fakeSource{
orgs: []string{"alterminal"},
repos: map[string][]Repo{"alterminal": {{Name: "teai", HasPullRequests: &h}}},
pulls: map[string][]PullRequest{
"alterminal/teai": {
{Number: 10, User: &User{UserName: "max"}, CreatedAt: iso(-600), UpdatedAt: iso(-600)},
{Number: 11, User: &User{UserName: "max"}, CreatedAt: iso(-600), UpdatedAt: iso(-300), RequestedReviewers: []User{{UserName: "ceo"}}},
{Number: 12, User: &User{UserName: "max"}, CreatedAt: iso(-600), UpdatedAt: iso(-300), RequestedReviewers: []User{{UserName: "ceo"}}},
{Number: 13, User: &User{UserName: "max"}, CreatedAt: iso(-600), UpdatedAt: iso(-300), RequestedReviewers: []User{{UserName: "ceo"}}},
},
},
comments: map[string][]Comment{
"alterminal/teai/11": {{User: &User{UserName: "max"}, CreatedAt: iso(-300)}}, // author-idle
"alterminal/teai/12": {{User: &User{UserName: "ceo"}, CreatedAt: iso(-300)}}, // reviewer-idle
"alterminal/teai/13": {{User: &User{UserName: "dan"}, CreatedAt: iso(-300)}}, // no-commenter(外部留言)
},
}
got, err := ScanStalled(src, "admin", 4.0, now)
if err != nil {
t.Fatalf("ScanStalled: %v", err)
}
byNumber := map[int64]Item{}
for _, it := range got {
byNumber[it.Number] = it
}
for n, wantReason := range map[int64]string{10: "no-reviewer", 11: "author-idle", 12: "reviewer-idle", 13: "no-commenter"} {
item, ok := byNumber[n]
if !ok {
t.Fatalf("PR %d 應列入,got %v", n, got)
}
if item.Reason != wantReason {
t.Errorf("PR %d reason = %q, want %q", n, item.Reason, wantReason)
}
}
if len(got) != 4 {
t.Fatalf("應 4 筆,got %d", len(got))
}
if byNumber[10].Author != "max" {
t.Errorf("PR 10 author 應為 max,got %q", byNumber[10].Author)
}
}
// TestScanStalledNoPullsFlag 停用 PR 的倉庫仍掃 issues,只跳過 PR。
func TestScanStalledNoPullsFlag(t *testing.T) {
now := at(0)
h := false
src := &fakeSource{
orgs: []string{"alterminal"},
repos: map[string][]Repo{"alterminal": {{Name: "docs", HasPullRequests: &h}}},
issues: map[string]map[int64]Issue{
"alterminal/docs": {
1: {Number: 1, State: "open", CreatedAt: iso(-600), UpdatedAt: iso(-600), Repository: &Repository{FullName: "alterminal/docs"}},
},
},
pulls: map[string][]PullRequest{
// 即使假資料有 PR,flag 關閉也不應掃。
"alterminal/docs": {{Number: 2, User: &User{UserName: "max"}, CreatedAt: iso(-600), UpdatedAt: iso(-600)}},
},
}
got, err := ScanStalled(src, "admin", 4.0, now)
if err != nil {
t.Fatalf("ScanStalled: %v", err)
}
if len(got) != 1 || got[0].Number != 1 || got[0].Type != "issue" {
t.Fatalf("應只有 issue 1,got %v", got)
}
}
// TestScanStalledSkipsPRsInIssues 確認 /issues 混入的 PR 會被過濾。
func TestScanStalledSkipsPRsInIssues(t *testing.T) {
now := at(0)
src := &fakeSource{
orgs: []string{"alterminal"},
repos: map[string][]Repo{"alterminal": repoWith("teai", true)},
issues: map[string]map[int64]Issue{
"alterminal/teai": {
1: {Number: 1, State: "open", CreatedAt: iso(-600), UpdatedAt: iso(-600), Repository: &Repository{FullName: "alterminal/teai"}, PullRequest: &pullMarker{}},
},
},
}
got, err := ScanStalled(src, "admin", 4.0, now)
if err != nil {
t.Fatalf("ScanStalled: %v", err)
}
if len(got) != 0 {
t.Fatalf("/issues 混入的 PR 應過濾,got %v", got)
}
}
// TestItemJSON 與 gitea.py 的 JSON 位元組相容(鍵序、HTML 不轉義、48.0、null)。
func TestItemJSON(t *testing.T) {
ts := at(-600)
activity := FormatMoment(ts)
item := Item{
Type: "issue", Repo: "alterminal/teai", Number: 7, Title: "R,D <v2> & 規劃", URL: "u",
Assignees: []string{"ceo"}, LastCommentBy: "max",
LastActivityAt: ts, StalledHours: 48, Reason: "assignee-idle",
ChildActivity: []Child{
{Repo: "alterminal/teai", Number: 3, Title: "父", State: "open", LastActivityAt: &activity},
{Repo: "alterminal/teai", Number: 4, Title: "無時刻", State: "open"},
},
}
// json.Marshal 會把 <、>、& 重新轉義,必須用停用 HTML 轉義的編碼器。
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(item); err != nil {
t.Fatalf("Encode: %v", err)
}
got := strings.TrimSuffix(buf.String(), "\n")
want := `{"type":"issue","repo":"alterminal/teai","number":7,"title":"R,D <v2> & 規劃","url":"u","assignees":["ceo"],"last_comment_by":"max","last_activity_at":"2026-09-09T22:00:00+00:00","stalled_hours":48.0,"reason":"assignee-idle","child_activity":[{"repo":"alterminal/teai","number":3,"title":"父","state":"open","last_activity_at":"2026-09-09T22:00:00+00:00"},{"repo":"alterminal/teai","number":4,"title":"無時刻","state":"open","last_activity_at":null}]}`
if got != want {
t.Fatalf("JSON 位元組不相容:\n got %s\nwant %s", got, want)
}
}
// TestPullJSON:pull 的鍵序(author、reviewers)與非整數 stalled_hours。
func TestPullJSON(t *testing.T) {
item := Item{
Type: "pull", Repo: "alterminal/teai", Number: 12, Title: "t", URL: "u",
Author: "ceo", Reviewers: []string{"queena"},
LastActivityAt: at(-600), StalledHours: 10.44, Reason: "reviewer-idle",
}
b, err := json.Marshal(item)
if err != nil {
t.Fatalf("Marshal: %v", err)
}
got := string(b)
want := `{"type":"pull","repo":"alterminal/teai","number":12,"title":"t","url":"u","author":"ceo","reviewers":["queena"],"last_comment_by":"","last_activity_at":"2026-09-09T22:00:00+00:00","stalled_hours":10.4,"reason":"reviewer-idle"}`
if got != want {
t.Fatalf("JSON 位元組不相容:\n got %s\nwant %s", got, want)
}
}
// TestScanStalledEmpty 無停滯項目 → 空輸出(CLI 層輸出 [])。
func TestScanStalledEmpty(t *testing.T) {
now := at(0)
src := &fakeSource{orgs: []string{"alterminal"}, repos: map[string][]Repo{"alterminal": repoWith("teai", true)}}
got, err := ScanStalled(src, "admin", 4.0, now)
if err != nil {
t.Fatalf("ScanStalled: %v", err)
}
if len(got) != 0 {
t.Fatalf("應空,got %v", got)
}
}
// TestScanStalledOrgError 組織層錯誤應回傳(不靜默)。
func TestScanStalledOrgError(t *testing.T) {
src := &errSource{}
if _, err := ScanStalled(src, "admin", 4.0, at(0)); err == nil {
t.Fatal("組織清單失敗應回傳錯誤")
}
}
type errSource struct{}
func (errSource) MyOrganizations() ([]string, error) { return nil, errors.New("boom") }
func (e errSource) OrganizationRepositories(string) ([]Repo, error) {
return nil, errors.New("boom")
}
func (e errSource) OpenIssues(string, string) ([]Issue, error) { return nil, errors.New("boom") }
func (e errSource) OpenPulls(string, string) ([]PullRequest, error) { return nil, errors.New("boom") }
func (e errSource) IssueComments(string, string, int64) ([]Comment, error) {
return nil, errors.New("boom")
}
func (e errSource) TryGetIssue(string, string, int64) (Issue, bool, error) {
return Issue{}, false, errors.New("boom")
}
func (e errSource) IssueTimeline(string, string, int64) ([]TimelineEvent, error) {
return nil, errors.New("boom")
}
// TestRound1 round1 十進位舍入到一位小數(與 Python round(x,1) 半偶數一致)。
func TestRound1(t *testing.T) {
cases := []struct {
in float64
want float64
}{
{10.44, 10.4}, {10.46, 10.5}, {10.0, 10.0},
// 半偶數(與 Python round(x,1) 對二進位真值的行為一致):
// 10.45、5.25、5.15 的二進位真值都略低於表值 → 舍到偶數位。
{10.45, 10.4}, {0.05, 0.1}, {5.25, 5.2}, {5.15, 5.2},
}
for _, tc := range cases {
if got := round1(tc.in); got != tc.want {
t.Errorf("round1(%v) = %v, want %v", tc.in, got, tc.want)
}
}
}