Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab94cdce9f | ||
|
|
5f323a685e | ||
|
|
4582dfaa4e | ||
|
|
47056dda43 | ||
|
|
9948357f52 | ||
|
|
0b0c3cefcb | ||
|
|
a8c1f3e018 | ||
|
|
0ed6f262c8 | ||
|
|
fb2990dc04 | ||
|
|
67cafcff59 | ||
|
|
4a34def1f5 | ||
|
|
15c2d35935 | ||
|
|
c4fb641094 | ||
|
|
f7d63d6e8f | ||
|
|
f481377b9a | ||
|
|
c5d5c37eae | ||
|
|
b2dd2f3aac | ||
|
|
927855d3ca | ||
|
|
c311f02e0f | ||
|
|
7badd9e46d | ||
|
|
5583a00bb5 | ||
|
|
a86803d336 |
@@ -6,17 +6,52 @@ teai 是 Gitea 的命令列(CLI)工具,以更完整、更可靠的方式
|
||||
|
||||
- **語言:** Go(與 Gitea 本體一致),僅用標準庫,離線可建置
|
||||
- **目標站點:** `https://gitea.alterminal.com`
|
||||
- **狀態:** 專案初始化中,功能尚未開始開發;本文的指令集為設計藍圖
|
||||
- **狀態:** 基礎建設(#5:internal/gitea)、工作流命令(#6:whoami/orgs/members/mine/pulls/next)、日常操作命令(#8:issues/pulls/labels/milestones/releases/repos/api)與管理者巡邏命令(#7:stalled/xrefs)已實作
|
||||
- **範圍(#3):** 不避開 tea 已有的功能;單一工具涵蓋完整操作
|
||||
|
||||
## 安裝與建置
|
||||
|
||||
需要 Go 1.26 以上。
|
||||
### 需求
|
||||
|
||||
- **Go 1.26 以上**(`go version` 確認;本倉庫僅用標準庫,離線可建置)
|
||||
- **git**
|
||||
- Gitea 帳號的 **API token**(設定階段使用;在 Gitea「設定 → 應用程式」產生)
|
||||
|
||||
### 從原始碼建置
|
||||
|
||||
```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 0.1.0-dev
|
||||
```
|
||||
|
||||
也可以直接裝進 `GOBIN`(預設 `~/go/bin`;該目錄已在 PATH 時最省事):
|
||||
|
||||
```sh
|
||||
go install ./cmd/teai
|
||||
```
|
||||
|
||||
> **注意:** `go install gitea.alterminal.com/alterminal/teai/cmd/teai@latest` 目前**不可用**——
|
||||
> module 尚未發佈任何 tag,`@latest` 會解析到任意中繼 commit(且 #21 修復前 main 建置失敗)。
|
||||
> 請在 clone 目錄內以版本控制的方式建置;發佈 tag 後再提供 `teai@<version>` 安裝路徑。
|
||||
|
||||
### 登入設定(首次使用)
|
||||
|
||||
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`;
|
||||
@@ -29,7 +64,38 @@ go build -o teai ./cmd/teai
|
||||
3. **機器可讀優先**:預設輸出 JSON;`--output table` 僅供人工抽查。
|
||||
4. **可直接替換原型**:`gitea.py` 的每個子命令在 teai 都有語義相同的對應命令,可交叉驗證、平滑遷移。
|
||||
5. **認證沿用 tea**:讀 `tea` 的登入組態(`TEA_CONFIG` 或 `~/.config/tea/config.yml`),不另建認證體系。
|
||||
6. **安全預設**:本期全部是查詢類(唯讀);寫入類(留言、指派、審核者)不在本期範圍,未來加入時須明確 `--yes`。
|
||||
6. **安全預設**:查詢類唯讀;寫入類命令(#8 起)一律要求明確 `--yes`,未確認時不發出任何請求、不產生任何遠端變更。
|
||||
|
||||
### 日常操作(tea 對等指令;#3 不避開 tea 已有功能;#8 已實作)
|
||||
|
||||
issues/pulls/labels/milestones/releases/repos/api 的日常操作,自行實作、輸出一致 JSON、共用同一套認證與全域選項。介面語義以 `tea`/Gitea API 為相容參考。已實作:
|
||||
|
||||
```sh
|
||||
# issues
|
||||
teai issues list --repo <owner>/<repo> [--state open|closed|all]
|
||||
teai issues view --repo <owner>/<repo> <number> [--comments]
|
||||
teai issues create --repo <owner>/<repo> --title … [--body …] [--assignees a,b] --yes
|
||||
teai issues close --repo <owner>/<repo> --yes <number>
|
||||
teai issues comment --repo <owner>/<repo> --body … --yes <number>
|
||||
# pulls(無子命令仍是工作流清單:--mine/--reviewer/--repo)
|
||||
teai pulls list --repo <owner>/<repo> [--state open|closed|all]
|
||||
teai pulls view --repo <owner>/<repo> <number> [--comments]
|
||||
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 comment --repo <owner>/<repo> --body … --yes <number>
|
||||
# labels/milestones/releases/repos
|
||||
teai labels list --repo <owner>/<repo>
|
||||
teai labels create --repo <owner>/<repo> --name … [--color #RRGGBB] [--description …] --yes
|
||||
teai milestones list --repo <owner>/<repo> [--state open|closed|all]
|
||||
teai milestones create --repo <owner>/<repo> --title … [--description …] [--due RFC3339] --yes
|
||||
teai releases list --repo <owner>/<repo>
|
||||
teai repos list [--org <org>]
|
||||
# 任意 API 呼叫(逃生口)
|
||||
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 請求。
|
||||
> `teai api` 的 path 內含查詢字串(如 `/repos/a/b/issues?state=closed`)時會正確傳遞。
|
||||
|
||||
### 全域介面
|
||||
|
||||
@@ -60,22 +126,6 @@ teai [全域選項] <命令> [參數]
|
||||
| `teai xrefs <owner>/<repo> <number>` | (內部函式公開化) | 解析內文/留言中的 issue/PR 引用 |
|
||||
| `teai version` | — | 版本資訊(骨架已實作) |
|
||||
|
||||
### 日常操作(tea 對等指令;#3 不避開 tea 已有功能)
|
||||
|
||||
tea 已有的日常操作 teai 也會自行實作(一致的 JSON 輸出、同一套認證與全域選項),
|
||||
不要求使用者回頭併用 `tea`。介面語義以 `tea`/Gitea API 為相容參考,僅列出主要子命令,
|
||||
細節(旗標、欄位)在個別實作 issue 中定義:
|
||||
|
||||
| 命令 | 對應 tea | 說明 |
|
||||
| --- | --- | --- |
|
||||
| `teai issues [list\|create\|view\|close\|comment…]` | `tea issues` | issues 管理(含 `--comments`、`--assignees`) |
|
||||
| `teai pulls [list\|create\|view\|merge\|comment…]` | `tea pulls` | PR 管理(含審核者、合併) |
|
||||
| `teai labels` / `teai milestones` / `teai releases` | 同名 tea 指令 | 標籤、里程碑、發佈管理 |
|
||||
| `teai repos` / `teai orgs` | `tea repos`/`tea orgs` | 倉庫與組織查詢 |
|
||||
| `teai api <path>` | `tea api` | 任意 API 呼叫(逃生口,`--method`、`--data`) |
|
||||
|
||||
> 實作順序不變:先完成 gitea.py 工作流命令的 Go 化,再依 issue 逐項補齊日常操作。
|
||||
|
||||
> `gitea.py` 的底線函式(`_pr_needs_author_followup`、`_resolve_xref_targets` 等)是內部實作,teai 將其放在 `internal/` 套件,不另設 CLI 命令。
|
||||
|
||||
### `teai next` — 下一件該做的事
|
||||
@@ -221,6 +271,15 @@ teai whoami # 目前帳號(讀 tea 組態)
|
||||
| `mine` | `teai mine` | 相同 |
|
||||
| (底線函式) | `internal/` 套件 | 不設 CLI 命令;`xrefs` 為其邏輯的公開化 |
|
||||
|
||||
已知輸出差異(刻意保留,機器可讀優先):
|
||||
|
||||
- **空清單**:`gitea.py` 的 `_dump` 對空清單**不輸出任何內容**;teai 的清單類命令
|
||||
(`mine`/`pulls`)空清單輸出 `[]`。對 JSON 消費者來說 `[]` 比「無輸出」更明確,
|
||||
交叉驗證時以此差異為準。`next` 兩者語義相同(無工作 → `null`/「沒有未完成的工作」)。
|
||||
- **全域選項位置**:teai 的全域選項(`--output` 等)可出現在命令之前或之後,
|
||||
且可與命令旗標交錯(`teai members --has-work --output table`);
|
||||
gitea.py 的旗標剖析較寬鬆,兩者命令列介面以此行為對齊。
|
||||
|
||||
遷移策略:
|
||||
|
||||
1. 以 gitea.py 為行為基準:同帳號同時跑兩者,輸出應一致(交叉驗證)。
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
// 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) 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())
|
||||
}
|
||||
+136
-5
@@ -150,6 +150,110 @@ var globalFlags = map[string]bool{
|
||||
"--timeout": true,
|
||||
}
|
||||
|
||||
// reservedFlags 回傳 dispatch 不得搶走的旗標名稱(含 -- 前綴):這些
|
||||
// 旗標屬於目前命令(或其子命令),即使與全域選項同名也必須原樣留給
|
||||
// 命令剖析。目前唯一與全域同名的是 login add 的 --url/--token
|
||||
// (README「teai login add --url … --token …」)。其餘命令的旗標
|
||||
// (--repo、--has-work、--mine……)本來就不在 globalFlags 內,不受影響。
|
||||
func reservedFlags(name string) map[string]bool {
|
||||
reserved := make(map[string]bool)
|
||||
for _, f := range commandReservedFlags[name] {
|
||||
reserved[f] = true
|
||||
}
|
||||
return reserved
|
||||
}
|
||||
|
||||
// commandReservedFlags 登記每個命令「與全域選項同名」的自有旗標。
|
||||
// 命令旗標優先留給命令;新命令有同姓旗標時在這裡登記(#18)。
|
||||
var commandReservedFlags = map[string][]string{
|
||||
"login": {"--url", "--token"},
|
||||
}
|
||||
|
||||
// extractGlobals 從 args 中「抽取」全域選項(可出現在命令之後、與命令
|
||||
// 旗標交錯),其餘引數依原順序保留給子命令剖析。未知的選項一律留給
|
||||
// 子命令處理(可能是命令旗標,如 --has-work),不在這裡報錯。
|
||||
// reserved 是目前命令保留的旗標名稱(含 -- 前綴,見 reservedFlags):
|
||||
// 列於其中的選項即使與全域同名也原樣留給命令,命令旗標優先(#18)。
|
||||
func extractGlobals(g *Globals, args []string, reserved map[string]bool) ([]string, error) {
|
||||
rest := make([]string, 0, len(args))
|
||||
applyGlobal := func(name, value string) error {
|
||||
switch name {
|
||||
case "--url":
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return &ErrUsage{Msg: "--url must not be empty"}
|
||||
}
|
||||
g.URL = value
|
||||
case "--token":
|
||||
g.Token = value
|
||||
case "--config":
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return &ErrUsage{Msg: "--config must not be empty"}
|
||||
}
|
||||
g.ConfigPath = value
|
||||
case "--output":
|
||||
f, err := gitea.ParseFormat(value)
|
||||
if err != nil {
|
||||
return &ErrUsage{Msg: err.Error()}
|
||||
}
|
||||
g.Output = f
|
||||
case "--timeout":
|
||||
d, err := time.ParseDuration(value)
|
||||
if err != nil || d <= 0 {
|
||||
return &ErrUsage{Msg: fmt.Sprintf("invalid --timeout %q (want e.g. 30s)", value)}
|
||||
}
|
||||
g.Timeout = d
|
||||
}
|
||||
return nil
|
||||
}
|
||||
i := 0
|
||||
for i < len(args) {
|
||||
arg := args[i]
|
||||
if arg == "--" {
|
||||
rest = append(rest, args[i+1:]...)
|
||||
return rest, nil
|
||||
}
|
||||
if !strings.HasPrefix(arg, "--") {
|
||||
rest = append(rest, arg)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
name, inline, hasInline := strings.Cut(arg, "=")
|
||||
if reserved[name] {
|
||||
// 命令保留旗標:即使與全域選項同名也留給命令剖析(#18)。
|
||||
rest = append(rest, arg)
|
||||
if !hasInline && i+1 < len(args) {
|
||||
// 旗標值跟在下一個引數;一併保留,不當成全域值。
|
||||
rest = append(rest, args[i+1])
|
||||
i++
|
||||
}
|
||||
i++
|
||||
continue
|
||||
}
|
||||
_, ok := globalFlags[name]
|
||||
if !ok {
|
||||
// 不是全域選項:留給子命令(可能是 --has-work 這類命令旗標)。
|
||||
rest = append(rest, arg)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
var value string
|
||||
if hasInline {
|
||||
value = inline
|
||||
} else {
|
||||
if i+1 >= len(args) {
|
||||
return nil, &ErrUsage{Msg: fmt.Sprintf("global option %q requires a value", name)}
|
||||
}
|
||||
i++
|
||||
value = args[i]
|
||||
}
|
||||
if err := applyGlobal(name, value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
i++
|
||||
}
|
||||
return rest, nil
|
||||
}
|
||||
|
||||
// parseGlobals 從 args 前端取走全域選項,回傳剩餘引數(命令與其參數)。
|
||||
// 遇到第一個非選項引數即停;不認得的選項或缺少值都回 ErrUsage。
|
||||
func parseGlobals(g *Globals, args []string) ([]string, error) {
|
||||
@@ -218,20 +322,44 @@ func parseGlobals(g *Globals, args []string) ([]string, error) {
|
||||
}
|
||||
|
||||
// dispatch 執行已註冊的子命令,把錯誤轉成結束碼並輸出。
|
||||
// 旗標剖析交由各命令自行處理(不同命令有不同旗標,如 pulls --mine);
|
||||
// 全域選項允許出現在命令之後(README 範例:teai next --output table),
|
||||
// dispatch 先從 args 剝離全域選項併入 Globals,其餘(含命令自己的旗標,
|
||||
// 如 --has-work)原樣交給命令,不會誤判為未知全域選項。與全域選項
|
||||
// 同名的命令旗標(登記於 commandReservedFlags)優先留給命令(#18)。
|
||||
func dispatch(env *Env, name string, args []string) int {
|
||||
cmd := commands[name]
|
||||
fs := flag.NewFlagSet("teai "+name, flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
if err := fs.Parse(args); err != nil {
|
||||
g := env.Globals
|
||||
rest, err := extractGlobals(&g, args, reservedFlags(name))
|
||||
if err != nil {
|
||||
fmt.Fprintf(env.Err, "teai: %v\n\n", err)
|
||||
printUsage(env.Err)
|
||||
return int(ExitUsage)
|
||||
}
|
||||
if err := cmd.run(env, fs.Args()); err != nil {
|
||||
env.Globals = g
|
||||
if err := cmd.run(env, rest); err != nil {
|
||||
fmt.Fprintf(env.Err, "teai %s: %v\n", name, err)
|
||||
return int(exitCodeFor(err))
|
||||
}
|
||||
return int(ExitOK)
|
||||
}
|
||||
|
||||
// errHelp 表示使用者要求該命令的說明(-h/--help);FlagSet 已自行印出
|
||||
// 用法,靜默成功結束即可。
|
||||
var errHelp = errors.New("help requested")
|
||||
|
||||
// parseFlags 剖析命令旗標:-h/--help 回 errHelp(由 exitCodeFor 視為成功),
|
||||
// 其他剖析錯誤回 ErrUsage。
|
||||
func parseFlags(fs *flag.FlagSet, args []string) error {
|
||||
if err := fs.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return errHelp
|
||||
}
|
||||
return &ErrUsage{Msg: err.Error()}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// exitCodeFor 把命令錯誤映射到結束碼:用法錯誤 → 2,API 錯誤 → 3,
|
||||
// 其他(內部)→ 1。
|
||||
func exitCodeFor(err error) ExitCode {
|
||||
@@ -249,8 +377,11 @@ func exitCodeFor(err error) ExitCode {
|
||||
return ExitInternal
|
||||
}
|
||||
|
||||
// runVersion 輸出版本資訊。
|
||||
// runVersion 輸出版本資訊;不接受任何參數。
|
||||
func runVersion(env *Env, args []string) error {
|
||||
if len(args) > 0 {
|
||||
return &ErrUsage{Msg: "version 不接受參數"}
|
||||
}
|
||||
fmt.Fprintf(env.Out, "teai version %s\n", Version)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -51,8 +51,10 @@ func TestRunVersion(t *testing.T) {
|
||||
|
||||
func TestRunUnknownCommand(t *testing.T) {
|
||||
_, stderr, code := run("no-such-command")
|
||||
if code != int(ExitUsage) {
|
||||
t.Errorf("未知命令應回 ExitUsage(%d),得到 %d", int(ExitUsage), code)
|
||||
// 直接對照 README「輸出與結束碼」的數值(用法錯誤=2),
|
||||
// 不以常數互比,避免常數與規格再次脫鉤(#10)。
|
||||
if code != 2 {
|
||||
t.Errorf("未知命令應回 2(README 用法錯誤),得到 %d", code)
|
||||
}
|
||||
if !strings.Contains(stderr, "unknown command") {
|
||||
t.Errorf("未知命令應在 stderr 說明,得到:%q", stderr)
|
||||
|
||||
@@ -0,0 +1,866 @@
|
||||
// dailyops_commands.go — 日常操作命令的 CLI 接線(#8):issues、pulls、
|
||||
// labels、milestones、releases、repos、api(tea 對等指令)。
|
||||
//
|
||||
// 規則:
|
||||
// - 寫入類命令(create/close/comment/merge…)一律要求 --yes,
|
||||
// 未帶 --yes 時不產生任何遠端變更(exit 2,用法錯誤)。
|
||||
// - `teai pulls` 相容 #6 的工作流用法(無子命令=工作流清單 --mine/--reviewer);
|
||||
// 有子命令(list/create/view/merge/comment)時走日常操作。
|
||||
// - 輸出走 internal/gitea 的 Printer(--output json|table)。
|
||||
package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitea.alterminal.com/alterminal/teai/internal/dailyops"
|
||||
"gitea.alterminal.com/alterminal/teai/internal/gitea"
|
||||
)
|
||||
|
||||
func init() {
|
||||
register := func(c *command) { commands[c.name] = c }
|
||||
register(&command{name: "issues", usage: "issues 管理(list/view/create/close/comment)", run: runIssues})
|
||||
register(&command{name: "pulls", usage: "PR 管理(list/view/create/merge/comment;無子命令=工作流清單)", run: runPullsDaily})
|
||||
register(&command{name: "labels", usage: "標籤管理(list/create)", run: runLabels})
|
||||
register(&command{name: "milestones", usage: "里程碑管理(list/create)", run: runMilestones})
|
||||
register(&command{name: "releases", usage: "發佈清單(list)", run: runReleases})
|
||||
register(&command{name: "repos", usage: "倉庫查詢(list)", run: runRepos})
|
||||
register(&command{name: "api", usage: "任意 API 呼叫(--method/--data;寫入動詞需 --yes)", run: runAPIDirect})
|
||||
}
|
||||
|
||||
// requireYes 檢查寫入閘門:未帶 --yes 回 ErrUsage(exit 2),不觸發任何請求。
|
||||
func requireYes(yes bool, what string) error {
|
||||
if !yes {
|
||||
return &ErrUsage{Msg: what + " 是寫入操作,需 --yes 明確確認(未確認,未產生任何遠端變更)"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// splitRepoFlag 把 --repo owner/repo 拆成兩段;空值回 ("", "", nil)。
|
||||
func splitRepoFlag(v string) (string, string, error) {
|
||||
if v == "" {
|
||||
return "", "", nil
|
||||
}
|
||||
parts := strings.SplitN(v, "/", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return "", "", &ErrUsage{Msg: errNoRepoFlag.Error()}
|
||||
}
|
||||
return parts[0], parts[1], nil
|
||||
}
|
||||
|
||||
// newOpsClient 依全域選項建立 dailyops 用戶端。
|
||||
func newOpsClient(env *Env) (*dailyops.Ops, 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 &dailyops.Ops{Client: client}, nil
|
||||
}
|
||||
|
||||
// parseNumber 把位置參數解析為 issue/PR 編號。
|
||||
func parseNumber(s string) (int64, error) {
|
||||
n, err := strconv.ParseInt(s, 10, 64)
|
||||
if err != nil || n <= 0 {
|
||||
return 0, &ErrUsage{Msg: fmt.Sprintf("無效的編號 %q", s)}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// joinOrEmpty 把清單型欄位格式化為逗號分隔(table 用)。
|
||||
func joinOrEmpty(v any) string {
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
return x
|
||||
case []string:
|
||||
return strings.Join(x, ",")
|
||||
default:
|
||||
return fmt.Sprint(x)
|
||||
}
|
||||
}
|
||||
|
||||
// issueRowsFields 是 issues 清單的欄位定義(與值順序對應)。
|
||||
func issueListFields() []gitea.Field {
|
||||
return []gitea.Field{
|
||||
{Name: "number"}, {Name: "title"}, {Name: "state"},
|
||||
{Name: "author"}, {Name: "assignees", ValueFmt: joinOrEmpty}, {Name: "updated_at"},
|
||||
}
|
||||
}
|
||||
|
||||
// ---- issues ----
|
||||
|
||||
// runIssues:teai issues [list|view|create|close|comment] …
|
||||
func runIssues(env *Env, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return &ErrUsage{Msg: "issues 需要子命令:list | view | create | close | comment"}
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
case "list":
|
||||
return runIssuesList(env, rest)
|
||||
case "view":
|
||||
return runIssuesView(env, rest)
|
||||
case "create":
|
||||
return runIssuesCreate(env, rest)
|
||||
case "close":
|
||||
return runIssuesClose(env, rest)
|
||||
case "comment":
|
||||
return runComment(env, rest, false)
|
||||
default:
|
||||
return &ErrUsage{Msg: fmt.Sprintf("issues 未知子命令 %q(可用:list | view | create | close | comment)", sub)}
|
||||
}
|
||||
}
|
||||
|
||||
// runIssuesList:teai issues list --repo owner/repo [--state open|closed|all]
|
||||
func runIssuesList(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai issues list", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
state := fs.String("state", "open", "狀態:open|closed|all")
|
||||
if err := parseFlags(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 0 {
|
||||
return &ErrUsage{Msg: "issues list 不接受位置參數"}
|
||||
}
|
||||
owner, name, err := splitRepoFlag(*repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if owner == "" {
|
||||
return &ErrUsage{Msg: "issues list 需要 --repo owner/repo"}
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
issues, err := ops.ListIssues(context.Background(), owner, name, *state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := printer(env)
|
||||
rows := make([]gitea.Values, 0, len(issues))
|
||||
for i := range issues {
|
||||
it := &issues[i]
|
||||
rows = append(rows, gitea.Values{
|
||||
it.Number, it.Title, it.State, it.Author(),
|
||||
it.AssigneeNames(), it.UpdatedAt,
|
||||
})
|
||||
}
|
||||
return p.PrintList(issueListFields(), rows)
|
||||
}
|
||||
|
||||
// runIssuesView:teai issues view --repo owner/repo <number> [--comments]
|
||||
func runIssuesView(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai issues view", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
withComments := fs.Bool("comments", 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: "issues view 需要 --repo owner/repo"}
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return &ErrUsage{Msg: "issues view 需要恰好一個編號"}
|
||||
}
|
||||
num, err := parseNumber(fs.Arg(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
it, err := ops.GetIssue(context.Background(), owner, name, num)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := printer(env)
|
||||
fields := []gitea.Field{
|
||||
{Name: "number"}, {Name: "title"}, {Name: "state"},
|
||||
{Name: "author"}, {Name: "assignees", ValueFmt: joinOrEmpty},
|
||||
{Name: "labels", ValueFmt: joinOrEmpty}, {Name: "body"},
|
||||
{Name: "url"}, {Name: "updated_at"},
|
||||
}
|
||||
row := gitea.Values{
|
||||
it.Number, it.Title, it.State, it.Author(),
|
||||
it.AssigneeNames(), it.LabelNames(), it.Body,
|
||||
it.HTMLURL, it.UpdatedAt,
|
||||
}
|
||||
if err := p.PrintOne(fields, row); err != nil {
|
||||
return err
|
||||
}
|
||||
if !*withComments {
|
||||
return nil
|
||||
}
|
||||
return printComments(env, ops, owner, name, num)
|
||||
}
|
||||
|
||||
// printComments 輸出 issue/PR 的留言清單(view --comments 共用)。
|
||||
func printComments(env *Env, ops *dailyops.Ops, owner, repo string, number int64) error {
|
||||
comments, err := ops.ListComments(context.Background(), owner, repo, number)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := printer(env)
|
||||
rows := make([]gitea.Values, 0, len(comments))
|
||||
for i := range comments {
|
||||
c := &comments[i]
|
||||
rows = append(rows, gitea.Values{c.Author(), c.CreatedAt, c.Body})
|
||||
}
|
||||
return p.PrintList([]gitea.Field{
|
||||
{Name: "author"}, {Name: "created_at"}, {Name: "body"},
|
||||
}, rows)
|
||||
}
|
||||
|
||||
// runIssuesCreate:teai issues create --repo owner/repo --title … [--body …] [--assignees a,b] --yes
|
||||
func runIssuesCreate(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai issues create", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
title := fs.String("title", "", "標題(必填)")
|
||||
body := fs.String("body", "", "內文")
|
||||
assignees := fs.String("assignees", "", "assignees(逗號分隔,可選)")
|
||||
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: "issues create 需要 --repo owner/repo"}
|
||||
}
|
||||
if strings.TrimSpace(*title) == "" {
|
||||
return &ErrUsage{Msg: "issues create 需要 --title"}
|
||||
}
|
||||
if err := requireYes(*yes, "issues create"); err != nil {
|
||||
return err
|
||||
}
|
||||
var assigneeList []string
|
||||
if strings.TrimSpace(*assignees) != "" {
|
||||
for _, a := range strings.Split(*assignees, ",") {
|
||||
if a = strings.TrimSpace(a); a != "" {
|
||||
assigneeList = append(assigneeList, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
issue, err := ops.CreateIssue(context.Background(), owner, name, *title, *body, assigneeList)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printer(env).PrintOne([]gitea.Field{
|
||||
{Name: "number"}, {Name: "title"}, {Name: "url"},
|
||||
}, gitea.Values{issue.Number, issue.Title, issue.HTMLURL})
|
||||
}
|
||||
|
||||
// runIssuesClose:teai issues close --repo owner/repo <number> --yes
|
||||
func runIssuesClose(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai issues 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: "issues close 需要 --repo owner/repo"}
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return &ErrUsage{Msg: "issues close 需要恰好一個編號"}
|
||||
}
|
||||
num, err := parseNumber(fs.Arg(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := requireYes(*yes, "issues close"); err != nil {
|
||||
return err
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
issue, err := ops.SetIssueState(context.Background(), owner, name, num, "closed")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printer(env).PrintOne([]gitea.Field{
|
||||
{Name: "number"}, {Name: "title"}, {Name: "state"}, {Name: "url"},
|
||||
}, gitea.Values{issue.Number, issue.Title, issue.State, issue.HTMLURL})
|
||||
}
|
||||
|
||||
// runComment:teai issues comment / teai pulls comment 共用。
|
||||
func runComment(env *Env, args []string, isPR bool) error {
|
||||
name := "issues comment"
|
||||
if isPR {
|
||||
name = "pulls comment"
|
||||
}
|
||||
fs := flag.NewFlagSet("teai "+name, 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, rname, err := splitRepoFlag(*repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if owner == "" {
|
||||
return &ErrUsage{Msg: name + " 需要 --repo owner/repo"}
|
||||
}
|
||||
if strings.TrimSpace(*body) == "" {
|
||||
return &ErrUsage{Msg: name + " 需要 --body"}
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return &ErrUsage{Msg: name + " 需要恰好一個編號"}
|
||||
}
|
||||
num, err := parseNumber(fs.Arg(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := requireYes(*yes, name); err != nil {
|
||||
return err
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
comment, err := ops.AddComment(context.Background(), owner, rname, num, *body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printer(env).PrintOne([]gitea.Field{
|
||||
{Name: "author"}, {Name: "created_at"}, {Name: "body"},
|
||||
}, gitea.Values{comment.Author(), comment.CreatedAt, comment.Body})
|
||||
}
|
||||
|
||||
// ---- pulls ----
|
||||
|
||||
// runPullsDaily:teai pulls [list|view|create|merge|comment] …;
|
||||
// 無子命令時沿用 #6 的工作流清單(teai pulls [--mine|--reviewer] [--repo])。
|
||||
func runPullsDaily(env *Env, args []string) error {
|
||||
if len(args) == 0 || strings.HasPrefix(args[0], "-") {
|
||||
// 相容 #6:teai pulls / teai pulls --mine …(工作流清單)。
|
||||
return runPulls(env, args)
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
case "list":
|
||||
return runPullsList(env, rest)
|
||||
case "view":
|
||||
return runPullsView(env, rest)
|
||||
case "create":
|
||||
return runPullsCreate(env, rest)
|
||||
case "merge":
|
||||
return runPullsMerge(env, rest)
|
||||
case "comment":
|
||||
return runComment(env, rest, true)
|
||||
default:
|
||||
return &ErrUsage{Msg: fmt.Sprintf("pulls 未知子命令 %q(可用:list | view | create | merge | comment;或無子命令=工作流清單)", sub)}
|
||||
}
|
||||
}
|
||||
|
||||
// runPullsList:teai pulls list --repo owner/repo [--state open|closed|all]
|
||||
func runPullsList(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai pulls list", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
state := fs.String("state", "open", "狀態:open|closed|all")
|
||||
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 list 需要 --repo owner/repo"}
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pulls, err := ops.ListPulls(context.Background(), owner, name, *state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := printer(env)
|
||||
rows := make([]gitea.Values, 0, len(pulls))
|
||||
for i := range pulls {
|
||||
pr := &pulls[i]
|
||||
rows = append(rows, gitea.Values{
|
||||
pr.Number, pr.Title, pr.State, pr.Author(),
|
||||
pr.HeadRef(), pr.BaseRef(), pr.UpdatedAt,
|
||||
})
|
||||
}
|
||||
return p.PrintList([]gitea.Field{
|
||||
{Name: "number"}, {Name: "title"}, {Name: "state"},
|
||||
{Name: "author"}, {Name: "head"}, {Name: "base"}, {Name: "updated_at"},
|
||||
}, rows)
|
||||
}
|
||||
|
||||
// runPullsView:teai pulls view --repo owner/repo <number> [--comments]
|
||||
func runPullsView(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai pulls view", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
withComments := fs.Bool("comments", 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 view 需要 --repo owner/repo"}
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return &ErrUsage{Msg: "pulls view 需要恰好一個編號"}
|
||||
}
|
||||
num, err := parseNumber(fs.Arg(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pr, err := ops.GetPull(context.Background(), owner, name, num)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := printer(env)
|
||||
fields := []gitea.Field{
|
||||
{Name: "number"}, {Name: "title"}, {Name: "state"},
|
||||
{Name: "author"}, {Name: "head"}, {Name: "base"}, {Name: "body"},
|
||||
{Name: "url"}, {Name: "updated_at"},
|
||||
}
|
||||
row := gitea.Values{
|
||||
pr.Number, pr.Title, pr.State, pr.Author(),
|
||||
pr.HeadRef(), pr.BaseRef(), pr.Body, pr.HTMLURL, pr.UpdatedAt,
|
||||
}
|
||||
if err := p.PrintOne(fields, row); err != nil {
|
||||
return err
|
||||
}
|
||||
if !*withComments {
|
||||
return nil
|
||||
}
|
||||
return printComments(env, ops, owner, name, num)
|
||||
}
|
||||
|
||||
// runPullsCreate:teai pulls create --repo owner/repo --head <branch> --base <branch> --title … [--body …] --yes
|
||||
func runPullsCreate(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai pulls create", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
head := fs.String("head", "", "來源分支(必填)")
|
||||
base := fs.String("base", "main", "目標分支(預設 main)")
|
||||
title := fs.String("title", "", "標題(必填)")
|
||||
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 create 需要 --repo owner/repo"}
|
||||
}
|
||||
if *head == "" || *title == "" {
|
||||
return &ErrUsage{Msg: "pulls create 需要 --head 與 --title"}
|
||||
}
|
||||
if err := requireYes(*yes, "pulls create"); err != nil {
|
||||
return err
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pr, err := ops.CreatePull(context.Background(), owner, name, *title, *body, *head, *base)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printer(env).PrintOne([]gitea.Field{
|
||||
{Name: "number"}, {Name: "title"}, {Name: "url"},
|
||||
}, gitea.Values{pr.Number, pr.Title, pr.HTMLURL})
|
||||
}
|
||||
|
||||
// runPullsMerge:teai pulls merge --repo owner/repo <number> [--style merge|rebase|squash] --yes
|
||||
func runPullsMerge(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai pulls merge", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
style := fs.String("style", "merge", "合併方式:merge|rebase|rebase-merge|squash")
|
||||
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 merge 需要 --repo owner/repo"}
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return &ErrUsage{Msg: "pulls merge 需要恰好一個編號"}
|
||||
}
|
||||
num, err := parseNumber(fs.Arg(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch *style {
|
||||
case "merge", "rebase", "rebase-merge", "squash":
|
||||
default:
|
||||
return &ErrUsage{Msg: "pulls merge 的 --style 需為 merge|rebase|rebase-merge|squash"}
|
||||
}
|
||||
if err := requireYes(*yes, "pulls merge"); err != nil {
|
||||
return err
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ops.MergePull(context.Background(), owner, name, num, *style); err != nil {
|
||||
return err
|
||||
}
|
||||
return printer(env).PrintOne([]gitea.Field{
|
||||
{Name: "number"}, {Name: "state"},
|
||||
}, gitea.Values{num, "merged"})
|
||||
}
|
||||
|
||||
// ---- labels ----
|
||||
|
||||
// runLabels:teai labels list --repo owner/repo|teai labels create … --yes
|
||||
func runLabels(env *Env, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return &ErrUsage{Msg: "labels 需要子命令:list | create"}
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
case "list":
|
||||
return runLabelsList(env, rest)
|
||||
case "create":
|
||||
return runLabelsCreate(env, rest)
|
||||
default:
|
||||
return &ErrUsage{Msg: fmt.Sprintf("labels 未知子命令 %q(可用:list | create)", sub)}
|
||||
}
|
||||
}
|
||||
|
||||
// runLabelsList:teai labels list --repo owner/repo
|
||||
func runLabelsList(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai labels list", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
if err := parseFlags(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
owner, name, err := splitRepoFlag(*repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if owner == "" {
|
||||
return &ErrUsage{Msg: "labels list 需要 --repo owner/repo"}
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
labels, err := ops.ListLabels(context.Background(), owner, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows := make([]gitea.Values, 0, len(labels))
|
||||
for _, l := range labels {
|
||||
rows = append(rows, gitea.Values{l.Name, l.Color, l.Description})
|
||||
}
|
||||
return printer(env).PrintList([]gitea.Field{
|
||||
{Name: "name"}, {Name: "color"}, {Name: "description"},
|
||||
}, rows)
|
||||
}
|
||||
|
||||
// runLabelsCreate:teai labels create --repo owner/repo --name … [--color …] [--description …] --yes
|
||||
func runLabelsCreate(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai labels create", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
labelName := fs.String("name", "", "標籤名(必填)")
|
||||
color := fs.String("color", "#ffffff", "顏色(#RRGGBB,預設 #ffffff)")
|
||||
desc := fs.String("description", "", "說明")
|
||||
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: "labels create 需要 --repo owner/repo"}
|
||||
}
|
||||
if *labelName == "" {
|
||||
return &ErrUsage{Msg: "labels create 需要 --name"}
|
||||
}
|
||||
if err := requireYes(*yes, "labels create"); err != nil {
|
||||
return err
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
label, err := ops.CreateLabel(context.Background(), owner, name, *labelName, *color, *desc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printer(env).PrintOne([]gitea.Field{
|
||||
{Name: "name"}, {Name: "color"}, {Name: "description"},
|
||||
}, gitea.Values{label.Name, label.Color, label.Description})
|
||||
}
|
||||
|
||||
// ---- milestones ----
|
||||
|
||||
// runMilestones:teai milestones list|create …
|
||||
func runMilestones(env *Env, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return &ErrUsage{Msg: "milestones 需要子命令:list | create"}
|
||||
}
|
||||
sub, rest := args[0], args[1:]
|
||||
switch sub {
|
||||
case "list":
|
||||
return runMilestonesList(env, rest)
|
||||
case "create":
|
||||
return runMilestonesCreate(env, rest)
|
||||
default:
|
||||
return &ErrUsage{Msg: fmt.Sprintf("milestones 未知子命令 %q(可用:list | create)", sub)}
|
||||
}
|
||||
}
|
||||
|
||||
// runMilestonesList:teai milestones list --repo owner/repo [--state open|closed|all]
|
||||
func runMilestonesList(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai milestones list", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
state := fs.String("state", "open", "狀態:open|closed|all")
|
||||
if err := parseFlags(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
owner, name, err := splitRepoFlag(*repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if owner == "" {
|
||||
return &ErrUsage{Msg: "milestones list 需要 --repo owner/repo"}
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ms, err := ops.ListMilestones(context.Background(), owner, name, *state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows := make([]gitea.Values, 0, len(ms))
|
||||
for _, m := range ms {
|
||||
rows = append(rows, gitea.Values{m.Title, m.State, m.Description, m.DueOn})
|
||||
}
|
||||
return printer(env).PrintList([]gitea.Field{
|
||||
{Name: "title"}, {Name: "state"}, {Name: "description"}, {Name: "due_on"},
|
||||
}, rows)
|
||||
}
|
||||
|
||||
// runMilestonesCreate:teai milestones create --repo owner/repo --title … [--description …] [--due …] --yes
|
||||
func runMilestonesCreate(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai milestones create", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
title := fs.String("title", "", "標題(必填)")
|
||||
desc := fs.String("description", "", "說明")
|
||||
due := fs.String("due", "", "截止日(RFC3339,可選)")
|
||||
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: "milestones create 需要 --repo owner/repo"}
|
||||
}
|
||||
if *title == "" {
|
||||
return &ErrUsage{Msg: "milestones create 需要 --title"}
|
||||
}
|
||||
if err := requireYes(*yes, "milestones create"); err != nil {
|
||||
return err
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m, err := ops.CreateMilestone(context.Background(), owner, name, *title, *desc, *due)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printer(env).PrintOne([]gitea.Field{
|
||||
{Name: "id"}, {Name: "title"}, {Name: "state"}, {Name: "due_on"},
|
||||
}, gitea.Values{m.ID, m.Title, m.State, m.DueOn})
|
||||
}
|
||||
|
||||
// ---- releases / repos / api ----
|
||||
|
||||
// runReleases:teai releases list --repo owner/repo
|
||||
func runReleases(env *Env, args []string) error {
|
||||
if len(args) == 0 || args[0] != "list" {
|
||||
return &ErrUsage{Msg: "releases 目前支援子命令:list"}
|
||||
}
|
||||
fs := flag.NewFlagSet("teai releases list", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||
if err := parseFlags(fs, args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
owner, name, err := splitRepoFlag(*repo)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if owner == "" {
|
||||
return &ErrUsage{Msg: "releases list 需要 --repo owner/repo"}
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
releases, err := ops.ListReleases(context.Background(), owner, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows := make([]gitea.Values, 0, len(releases))
|
||||
for _, r := range releases {
|
||||
rows = append(rows, gitea.Values{r.TagName, r.Name, r.Draft, r.Prerelease, r.PublishedAt})
|
||||
}
|
||||
return printer(env).PrintList([]gitea.Field{
|
||||
{Name: "tag_name"}, {Name: "name"}, {Name: "draft"}, {Name: "prerelease"}, {Name: "published_at"},
|
||||
}, rows)
|
||||
}
|
||||
|
||||
// runRepos:teai repos list [--org <org>](未指定 --org 則列自己可存的倉庫)
|
||||
func runRepos(env *Env, args []string) error {
|
||||
if len(args) == 0 || args[0] != "list" {
|
||||
return &ErrUsage{Msg: "repos 目前支援子命令:list"}
|
||||
}
|
||||
fs := flag.NewFlagSet("teai repos list", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
org := fs.String("org", "", "組織(未指定則列自己可存取的倉庫)")
|
||||
if err := parseFlags(fs, args[1:]); err != nil {
|
||||
return err
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var repos []dailyops.Repo
|
||||
if *org != "" {
|
||||
repos, err = ops.ListOrgRepos(context.Background(), *org)
|
||||
} else {
|
||||
repos, err = ops.ListMyRepos(context.Background())
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows := make([]gitea.Values, 0, len(repos))
|
||||
for _, r := range repos {
|
||||
rows = append(rows, gitea.Values{r.FullName, r.Private, r.Empty, r.UpdatedAt, r.HTMLURL})
|
||||
}
|
||||
return printer(env).PrintList([]gitea.Field{
|
||||
{Name: "full_name"}, {Name: "private"}, {Name: "empty"}, {Name: "updated_at"}, {Name: "url"},
|
||||
}, rows)
|
||||
}
|
||||
|
||||
// runAPIDirect:teai api <path> [--method GET|POST|…] [--data <json>] [--yes]
|
||||
func runAPIDirect(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai api", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
method := fs.String("method", "GET", "HTTP 動詞(GET 預設;非 GET 需 --yes)")
|
||||
data := fs.String("data", "", "請求 body(JSON 字串,可選)")
|
||||
yes := fs.Bool("yes", false, "確認寫入")
|
||||
if err := parseFlags(fs, args); err != nil {
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 1 {
|
||||
return &ErrUsage{Msg: "api 需要恰好一個 path(相對 api/v1,以 / 開頭)"}
|
||||
}
|
||||
path := fs.Arg(0)
|
||||
// path 內含查詢字串(如 /repos/x?state=closed)時剝離到 rawQuery,
|
||||
// 不可併進 URL path(會 404)。
|
||||
rawQuery := ""
|
||||
if q := strings.IndexByte(path, '?'); q >= 0 {
|
||||
rawQuery = path[q+1:]
|
||||
path = path[:q]
|
||||
}
|
||||
if path == "" || path[0] != '/' {
|
||||
return &ErrUsage{Msg: "api path 必須以 / 開頭(相對 api/v1)"}
|
||||
}
|
||||
upper := strings.ToUpper(strings.TrimSpace(*method))
|
||||
if upper == "" {
|
||||
upper = "GET"
|
||||
}
|
||||
switch upper {
|
||||
case "GET", "HEAD", "OPTIONS":
|
||||
default:
|
||||
if err := requireYes(*yes, "api "+upper); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var payload []byte
|
||||
if strings.TrimSpace(*data) != "" {
|
||||
if !json.Valid([]byte(*data)) {
|
||||
return &ErrUsage{Msg: "--data 必須是合法 JSON"}
|
||||
}
|
||||
payload = []byte(*data)
|
||||
}
|
||||
ops, err := newOpsClient(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := ops.CallAPIDirect(context.Background(), upper, path, rawQuery, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 原樣輸出(teai api 是逃生口,不做欄位挑選)。
|
||||
_, err = env.Out.Write(resp)
|
||||
if len(resp) > 0 && resp[len(resp)-1] != '\n' {
|
||||
fmt.Fprintln(env.Out)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
// dailyops_commands_test.go — #8 的驗收測試:以 httptest 假伺服器驗證
|
||||
// issues/pulls/labels/milestones/releases/repos/api 的讀取行為,與
|
||||
// 寫入命令的 --yes 閘門(未帶 --yes 不得發出任何請求)。
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// opsTestServer 建立假 Gitea API 伺服器與對應的執行輔助。
|
||||
func opsTestServer(t *testing.T, handler http.HandlerFunc) func(args ...string) (string, string, int) {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return func(args ...string) (string, string, int) {
|
||||
full := append([]string{"--url", srv.URL}, args...)
|
||||
return runCLI(full...) // 套件級輔助(見下)
|
||||
}
|
||||
}
|
||||
|
||||
// runCLI 是 cli_test.go `run` 的別名,避免與各測試內的區域變數 run 混淆。
|
||||
func runCLI(args ...string) (string, string, int) {
|
||||
return run(args...)
|
||||
}
|
||||
|
||||
// TestIssuesListReadsOpenIssuesOnly 驗證 issues list 帶 state=open 與
|
||||
// type=issues(排除 PR),輸出 JSON 陣列。
|
||||
func TestIssuesListReadsOpenIssuesOnly(t *testing.T) {
|
||||
var gotQuery string
|
||||
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
gotQuery = r.URL.RawQuery
|
||||
fmt.Fprint(w, `[{"number":8,"title":"日常操作","state":"open","user":{"login":"ceo"},"assignees":[{"login":"alex"}],"updated_at":"2026-09-10T08:13:00Z"}]`)
|
||||
})
|
||||
stdout, _, code := run("issues", "list", "--repo", "alterminal/teai")
|
||||
if code != 0 {
|
||||
t.Fatalf("issues list 應回 0,得到 %d", code)
|
||||
}
|
||||
if !strings.Contains(gotQuery, "state=open") || !strings.Contains(gotQuery, "type=issues") {
|
||||
t.Errorf("查詢參數應含 state=open 與 type=issues,得到 %q", gotQuery)
|
||||
}
|
||||
if !strings.Contains(stdout, `"number":8`) || !strings.Contains(stdout, `"author":"ceo"`) {
|
||||
t.Errorf("輸出應含 number 與 author 欄位,得到:%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIssuesListRequiresRepo 驗證 --repo 必填。
|
||||
func TestIssuesListRequiresRepo(t *testing.T) {
|
||||
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Errorf("不應發出任何請求")
|
||||
})
|
||||
_, stderr, code := run("issues", "list")
|
||||
// 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
|
||||
if code != 2 {
|
||||
t.Errorf("缺 --repo 應回 2(README 用法錯誤),得到 %d", code)
|
||||
}
|
||||
if !strings.Contains(stderr, "--repo") {
|
||||
t.Errorf("錯誤訊息應提及 --repo,得到:%s", stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIssuesViewWithComments 驗證 view --comments 連留言輸出。
|
||||
func TestIssuesViewWithComments(t *testing.T) {
|
||||
var paths []string
|
||||
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
paths = append(paths, r.URL.Path)
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/issues/8"):
|
||||
fmt.Fprint(w, `{"number":8,"title":"日常操作","state":"open","user":{"login":"ceo"},"body":"內文","html_url":"https://x/8","labels":[],"updated_at":"t"}`)
|
||||
case strings.HasSuffix(r.URL.Path, "/comments"):
|
||||
fmt.Fprint(w, `[{"body":"開始處理","created_at":"t1","user":{"login":"alex"}}]`)
|
||||
default:
|
||||
fmt.Fprint(w, `[]`)
|
||||
}
|
||||
})
|
||||
stdout, _, code := run("issues", "view", "--repo", "alterminal/teai", "--comments", "8")
|
||||
if code != 0 {
|
||||
t.Fatalf("view --comments 應回 0,得到 %d", code)
|
||||
}
|
||||
if len(paths) != 2 || !strings.HasSuffix(paths[1], "/issues/8/comments") {
|
||||
t.Errorf("應依序呼叫 issue 與 comments 端點,得到 %v", paths)
|
||||
}
|
||||
if !strings.Contains(stdout, `"body":"開始處理"`) {
|
||||
t.Errorf("輸出應含留言內容,得到:%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWriteCommandsRequireYes 驗證所有寫入命令未帶 --yes 時:
|
||||
// 回 ExitUsage 且不發出任何 HTTP 請求(issue 驗收條件)。
|
||||
func TestWriteCommandsRequireYes(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"issues create", []string{"issues", "create", "--repo", "a/b", "--title", "t"}},
|
||||
{"issues close", []string{"issues", "close", "--repo", "a/b", "1"}},
|
||||
{"issues comment", []string{"issues", "comment", "--repo", "a/b", "--body", "x", "1"}},
|
||||
{"pulls create", []string{"pulls", "create", "--repo", "a/b", "--head", "h", "--title", "t"}},
|
||||
{"pulls merge", []string{"pulls", "merge", "--repo", "a/b", "1"}},
|
||||
{"pulls comment", []string{"pulls", "comment", "--repo", "a/b", "--body", "x", "1"}},
|
||||
{"labels create", []string{"labels", "create", "--repo", "a/b", "--name", "n"}},
|
||||
{"milestones create", []string{"milestones", "create", "--repo", "a/b", "--title", "t"}},
|
||||
{"api POST", []string{"api", "--method", "POST", "/repos/a/b/issues"}},
|
||||
}
|
||||
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...)
|
||||
// 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
|
||||
if code != 2 {
|
||||
t.Errorf("%s 未帶 --yes 應回 2(README 用法錯誤),得到 %d", tc.name, code)
|
||||
}
|
||||
if !strings.Contains(stderr, "--yes") {
|
||||
t.Errorf("%s 錯誤訊息應提及 --yes,得到:%s", tc.name, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestIssuesCreateWithYes 驗證帶 --yes 時 POST 正確 payload。
|
||||
func TestIssuesCreateWithYes(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":15,"title":"新 issue","html_url":"https://x/15"}`)
|
||||
})
|
||||
stdout, _, code := run("issues", "create", "--repo", "alterminal/teai", "--title", "新 issue", "--body", "說明", "--assignees", "alex,ceo", "--yes")
|
||||
if code != 0 {
|
||||
t.Fatalf("create --yes 應回 0,得到 %d", code)
|
||||
}
|
||||
if gotMethod != "POST" || !strings.HasSuffix(gotPath, "/repos/alterminal/teai/issues") {
|
||||
t.Errorf("應 POST /repos/alterminal/teai/issues,得到 %s %s", gotMethod, gotPath)
|
||||
}
|
||||
if !strings.Contains(gotBody, `"assignees":["alex","ceo"]`) {
|
||||
t.Errorf("body 應含 assignees,得到:%s", gotBody)
|
||||
}
|
||||
if !strings.Contains(stdout, `"number":15`) {
|
||||
t.Errorf("輸出應含新 issue 編號,得到:%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPullsListAndSubcommands 驗證 pulls list 與 pulls(無子命令)可並存。
|
||||
func TestPullsListAndSubcommands(t *testing.T) {
|
||||
var gotPath string
|
||||
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
fmt.Fprint(w, `[{"number":13,"title":"PR","state":"open","user":{"login":"alex"},"head":{"ref":"feat"},"base":{"ref":"main"},"updated_at":"t"}]`)
|
||||
})
|
||||
stdout, _, code := run("pulls", "list", "--repo", "alterminal/teai")
|
||||
if code != 0 {
|
||||
t.Fatalf("pulls list 應回 0,得到 %d", code)
|
||||
}
|
||||
if !strings.HasSuffix(gotPath, "/repos/alterminal/teai/pulls") {
|
||||
t.Errorf("應呼叫 /repos/alterminal/teai/pulls,得到 %s", gotPath)
|
||||
}
|
||||
if !strings.Contains(stdout, `"head":"feat"`) || !strings.Contains(stdout, `"base":"main"`) {
|
||||
t.Errorf("輸出應含 head/base 欄位,得到:%s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLabelsMilestonesReleasesList 驗證三個清單命令打對端點並輸出。
|
||||
func TestLabelsMilestonesReleasesList(t *testing.T) {
|
||||
cases := []struct {
|
||||
args []string
|
||||
path string
|
||||
resp string
|
||||
wantOut string
|
||||
}{
|
||||
{
|
||||
args: []string{"labels", "list", "--repo", "a/b"},
|
||||
path: "/api/v1/repos/a/b/labels",
|
||||
resp: `[{"name":"enhancement","color":"#84b6eb","description":""}]`,
|
||||
wantOut: `"name":"enhancement"`,
|
||||
},
|
||||
{
|
||||
args: []string{"milestones", "list", "--repo", "a/b"},
|
||||
path: "/api/v1/repos/a/b/milestones",
|
||||
resp: `[{"title":"v1","state":"open","description":"","due_on":""}]`,
|
||||
wantOut: `"title":"v1"`,
|
||||
},
|
||||
{
|
||||
args: []string{"releases", "list", "--repo", "a/b"},
|
||||
path: "/api/v1/repos/a/b/releases",
|
||||
resp: `[{"tag_name":"v1.0.0","name":"首個發佈","draft":false,"prerelease":false,"published_at":"t"}]`,
|
||||
wantOut: `"tag_name":"v1.0.0"`,
|
||||
},
|
||||
{
|
||||
args: []string{"repos", "list", "--org", "alterminal"},
|
||||
path: "/api/v1/orgs/alterminal/repos",
|
||||
resp: `[{"full_name":"alterminal/teai","private":false,"empty":false,"updated_at":"t","html_url":"u"}]`,
|
||||
wantOut: `"full_name":"alterminal/teai"`,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(strings.Join(tc.args, " "), func(t *testing.T) {
|
||||
var gotPath string
|
||||
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
fmt.Fprint(w, tc.resp)
|
||||
})
|
||||
stdout, _, code := run(tc.args...)
|
||||
if code != 0 {
|
||||
t.Fatalf("%v 應回 0,得到 %d", tc.args, code)
|
||||
}
|
||||
if gotPath != tc.path {
|
||||
t.Errorf("應呼叫 %s,得到 %s", tc.path, gotPath)
|
||||
}
|
||||
if !strings.Contains(stdout, tc.wantOut) {
|
||||
t.Errorf("輸出應含 %s,得到:%s", tc.wantOut, stdout)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDirectPassthrough 驗證 teai api 原樣輸出、GET 免 --yes、
|
||||
// POST 未帶 --yes 被擋。
|
||||
func TestAPIDirectPassthrough(t *testing.T) {
|
||||
var gotMethod string
|
||||
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
gotMethod = r.Method
|
||||
fmt.Fprint(w, `{"version":"1.27.0"}`)
|
||||
})
|
||||
stdout, _, code := run("api", "/version")
|
||||
if code != 0 || gotMethod != "GET" {
|
||||
t.Fatalf("GET /version 應回 0,得到 %d (%s)", code, gotMethod)
|
||||
}
|
||||
if strings.TrimSpace(stdout) != `{"version":"1.27.0"}` {
|
||||
t.Errorf("api 應原樣輸出,得到:%s", stdout)
|
||||
}
|
||||
|
||||
_, stderr, code := run("api", "--method", "POST", "/version")
|
||||
// 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
|
||||
if code != 2 || !strings.Contains(stderr, "--yes") {
|
||||
t.Errorf("POST 未帶 --yes 應回 2 並提及 --yes,得到 %d:%s", code, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDirectQueryInPath 驗證 path 內含 ?query 時查詢字串正確傳遞。
|
||||
func TestAPIDirectQueryInPath(t *testing.T) {
|
||||
var gotQuery, gotPath string
|
||||
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath, gotQuery = r.URL.Path, r.URL.RawQuery
|
||||
fmt.Fprint(w, `[]`)
|
||||
})
|
||||
_, _, code := run("api", "/repos/a/b/issues?state=closed&limit=10")
|
||||
if code != 0 {
|
||||
t.Fatalf("api 帶查詢字串應回 0,得到 %d", code)
|
||||
}
|
||||
if gotPath != "/api/v1/repos/a/b/issues" || gotQuery != "state=closed&limit=10" {
|
||||
t.Errorf("應剝離查詢字串,得到 path=%s query=%s", gotPath, gotQuery)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIssuesCommentPostsBody 驗證 comment --yes 送出 body。
|
||||
func TestIssuesCommentPostsBody(t *testing.T) {
|
||||
var gotPath, gotBody string
|
||||
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
buf := make([]byte, 512)
|
||||
n, _ := r.Body.Read(buf)
|
||||
gotPath, gotBody = r.URL.Path, string(buf[:n])
|
||||
fmt.Fprint(w, `{"body":"留言","created_at":"t","user":{"login":"alex"}}`)
|
||||
})
|
||||
_, _, code := run("issues", "comment", "--repo", "alterminal/teai", "--body", "留言", "--yes", "8")
|
||||
if code != 0 {
|
||||
t.Fatalf("comment --yes 應回 0,得到 %d", code)
|
||||
}
|
||||
if !strings.HasSuffix(gotPath, "/issues/8/comments") || !strings.Contains(gotBody, `"body":"留言"`) {
|
||||
t.Errorf("應 POST comments 端點帶 body,得到 %s %s", gotPath, gotBody)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractGlobalsAllowsCommandFlags 驗證命令旗標與全域選項可交錯。
|
||||
func TestExtractGlobalsAllowsCommandFlags(t *testing.T) {
|
||||
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, `{"login":"alex"}`)
|
||||
})
|
||||
stdout, _, code := run("whoami", "--output", "table")
|
||||
if code != 0 {
|
||||
t.Fatalf("whoami --output table 應回 0,得到 %d", code)
|
||||
}
|
||||
if !strings.Contains(stdout, "alex") {
|
||||
t.Errorf("table 輸出應含 alex,得到:%s", stdout)
|
||||
}
|
||||
}
|
||||
+116
-15
@@ -10,20 +10,22 @@ import (
|
||||
)
|
||||
|
||||
func TestExitCodeMapping(t *testing.T) {
|
||||
// want 直接寫 README「輸出與結束碼」的數值(0/2/3;內部錯誤 1),
|
||||
// 不以常數互比,避免常數與規格再次脫鉤(#10)。
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want ExitCode
|
||||
want int
|
||||
}{
|
||||
{"usage error", &ErrUsage{Msg: "bad flag"}, ExitUsage},
|
||||
{"api error 401", &gitea.ErrAPI{StatusCode: 401, Op: "GET /api/v1/user"}, ExitAPI},
|
||||
{"api error transport", &gitea.ErrAPI{Op: "GET /api/v1/user", Err: errString("dial tcp")}, ExitAPI},
|
||||
{"wrapped api error", wrapped(&gitea.ErrAPI{StatusCode: 500}), ExitAPI},
|
||||
{"other error", errString("boom"), ExitInternal},
|
||||
{"nil maps to OK", nil, ExitOK},
|
||||
{"usage error", &ErrUsage{Msg: "bad flag"}, 2},
|
||||
{"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")}, 3},
|
||||
{"wrapped api error", wrapped(&gitea.ErrAPI{StatusCode: 500}), 3},
|
||||
{"other error", errString("boom"), 1},
|
||||
{"nil maps to OK", nil, 0},
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -68,16 +70,16 @@ func TestRunExitCodes(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestParseGlobals(t *testing.T) {
|
||||
func TestExtractGlobals(t *testing.T) {
|
||||
g := defaultGlobals()
|
||||
rest, err := parseGlobals(&g, []string{
|
||||
rest, err := extractGlobals(&g, []string{
|
||||
"--url", "https://example.com",
|
||||
"--token=tok",
|
||||
"--config", "/tmp/c.yml",
|
||||
"--output", "table",
|
||||
"--timeout", "45s",
|
||||
"next",
|
||||
})
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -95,16 +97,115 @@ func TestParseGlobals(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGlobalsStopsAtCommand(t *testing.T) {
|
||||
func TestExtractGlobalsAfterCommand(t *testing.T) {
|
||||
// 全域選項出現在命令之後也應抽出(README:teai next --output table)。
|
||||
g := defaultGlobals()
|
||||
rest, err := parseGlobals(&g, []string{"version", "--output", "table"})
|
||||
rest, err := extractGlobals(&g, []string{"version", "--output", "table"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 命令之後的選項屬於命令,不屬於全域。
|
||||
if len(rest) != 3 || rest[0] != "version" {
|
||||
if len(rest) != 1 || 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)
|
||||
}
|
||||
if g.Output != gitea.FormatTable {
|
||||
t.Fatalf("output = %v, want table", g.Output)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractGlobalsReservedFlags 驗證 #18:與全域同名的命令旗標
|
||||
// (登記於 commandReservedFlags)必須留給命令,其餘全域選項照常抽取。
|
||||
func TestExtractGlobalsReservedFlags(t *testing.T) {
|
||||
g := defaultGlobals()
|
||||
rest, err := extractGlobals(&g, []string{
|
||||
"add",
|
||||
"--url", "https://srv.example.com", // login add 自有旗標:保留
|
||||
"--token=tok", // 同上(inline 形式):保留
|
||||
"--name", "test-site",
|
||||
"--output", "table", // 非保留:仍是全域
|
||||
}, reservedFlags("login"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"add", "--url", "https://srv.example.com", "--token=tok", "--name", "test-site"}
|
||||
if len(rest) != len(want) {
|
||||
t.Fatalf("rest = %v, want %v", rest, want)
|
||||
}
|
||||
for i := range want {
|
||||
if rest[i] != want[i] {
|
||||
t.Fatalf("rest = %v, want %v", rest, want)
|
||||
}
|
||||
}
|
||||
if g.Output != gitea.FormatTable {
|
||||
t.Fatalf("output = %v, want table", g.Output)
|
||||
}
|
||||
if g.URL != defaultGlobals().URL || g.Token != "" {
|
||||
t.Fatalf("reserved flags must not leak into globals: %+v", g)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractGlobalsNonReservedCommand 驗證 #13 行為不回歸:未登記保留
|
||||
// 旗標的命令(如 next/members/pulls),命令後的全域選項照常抽取、
|
||||
// 命令自己的旗標(--has-work 等)原樣保留。
|
||||
func TestExtractGlobalsNonReservedCommand(t *testing.T) {
|
||||
g := defaultGlobals()
|
||||
rest, err := extractGlobals(&g, []string{
|
||||
"members", "--has-work", "--output", "table",
|
||||
}, reservedFlags("members"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rest) != 2 || rest[0] != "members" || rest[1] != "--has-work" {
|
||||
t.Fatalf("rest = %v, want [members --has-work]", rest)
|
||||
}
|
||||
if g.Output != gitea.FormatTable {
|
||||
t.Fatalf("output = %v, want table", g.Output)
|
||||
}
|
||||
}
|
||||
|
||||
// errString 把字串轉成 error(測試輔助)。
|
||||
|
||||
@@ -145,8 +145,9 @@ func TestLoginAddRejected401NoWrite(t *testing.T) {
|
||||
`)
|
||||
_, stderr, code := run(append(prefix,
|
||||
"--url", srv.URL, "login", "add", "--token", "bad-tok")...)
|
||||
if code != int(ExitAPI) {
|
||||
t.Fatalf("401 should exit 3, got %d (stderr %s)", code, stderr)
|
||||
// 401 是 API 錯誤;對照 README「輸出與結束碼」=3(#10)。
|
||||
if code != 3 {
|
||||
t.Fatalf("401 should exit 3 (README api error), got %d (stderr %s)", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stderr, "401") {
|
||||
t.Fatalf("stderr should mention 401: %s", stderr)
|
||||
@@ -250,8 +251,9 @@ func TestLoginRemoveAsksConfirmation(t *testing.T) {
|
||||
func TestLoginUnknownSubcommandUsage(t *testing.T) {
|
||||
prefix, _ := loginTestEnv(t, "")
|
||||
_, stderr, code := run(append(prefix, "login", "bogus")...)
|
||||
if code != int(ExitUsage) {
|
||||
t.Fatalf("want exit 2, got %d", code)
|
||||
// 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
|
||||
if code != 2 {
|
||||
t.Fatalf("want exit 2 (README usage), got %d", code)
|
||||
}
|
||||
if !strings.Contains(stderr, "unknown login subcommand") {
|
||||
t.Fatalf("stderr: %s", stderr)
|
||||
@@ -261,8 +263,9 @@ func TestLoginUnknownSubcommandUsage(t *testing.T) {
|
||||
func TestLoginNoSubcommandUsage(t *testing.T) {
|
||||
prefix, _ := loginTestEnv(t, "")
|
||||
_, stderr, code := run(append(prefix, "login")...)
|
||||
if code != int(ExitUsage) {
|
||||
t.Fatalf("want exit 2, got %d", code)
|
||||
// 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
|
||||
if code != 2 {
|
||||
t.Fatalf("want exit 2 (README usage), got %d", code)
|
||||
}
|
||||
if !strings.Contains(stderr, "subcommand") {
|
||||
t.Fatalf("stderr: %s", stderr)
|
||||
@@ -272,8 +275,9 @@ func TestLoginNoSubcommandUsage(t *testing.T) {
|
||||
func TestLoginRemoveNotFound(t *testing.T) {
|
||||
prefix, _ := loginTestEnv(t, "logins: []\n")
|
||||
_, stderr, code := run(append(prefix, "login", "remove", "--yes", "ghost")...)
|
||||
if code != int(ExitInternal) {
|
||||
t.Fatalf("want exit 1, got %d", code)
|
||||
// ExitInternal 不在 README 保證範圍;此處固定為 1(內部錯誤,#10)。
|
||||
if code != 1 {
|
||||
t.Fatalf("want exit 1 (internal), got %d", code)
|
||||
}
|
||||
if !strings.Contains(stderr, `login "ghost" not found`) {
|
||||
t.Fatalf("stderr: %s", stderr)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// 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) 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
// workflow_commands.go — gitea.py 工作流命令的 CLI 接線(#6):
|
||||
// whoami、orgs、members [--has-work]、mine、pulls [--mine|--reviewer] [--repo]、next。
|
||||
//
|
||||
// 輸出走 internal/gitea 的 Printer(--output json|table);錯誤經 cli.exitCodeFor
|
||||
// 映射結束碼(用法 2/API 3)。token 解析選序見 internal/gitea/auth.go。
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"gitea.alterminal.com/alterminal/teai/internal/gitea"
|
||||
"gitea.alterminal.com/alterminal/teai/internal/workflow"
|
||||
)
|
||||
|
||||
func init() {
|
||||
register := func(c *command) {
|
||||
commands[c.name] = c
|
||||
}
|
||||
register(&command{name: "whoami", usage: "目前帳號", run: runWhoami})
|
||||
register(&command{name: "orgs", usage: "我所屬的組織", run: runOrgs})
|
||||
register(&command{name: "members", usage: "Agents 團隊成員;--has-work 只列有未完成工作者", run: runMembers})
|
||||
register(&command{name: "mine", usage: "分派給我、待跟進的 issues", run: runMine})
|
||||
// pulls 由 dailyops_commands.go 註冊(#8):無子命令時走本檔的 runPulls
|
||||
// 工作流清單,有子命令(list/view/create/merge/comment)走日常操作。
|
||||
register(&command{name: "next", usage: "下一件該做的事", run: runNext})
|
||||
}
|
||||
|
||||
// errNoRepoFlag 是 --repo 值格式錯誤。
|
||||
var errNoRepoFlag = errors.New("--repo 需為 owner/repo 形式")
|
||||
|
||||
// newScannerFunc 建立工作流 Scanner;正式環境用 API client。
|
||||
// 宣告為變數讓接線層測試可注入假 client(不走網路),
|
||||
// 彌補 workflow 套件單元測試覆蓋不到 CLI 分派路徑的缺口。
|
||||
var newScannerFunc = newWorkflowClient
|
||||
|
||||
// newWorkflowClient 依全域選項建立 workflow 所需的 API client。
|
||||
func newWorkflowClient(env *Env) (*workflow.Scanner, 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.Scanner{Client: &workflow.APIClient{Client: client}}, nil
|
||||
}
|
||||
|
||||
// printer 依全域選項建立輸出器。
|
||||
func printer(env *Env) gitea.Printer {
|
||||
return gitea.Printer{Format: env.Globals.Output, Out: env.Out}
|
||||
}
|
||||
|
||||
// runWhoami:teai whoami。
|
||||
func runWhoami(env *Env, args []string) error {
|
||||
if len(args) != 0 {
|
||||
return &ErrUsage{Msg: "whoami 不接受參數"}
|
||||
}
|
||||
s, err := newScannerFunc(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name, err := s.Whoami()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printer(env).PrintOne(
|
||||
[]gitea.Field{{Name: "username"}},
|
||||
gitea.Values{name},
|
||||
)
|
||||
}
|
||||
|
||||
// runOrgs:teai orgs。
|
||||
func runOrgs(env *Env, args []string) error {
|
||||
if len(args) != 0 {
|
||||
return &ErrUsage{Msg: "orgs 不接受參數"}
|
||||
}
|
||||
s, err := newScannerFunc(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
orgs, err := s.Orgs()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows := make([]gitea.Values, 0, len(orgs))
|
||||
for _, o := range orgs {
|
||||
rows = append(rows, gitea.Values{o})
|
||||
}
|
||||
return printer(env).PrintList(
|
||||
[]gitea.Field{{Name: "username"}},
|
||||
rows,
|
||||
)
|
||||
}
|
||||
|
||||
// runMembers:teai members [--has-work]。輸出每行一個帳號(同 gitea.py)。
|
||||
func runMembers(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai members", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
hasWork := fs.Bool("has-work", false, "只列出有未完成工作的成員")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return &ErrUsage{Msg: err.Error()}
|
||||
}
|
||||
if fs.NArg() != 0 {
|
||||
return &ErrUsage{Msg: "members 不接受位置參數"}
|
||||
}
|
||||
s, err := newScannerFunc(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
names, err := s.Members(*hasWork)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// gitea.py members 每行輸出一個帳號(非 JSON);保持一致以便交叉驗證。
|
||||
for _, name := range names {
|
||||
fmt.Fprintln(env.Out, name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// runMine:teai mine。
|
||||
func runMine(env *Env, args []string) error {
|
||||
if len(args) != 0 {
|
||||
return &ErrUsage{Msg: "mine 不接受參數"}
|
||||
}
|
||||
s, err := newScannerFunc(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
issues, err := s.Mine()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return printer(env).PrintList(
|
||||
[]gitea.Field{
|
||||
{Name: "repo"}, {Name: "number"}, {Name: "title"}, {Name: "url"},
|
||||
},
|
||||
issueRows(issues),
|
||||
)
|
||||
}
|
||||
|
||||
// runPulls:teai pulls [--mine|--reviewer] [--repo owner/repo]。
|
||||
func runPulls(env *Env, args []string) error {
|
||||
fs := flag.NewFlagSet("teai pulls", flag.ContinueOnError)
|
||||
fs.SetOutput(env.Err)
|
||||
mine := fs.Bool("mine", false, "限定作者是目前帳號")
|
||||
reviewer := fs.Bool("reviewer", false, "限定自己是 requested reviewer")
|
||||
repo := fs.String("repo", "", "限定單一倉庫(owner/repo)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return &ErrUsage{Msg: err.Error()}
|
||||
}
|
||||
if fs.NArg() != 0 {
|
||||
return &ErrUsage{Msg: "pulls 不接受位置參數"}
|
||||
}
|
||||
if *mine && *reviewer {
|
||||
return &ErrUsage{Msg: "--mine 與 --reviewer 不能併用"}
|
||||
}
|
||||
var owner, name string
|
||||
if *repo != "" {
|
||||
parts := strings.SplitN(*repo, "/", 2)
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return &ErrUsage{Msg: errNoRepoFlag.Error()}
|
||||
}
|
||||
owner, name = parts[0], parts[1]
|
||||
}
|
||||
s, err := newScannerFunc(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, err := s.Pulls(*mine, *reviewer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows := make([]gitea.Values, 0, len(items))
|
||||
for _, item := range items {
|
||||
if *repo != "" && (item.Owner != owner || item.Repo != name) {
|
||||
continue
|
||||
}
|
||||
rows = append(rows, gitea.Values{
|
||||
item.Owner + "/" + item.Repo,
|
||||
item.Pull.Number,
|
||||
item.Pull.Title,
|
||||
item.Pull.WebURL(),
|
||||
})
|
||||
}
|
||||
return printer(env).PrintList(
|
||||
[]gitea.Field{
|
||||
{Name: "repo"}, {Name: "number"}, {Name: "title"}, {Name: "url"},
|
||||
},
|
||||
rows,
|
||||
)
|
||||
}
|
||||
|
||||
// runNext:teai next。無工作輸出 null(exit 0)。
|
||||
func runNext(env *Env, args []string) error {
|
||||
if len(args) != 0 {
|
||||
return &ErrUsage{Msg: "next 不接受參數"}
|
||||
}
|
||||
s, err := newScannerFunc(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
work, err := s.Next()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p := printer(env)
|
||||
if work == nil {
|
||||
return p.PrintNull()
|
||||
}
|
||||
// gitea.py 的 _work_dict:role 僅 pull 帶(issue 不輸出 role 欄位)。
|
||||
fields := []gitea.Field{
|
||||
{Name: "type"}, {Name: "role"}, {Name: "repo"},
|
||||
{Name: "number"}, {Name: "title"}, {Name: "url"},
|
||||
}
|
||||
row := gitea.Values{work.Type, work.Role, work.Repo, work.Number, work.Title, work.URL}
|
||||
if work.Role == "" {
|
||||
fields = []gitea.Field{
|
||||
{Name: "type"}, {Name: "repo"},
|
||||
{Name: "number"}, {Name: "title"}, {Name: "url"},
|
||||
}
|
||||
row = gitea.Values{work.Type, work.Repo, work.Number, work.Title, work.URL}
|
||||
}
|
||||
return p.PrintOne(fields, row)
|
||||
}
|
||||
|
||||
// issueRows 把 issues 轉成輸出列(repo 欄位由掃描脈絡補齊)。
|
||||
func issueRows(issues []workflow.Issue) []gitea.Values {
|
||||
rows := make([]gitea.Values, 0, len(issues))
|
||||
for i := range issues {
|
||||
issue := &issues[i]
|
||||
rows = append(rows, gitea.Values{
|
||||
issue.FullName(),
|
||||
issue.Num(),
|
||||
issue.Title,
|
||||
issue.WebURL(),
|
||||
})
|
||||
}
|
||||
return rows
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
// Package dailyops 實作 tea 對等的日常操作(#8):issues、pulls、labels、
|
||||
// milestones、releases、repos 的讀寫,直接以 Gitea API 為準。
|
||||
//
|
||||
// 讀寫行為對照 Gitea 1.27 API(issues 端點帶 type=issues 排除 PR,
|
||||
// 見 gitea.py 的注意事項);寫入的「--yes 閘門」在 CLI 層(見
|
||||
// dailyops_commands.go),本套件只負責 API 呼叫。
|
||||
package dailyops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"gitea.alterminal.com/alterminal/teai/internal/gitea"
|
||||
)
|
||||
|
||||
// User 是 API 回應中的使用者精簡欄位。
|
||||
type User struct {
|
||||
UserName string `json:"login"`
|
||||
}
|
||||
|
||||
// Name 回傳帳號名。
|
||||
func (u *User) Name() string {
|
||||
if u == nil {
|
||||
return ""
|
||||
}
|
||||
return u.UserName
|
||||
}
|
||||
|
||||
// Issue 是 Gitea issue/PR 共用端點的精簡欄位(PR 亦走 issues 端點)。
|
||||
type Issue struct {
|
||||
Number int64 `json:"number"`
|
||||
Title string `json:"title"`
|
||||
State string `json:"state"`
|
||||
Body string `json:"body"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
User *User `json:"user"`
|
||||
Assignees []*User `json:"assignees"`
|
||||
Labels []Label `json:"labels"`
|
||||
Assignee []string `json:"-"` // 輸出用:帳號清單(由 Assignees 導出)
|
||||
}
|
||||
|
||||
// Author 回傳建立者帳號。
|
||||
func (i *Issue) Author() string { return i.User.Name() }
|
||||
|
||||
// AssigneeNames 回傳 assignees 帳號清單(輸出用)。
|
||||
func (i *Issue) AssigneeNames() []string {
|
||||
names := make([]string, 0, len(i.Assignees))
|
||||
for _, a := range i.Assignees {
|
||||
if n := a.Name(); n != "" {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// LabelNames 回傳標籤名稱清單(輸出用)。
|
||||
func (i *Issue) LabelNames() []string {
|
||||
names := make([]string, 0, len(i.Labels))
|
||||
for _, l := range i.Labels {
|
||||
names = append(names, l.Name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// Label 是倉庫標籤。
|
||||
type Label struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Color string `json:"color"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// Milestone 是倉庫里程碑。
|
||||
type Milestone struct {
|
||||
ID int64 `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
State string `json:"state"`
|
||||
DueOn string `json:"due_on"`
|
||||
}
|
||||
|
||||
// Release 是倉庫發佈。
|
||||
type Release struct {
|
||||
TagName string `json:"tag_name"`
|
||||
Name string `json:"name"`
|
||||
Draft bool `json:"draft"`
|
||||
Prerelease bool `json:"prerelease"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
PublishedAt string `json:"published_at"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
}
|
||||
|
||||
// Comment 是 issue/PR 留言。
|
||||
type Comment struct {
|
||||
Body string `json:"body"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
User *User `json:"user"`
|
||||
}
|
||||
|
||||
// Author 回串留言者帳號。
|
||||
func (c *Comment) Author() string { return c.User.Name() }
|
||||
|
||||
// Pull 是 pull request 的精簡欄位。
|
||||
type Pull struct {
|
||||
Number int64 `json:"number"`
|
||||
Title string `json:"title"`
|
||||
State string `json:"state"`
|
||||
Body string `json:"body"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
User *User `json:"user"`
|
||||
Head *pullRef `json:"head"`
|
||||
Base *pullRef `json:"base"`
|
||||
}
|
||||
|
||||
// pullRef 是 PR 的 head/base 參照。
|
||||
type pullRef struct {
|
||||
Ref string `json:"ref"`
|
||||
Repo *struct {
|
||||
FullName string `json:"full_name"`
|
||||
} `json:"repo"`
|
||||
}
|
||||
|
||||
// HeadRef 回傳 head 分支名(輸出用)。
|
||||
func (p *Pull) HeadRef() string {
|
||||
if p.Head == nil {
|
||||
return ""
|
||||
}
|
||||
return p.Head.Ref
|
||||
}
|
||||
|
||||
// BaseRef 回傳 base 分支名(輸出用)。
|
||||
func (p *Pull) BaseRef() string {
|
||||
if p.Base == nil {
|
||||
return ""
|
||||
}
|
||||
return p.Base.Ref
|
||||
}
|
||||
|
||||
// Author 回傳 PR 作者帳號。
|
||||
func (p *Pull) Author() string { return p.User.Name() }
|
||||
|
||||
// Repo 是倉庫的精簡欄位。
|
||||
type Repo struct {
|
||||
FullName string `json:"full_name"`
|
||||
Description string `json:"description"`
|
||||
Private bool `json:"private"`
|
||||
Empty bool `json:"empty"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
}
|
||||
|
||||
// Ops 聚合日常操作的 API 呼叫。
|
||||
type Ops struct {
|
||||
// Client 是 Gitea API 用戶端(internal/gitea)。
|
||||
Client *gitea.Client
|
||||
}
|
||||
|
||||
// repoPath 組出 /repos/{owner}/{repo} 前綴;owner/repo 皆做路徑跳脫。
|
||||
func repoPath(owner, repo string) string {
|
||||
return "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo)
|
||||
}
|
||||
|
||||
// ListIssues 列出倉庫 issues。state:open|closed|all(預設 open);
|
||||
// type=issues 排除 PR(Gitea 的 issues 端點會連 PR 一起回)。
|
||||
func (o *Ops) ListIssues(ctx context.Context, owner, repo, state string) ([]Issue, error) {
|
||||
if state == "" {
|
||||
state = "open"
|
||||
}
|
||||
extra := url.Values{}
|
||||
if state != "all" {
|
||||
extra.Set("state", state)
|
||||
}
|
||||
// type=issues:排除 PR(PR 在此端點帶 pull_request 欄位)。
|
||||
extra.Set("type", "issues")
|
||||
var issues []Issue
|
||||
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/issues", gitea.ListOptions{Extra: extra}, &issues); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return issues, nil
|
||||
}
|
||||
|
||||
// CreateIssue 建立 issue;assignees 可為空。
|
||||
func (o *Ops) CreateIssue(ctx context.Context, owner, repo, title, body string, assignees []string) (*Issue, error) {
|
||||
payload := map[string]any{
|
||||
"title": title,
|
||||
"body": body,
|
||||
}
|
||||
if len(assignees) > 0 {
|
||||
payload["assignees"] = assignees
|
||||
}
|
||||
var issue Issue
|
||||
if err := o.Client.DoJSON(ctx, "POST", repoPath(owner, repo)+"/issues", "", payload, &issue); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &issue, nil
|
||||
}
|
||||
|
||||
// GetIssue 取得單一 issue(含 PR,但此處供 issues view 用)。
|
||||
func (o *Ops) GetIssue(ctx context.Context, owner, repo string, number int64) (*Issue, error) {
|
||||
var issue Issue
|
||||
path := repoPath(owner, repo) + "/issues/" + strconv.FormatInt(number, 10)
|
||||
if err := o.Client.GetJSON(ctx, path, &issue); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &issue, nil
|
||||
}
|
||||
|
||||
// SetIssueState 變更 issue 狀態(open|closed)。
|
||||
func (o *Ops) SetIssueState(ctx context.Context, owner, repo string, number int64, state string) (*Issue, error) {
|
||||
payload := map[string]any{"state": state}
|
||||
var issue Issue
|
||||
path := repoPath(owner, repo) + "/issues/" + strconv.FormatInt(number, 10)
|
||||
if err := o.Client.DoJSON(ctx, "PATCH", path, "", payload, &issue); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &issue, nil
|
||||
}
|
||||
|
||||
// ListComments 列出 issue/PR 的留言(PR 亦走 issues 端點)。
|
||||
func (o *Ops) ListComments(ctx context.Context, owner, repo string, number int64) ([]Comment, error) {
|
||||
var comments []Comment
|
||||
path := repoPath(owner, repo) + "/issues/" + strconv.FormatInt(number, 10) + "/comments"
|
||||
if err := o.Client.ListAll(ctx, path, gitea.ListOptions{}, &comments); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return comments, nil
|
||||
}
|
||||
|
||||
// AddComment 對 issue/PR 留言。
|
||||
func (o *Ops) AddComment(ctx context.Context, owner, repo string, number int64, body string) (*Comment, error) {
|
||||
payload := map[string]any{"body": body}
|
||||
var comment Comment
|
||||
path := repoPath(owner, repo) + "/issues/" + strconv.FormatInt(number, 10) + "/comments"
|
||||
if err := o.Client.DoJSON(ctx, "POST", path, "", payload, &comment); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &comment, nil
|
||||
}
|
||||
|
||||
// ListPulls 列出倉庫 PR;state 預設 open。
|
||||
func (o *Ops) ListPulls(ctx context.Context, owner, repo, state string) ([]Pull, error) {
|
||||
if state == "" {
|
||||
state = "open"
|
||||
}
|
||||
extra := url.Values{}
|
||||
if state != "all" {
|
||||
extra.Set("state", state)
|
||||
}
|
||||
var pulls []Pull
|
||||
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/pulls", gitea.ListOptions{Extra: extra}, &pulls); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pulls, nil
|
||||
}
|
||||
|
||||
// GetPull 取得單一 PR。
|
||||
func (o *Ops) GetPull(ctx context.Context, owner, repo string, number int64) (*Pull, error) {
|
||||
var pull Pull
|
||||
path := repoPath(owner, repo) + "/pulls/" + strconv.FormatInt(number, 10)
|
||||
if err := o.Client.GetJSON(ctx, path, &pull); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pull, nil
|
||||
}
|
||||
|
||||
// CreatePull 建立 PR。
|
||||
func (o *Ops) CreatePull(ctx context.Context, owner, repo, title, body, head, base string) (*Pull, error) {
|
||||
payload := map[string]any{
|
||||
"title": title,
|
||||
"body": body,
|
||||
"head": head,
|
||||
"base": base,
|
||||
}
|
||||
var pull Pull
|
||||
if err := o.Client.DoJSON(ctx, "POST", repoPath(owner, repo)+"/pulls", "", payload, &pull); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pull, nil
|
||||
}
|
||||
|
||||
// MergePull 合併 PR。style:merge|rebase|rebase-merge|squash(預設 merge)。
|
||||
func (o *Ops) MergePull(ctx context.Context, owner, repo string, number int64, style string) error {
|
||||
if style == "" {
|
||||
style = "merge"
|
||||
}
|
||||
payload := map[string]any{"Do": style}
|
||||
path := repoPath(owner, repo) + "/pulls/" + strconv.FormatInt(number, 10) + "/merge"
|
||||
return o.Client.DoJSON(ctx, "POST", path, "", payload, nil)
|
||||
}
|
||||
|
||||
// ListLabels 列出倉庫標籤。
|
||||
func (o *Ops) ListLabels(ctx context.Context, owner, repo string) ([]Label, error) {
|
||||
var labels []Label
|
||||
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/labels", gitea.ListOptions{}, &labels); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return labels, nil
|
||||
}
|
||||
|
||||
// CreateLabel 建立標籤;color 格式如 #ffffff。
|
||||
func (o *Ops) CreateLabel(ctx context.Context, owner, repo, name, color, description string) (*Label, error) {
|
||||
payload := map[string]any{
|
||||
"name": name,
|
||||
"color": color,
|
||||
"description": description,
|
||||
}
|
||||
var label Label
|
||||
if err := o.Client.DoJSON(ctx, "POST", repoPath(owner, repo)+"/labels", "", payload, &label); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &label, nil
|
||||
}
|
||||
|
||||
// ListMilestones 列出倉庫里程碑;state 預設 open(可用 all)。
|
||||
func (o *Ops) ListMilestones(ctx context.Context, owner, repo, state string) ([]Milestone, error) {
|
||||
if state == "" {
|
||||
state = "open"
|
||||
}
|
||||
extra := url.Values{}
|
||||
if state != "all" {
|
||||
extra.Set("state", state)
|
||||
}
|
||||
var ms []Milestone
|
||||
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/milestones", gitea.ListOptions{Extra: extra}, &ms); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ms, nil
|
||||
}
|
||||
|
||||
// CreateMilestone 建立里程碑;dueOn 可空(RFC3339)。
|
||||
func (o *Ops) CreateMilestone(ctx context.Context, owner, repo, title, description, dueOn string) (*Milestone, error) {
|
||||
payload := map[string]any{
|
||||
"title": title,
|
||||
"description": description,
|
||||
}
|
||||
if dueOn != "" {
|
||||
payload["due_on"] = dueOn
|
||||
}
|
||||
var m Milestone
|
||||
if err := o.Client.DoJSON(ctx, "POST", repoPath(owner, repo)+"/milestones", "", payload, &m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// ListReleases 列出倉庫發佈。
|
||||
func (o *Ops) ListReleases(ctx context.Context, owner, repo string) ([]Release, error) {
|
||||
var releases []Release
|
||||
if err := o.Client.ListAll(ctx, repoPath(owner, repo)+"/releases", gitea.ListOptions{}, &releases); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return releases, nil
|
||||
}
|
||||
|
||||
// ListMyRepos 列出自己可存取的倉庫。
|
||||
func (o *Ops) ListMyRepos(ctx context.Context) ([]Repo, error) {
|
||||
var repos []Repo
|
||||
if err := o.Client.ListAll(ctx, "/user/repos", gitea.ListOptions{}, &repos); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return repos, nil
|
||||
}
|
||||
|
||||
// ListOrgRepos 列出組織倉庫。
|
||||
func (o *Ops) ListOrgRepos(ctx context.Context, org string) ([]Repo, error) {
|
||||
var repos []Repo
|
||||
if err := o.Client.ListAll(ctx, "/orgs/"+url.PathEscape(org)+"/repos", gitea.ListOptions{}, &repos); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return repos, nil
|
||||
}
|
||||
|
||||
// CallAPIDirect 是 teai api 的原樣傳遞:以指定動詞呼叫 path(相對 /api/v1),
|
||||
// data 為原樣 JSON(可為 nil)。回傳原始回應位元組。
|
||||
func (o *Ops) CallAPIDirect(ctx context.Context, method, path, rawQuery string, data []byte) ([]byte, error) {
|
||||
if path == "" || path[0] != '/' {
|
||||
return nil, fmt.Errorf("api path 必須以 / 開頭(相對 api/v1)")
|
||||
}
|
||||
return o.Client.DoRaw(ctx, method, path, rawQuery, data)
|
||||
}
|
||||
+55
-10
@@ -7,6 +7,7 @@
|
||||
package gitea
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -79,36 +80,80 @@ const MaxLimit = 50
|
||||
// getJSON 對 path(相對 baseURL,以 / 開頭)發 GET,把 JSON 回應解到 out。
|
||||
// 失敗時回傳 *ErrAPI。rawQuery 為組好的查詢字串(見 ListOptions.query)。
|
||||
func (c *Client) getJSON(ctx context.Context, path, rawQuery string, out any) error {
|
||||
_, err := c.do(ctx, http.MethodGet, path, rawQuery, "", nil, out)
|
||||
return err
|
||||
}
|
||||
|
||||
// DoJSON 對 path 發 method 請求(POST/PATCH/PUT/DELETE…),body 為可 JSON
|
||||
// 化的值(nil 表示不帶 body),2xx 時把回應解到 out(out 非 nil 且回應
|
||||
// 有內容時)。供寫入類操作(issues create、pulls merge…)使用。
|
||||
func (c *Client) DoJSON(ctx context.Context, method, path, rawQuery string, body any, out any) error {
|
||||
var payload []byte
|
||||
if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("gitea: marshal request body: %w", err)
|
||||
}
|
||||
payload = b
|
||||
}
|
||||
_, err := c.do(ctx, method, path, rawQuery, "application/json", payload, out)
|
||||
return err
|
||||
}
|
||||
|
||||
// DoRaw 以原樣 body 送出請求並回傳原始回應內容(teai api 用)。
|
||||
// 非 2xx 回 *ErrAPI。
|
||||
func (c *Client) DoRaw(ctx context.Context, method, path, rawQuery string, body []byte) ([]byte, error) {
|
||||
contentType := ""
|
||||
if body != nil {
|
||||
contentType = "application/json"
|
||||
}
|
||||
return c.do(ctx, method, path, rawQuery, contentType, body, nil)
|
||||
}
|
||||
|
||||
// do 是所有請求的共同核心:組 URL、帶認證表頭、送出、檢查狀態碼、
|
||||
// 解析回應。2xx 時回傳原始回應位元組;out 非 nil 時另解到 out。
|
||||
// 錯誤訊息不含 token 或回應內容。
|
||||
func (c *Client) do(ctx context.Context, method, path, rawQuery, contentType string, payload []byte, out any) ([]byte, error) {
|
||||
u := *c.baseURL
|
||||
u.Path += path
|
||||
u.RawQuery = rawQuery
|
||||
op := "GET " + u.Path
|
||||
op := method + " " + u.Path
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
||||
var body io.Reader
|
||||
if payload != nil {
|
||||
body = bytes.NewReader(payload)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, u.String(), body)
|
||||
if err != nil {
|
||||
return &ErrAPI{Op: op, Err: err}
|
||||
return nil, &ErrAPI{Op: op, Err: err}
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if payload != nil && contentType != "" {
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "token "+c.token)
|
||||
}
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return &ErrAPI{Op: op, Err: err}
|
||||
return nil, &ErrAPI{Op: op, Err: err}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
// 把內容讀掉再丟棄,讓連線可重用;錯誤訊息不含回應內容。
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
return &ErrAPI{Op: op, StatusCode: resp.StatusCode}
|
||||
return nil, &ErrAPI{Op: op, StatusCode: resp.StatusCode}
|
||||
}
|
||||
if out == nil {
|
||||
return nil
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, &ErrAPI{Op: op, Err: err}
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
|
||||
return &ErrAPI{Op: op, Err: fmt.Errorf("decode response: %w", err)}
|
||||
if out != nil && len(data) > 0 {
|
||||
if err := json.Unmarshal(data, out); err != nil {
|
||||
return nil, &ErrAPI{Op: op, Err: fmt.Errorf("decode response: %w", err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// GetJSON 是 getJSON 的公開介面,供非清單端點(如 /user)使用。
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
// giteaapi.go — 以 internal/gitea 的 HTTP 用戶端實作 workflow.Client。
|
||||
//
|
||||
// 端點與查詢參數對照 gitea.py:清單一律帶 limit 分頁(ListAll 固定 50);
|
||||
// issues 端點帶 type=issues(排除 PR)與 state=open;pulls 帶 state=open。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"gitea.alterminal.com/alterminal/teai/internal/gitea"
|
||||
)
|
||||
|
||||
// errNoUsername 表示 /user 回應中找不到帳號名(伺服端回應異常)。
|
||||
var errNoUsername = errors.New("gitea: GET /user: response has no username")
|
||||
|
||||
// APIClient 是 Client 介面的 HTTP 實作,包裝 internal/gitea.Client。
|
||||
type APIClient struct {
|
||||
Client *gitea.Client
|
||||
}
|
||||
|
||||
// 確認 APIClient 實作 Client 介面(編譯期檢查)。
|
||||
var _ Client = (*APIClient)(nil)
|
||||
|
||||
func (a *APIClient) CurrentUser() (string, error) {
|
||||
var u User
|
||||
if err := a.Client.GetJSON(context.Background(), "/user", &u); err != nil {
|
||||
return "", err
|
||||
}
|
||||
name := u.Name()
|
||||
if name == "" {
|
||||
return "", errNoUsername
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
func (a *APIClient) ListOrgs() ([]string, error) {
|
||||
var orgs []Org
|
||||
if err := a.Client.ListAll(context.Background(), "/user/orgs", gitea.ListOptions{}, &orgs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names := make([]string, 0, len(orgs))
|
||||
for _, o := range orgs {
|
||||
if n := o.Account(); n != "" {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (a *APIClient) ListTeams(org string) ([]Team, error) {
|
||||
var teams []Team
|
||||
path := "/orgs/" + url.PathEscape(org) + "/teams"
|
||||
if err := a.Client.ListAll(context.Background(), path, gitea.ListOptions{}, &teams); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return teams, nil
|
||||
}
|
||||
|
||||
func (a *APIClient) ListTeamMembers(teamID int64) ([]string, error) {
|
||||
var users []User
|
||||
path := "/teams/" + strconv.FormatInt(teamID, 10) + "/members"
|
||||
if err := a.Client.ListAll(context.Background(), path, gitea.ListOptions{}, &users); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names := make([]string, 0, len(users))
|
||||
for i := range users {
|
||||
if n := users[i].Name(); n != "" {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (a *APIClient) ListOrgRepos(org string) ([]Repo, error) {
|
||||
var repos []Repo
|
||||
path := "/orgs/" + url.PathEscape(org) + "/repos"
|
||||
if err := a.Client.ListAll(context.Background(), path, gitea.ListOptions{}, &repos); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return repos, nil
|
||||
}
|
||||
|
||||
func (a *APIClient) ListIssues(owner, repo string) ([]Issue, error) {
|
||||
var issues []Issue
|
||||
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) + "/issues"
|
||||
opts := gitea.ListOptions{Extra: url.Values{
|
||||
"type": {"issues"},
|
||||
"state": {"open"},
|
||||
}}
|
||||
if err := a.Client.ListAll(context.Background(), path, opts, &issues); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// /issues 也會回傳 PR(帶 pull_request 欄位);一律排除。
|
||||
out := make([]Issue, 0, len(issues))
|
||||
for i := range issues {
|
||||
if issues[i].PullRequest == nil {
|
||||
out = append(out, issues[i])
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (a *APIClient) ListPulls(owner, repo string) ([]PullRequest, error) {
|
||||
var pulls []PullRequest
|
||||
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) + "/pulls"
|
||||
opts := gitea.ListOptions{Extra: url.Values{"state": {"open"}}}
|
||||
if err := a.Client.ListAll(context.Background(), path, opts, &pulls); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pulls, nil
|
||||
}
|
||||
|
||||
func (a *APIClient) ListComments(owner, repo string, number int64) ([]Comment, error) {
|
||||
var comments []Comment
|
||||
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) +
|
||||
"/issues/" + strconv.FormatInt(number, 10) + "/comments"
|
||||
if err := a.Client.ListAll(context.Background(), path, gitea.ListOptions{}, &comments); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// 編譯期確認 APIClient 同時實作 Client 與 StalledSource。
|
||||
var _ StalledSource = (*APIClient)(nil)
|
||||
@@ -0,0 +1,137 @@
|
||||
package workflow
|
||||
|
||||
import "sort"
|
||||
|
||||
// sortComments 依 created_at 字典序穩定排序(ISO8601 字串字典序與時間序一致),
|
||||
// 對應 gitea.py 各處的 comments.sort(key=created_at)。
|
||||
func sortComments(comments []Comment) []Comment {
|
||||
out := append([]Comment(nil), comments...)
|
||||
sort.SliceStable(out, func(a, b int) bool { return out[a].CreatedAt < out[b].CreatedAt })
|
||||
return out
|
||||
}
|
||||
|
||||
// LastComment 回傳依 created_at 排序後的最後一則留言;沒有留言回 nil。
|
||||
func LastComment(comments []Comment) *Comment {
|
||||
ordered := sortComments(comments)
|
||||
if len(ordered) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &ordered[len(ordered)-1]
|
||||
}
|
||||
|
||||
// lastCommentAuthor 回傳最後一則留言的作者;無留言或作者未知回空字串。
|
||||
func lastCommentAuthor(comments []Comment) string {
|
||||
if last := LastComment(comments); last != nil {
|
||||
return last.Author()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func containsString(items []string, target string) bool {
|
||||
for _, item := range items {
|
||||
if item == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NeedsAuthorFollowup 判定 PR 是否需要發起者跟進:有留言、且最後一則留言
|
||||
// 不是 PR 作者(gitea.py 的 _pr_needs_author_followup)。
|
||||
// 無留言或作者未知 → false(尚無留言的 PR 不列入跟進清單)。
|
||||
func NeedsAuthorFollowup(pr *PullRequest, comments []Comment) bool {
|
||||
author := pr.Author()
|
||||
if author == "" {
|
||||
return false
|
||||
}
|
||||
last := lastCommentAuthor(comments)
|
||||
return last != "" && last != author
|
||||
}
|
||||
|
||||
// NeedsReviewerFollowup 判定使用者是否需要審核此 PR:被指定為審核者、
|
||||
// 不是作者、最後一則留言不是自己(含尚無留言)
|
||||
// (gitea.py 的 _pr_needs_reviewer_followup)。
|
||||
func NeedsReviewerFollowup(pr *PullRequest, comments []Comment, username string) bool {
|
||||
if username == "" {
|
||||
return false
|
||||
}
|
||||
if pr.Author() == username {
|
||||
return false
|
||||
}
|
||||
if !containsString(ReviewerNames(pr), username) {
|
||||
return false
|
||||
}
|
||||
return lastCommentAuthor(comments) != username
|
||||
}
|
||||
|
||||
// ReviewerNames 回傳 PR 的 requested reviewers(去重、排序)。
|
||||
func ReviewerNames(pr *PullRequest) []string {
|
||||
seen := map[string]bool{}
|
||||
names := make([]string, 0, len(pr.RequestedReviewers))
|
||||
for i := range pr.RequestedReviewers {
|
||||
name := pr.RequestedReviewers[i].Name()
|
||||
if name != "" && !seen[name] {
|
||||
seen[name] = true
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
|
||||
// AssigneeNames 回傳 issue 的全部 assignees(assignee 欄位+assignees 陣列,
|
||||
// 去重、排序),對應 gitea.py 的 _assignee_usernames。
|
||||
func AssigneeNames(issue *Issue) []string {
|
||||
seen := map[string]bool{}
|
||||
add := func(u *User) {
|
||||
if u == nil {
|
||||
return
|
||||
}
|
||||
if name := u.Name(); name != "" && !seen[name] {
|
||||
seen[name] = true
|
||||
}
|
||||
}
|
||||
add(issue.Assignee)
|
||||
for i := range issue.Assignees {
|
||||
add(&issue.Assignees[i])
|
||||
}
|
||||
names := make([]string, 0, len(seen))
|
||||
for name := range seen {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names
|
||||
}
|
||||
|
||||
// AssigneeOverlaps 判定 issue 是否分派給 members 中至少一人
|
||||
// (members 為空 → false,同 gitea.py filter_issues_by_assignee 的空成員集行為)。
|
||||
func AssigneeOverlaps(issue *Issue, members []string) bool {
|
||||
if len(members) == 0 {
|
||||
return false
|
||||
}
|
||||
assignees := AssigneeNames(issue)
|
||||
for _, member := range members {
|
||||
if member != "" && containsString(assignees, member) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// LastCommentNotByAssignee 判定 issue 的最後一則留言是否不是任何 assignee
|
||||
// 留的(無留言 → true,視為需要處理)。
|
||||
// 注意:判定對象是該 issue 的**全部** assignees,不只是 members 中的成員
|
||||
// (gitea.py _last_comment_is_from_assignee 的語義)。
|
||||
func LastCommentNotByAssignee(issue *Issue, comments []Comment) bool {
|
||||
last := lastCommentAuthor(comments)
|
||||
if last == "" {
|
||||
return true
|
||||
}
|
||||
return !containsString(AssigneeNames(issue), last)
|
||||
}
|
||||
|
||||
// IssueNeedsWork 組合判定:分派給 members 中至少一人,且最後一則留言
|
||||
// 不是 assignee(gitea.py filter_issues_by_assignee 保留的項目)。
|
||||
func IssueNeedsWork(issue *Issue, comments []Comment, members []string) bool {
|
||||
return AssigneeOverlaps(issue, members) && LastCommentNotByAssignee(issue, comments)
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// judge_test.go — 驗證工作流判定語義(對照 gitea.py):
|
||||
// 最後留言判定、作者/審核者跟進條件、assignee 交集與排序。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// mkUser 構造 User。
|
||||
func mkUser(name string) *User { return &User{UserName: name} }
|
||||
|
||||
func TestUserNameFallback(t *testing.T) {
|
||||
if got := (&User{UserName: "a", Login: "b"}).Name(); got != "a" {
|
||||
t.Errorf("username 優先,得到 %q", got)
|
||||
}
|
||||
if got := (&User{Login: "b"}).Name(); got != "b" {
|
||||
t.Errorf("login 回退,得到 %q", got)
|
||||
}
|
||||
if got := mkUser("").Name(); got != "" {
|
||||
t.Errorf("空帳號,得到 %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastComment(t *testing.T) {
|
||||
comments := []Comment{
|
||||
{CreatedAt: "2026-09-09T01:00:00Z", User: mkUser("alex")},
|
||||
{CreatedAt: "2026-09-09T03:00:00Z", User: mkUser("max")},
|
||||
{CreatedAt: "2026-09-09T02:00:00Z", User: mkUser("ceo")},
|
||||
}
|
||||
last := LastComment(comments)
|
||||
if last == nil || last.Author() != "max" {
|
||||
t.Errorf("應依 created_at 排序取最後(03:00 max),得到 %+v", last)
|
||||
}
|
||||
if LastComment(nil) != nil {
|
||||
t.Errorf("無留言應回 nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedsAuthorFollowup(t *testing.T) {
|
||||
pr := &PullRequest{User: mkUser("alex")}
|
||||
cases := []struct {
|
||||
name string
|
||||
comments []Comment
|
||||
want bool
|
||||
}{
|
||||
{"無留言", nil, false},
|
||||
{"最後留言是作者", []Comment{{CreatedAt: "a", User: mkUser("alex")}}, false},
|
||||
{"最後留言是他人", []Comment{
|
||||
{CreatedAt: "a", User: mkUser("alex")},
|
||||
{CreatedAt: "b", User: mkUser("ceo")},
|
||||
}, true},
|
||||
{"留言者未知", []Comment{{CreatedAt: "a"}}, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := NeedsAuthorFollowup(pr, c.comments); got != c.want {
|
||||
t.Errorf("%s:得到 %v,want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedsReviewerFollowup(t *testing.T) {
|
||||
pr := &PullRequest{
|
||||
User: mkUser("max"),
|
||||
RequestedReviewers: []User{*mkUser("alex"), *mkUser("queena")},
|
||||
}
|
||||
comments := []Comment{{CreatedAt: "a", User: mkUser("max")}}
|
||||
if !NeedsReviewerFollowup(pr, comments, "alex") {
|
||||
t.Errorf("審核者且最後留言非自己 → 應需跟進")
|
||||
}
|
||||
if NeedsReviewerFollowup(pr, comments, "max") {
|
||||
t.Errorf("作者本人 → 不應列入審核清單")
|
||||
}
|
||||
if NeedsReviewerFollowup(pr, []Comment{{CreatedAt: "a", User: mkUser("alex")}}, "alex") {
|
||||
t.Errorf("最後留言是自己 → 不應需跟進")
|
||||
}
|
||||
if NeedsReviewerFollowup(pr, comments, "ceo") {
|
||||
t.Errorf("非審核者 → 不應需跟進")
|
||||
}
|
||||
// 尚無留言的 PR:審核者仍應被列入(含尚無留言)。
|
||||
if !NeedsReviewerFollowup(pr, nil, "queena") {
|
||||
t.Errorf("尚無留言 → 審核者應需跟進")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssigneeNames(t *testing.T) {
|
||||
issue := &Issue{
|
||||
Assignee: mkUser("alex"),
|
||||
Assignees: []User{*mkUser("alex"), *mkUser("max")},
|
||||
}
|
||||
if got := AssigneeNames(issue); !reflect.DeepEqual(got, []string{"alex", "max"}) {
|
||||
t.Errorf("assignee 應去重排序,得到 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssigneeOverlapsEmptyMembers(t *testing.T) {
|
||||
issue := &Issue{Assignee: mkUser("alex")}
|
||||
if AssigneeOverlaps(issue, nil) {
|
||||
t.Errorf("成員集為空 → 不應列入(同 gitea.py filter_issues_by_assignee)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastCommentNotByAssignee(t *testing.T) {
|
||||
issue := &Issue{Assignee: mkUser("alex")}
|
||||
if !LastCommentNotByAssignee(issue, nil) {
|
||||
t.Errorf("無留言 → 應視為需要處理")
|
||||
}
|
||||
if LastCommentNotByAssignee(issue, []Comment{{CreatedAt: "a", User: mkUser("alex")}}) {
|
||||
t.Errorf("最後留言來自 assignee → 不應列入")
|
||||
}
|
||||
if !LastCommentNotByAssignee(issue, []Comment{{CreatedAt: "a", User: mkUser("ceo")}}) {
|
||||
t.Errorf("最後留言來自他人 → 應列入")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdatedKeyFallbackChain(t *testing.T) {
|
||||
i := &Issue{UpdatedAt: "", Updated: "u", CreatedAt: "c"}
|
||||
if got := i.updatedKey(); got != "u" {
|
||||
t.Errorf("updated 回退鏈,得到 %q", got)
|
||||
}
|
||||
if got := (&Issue{}).updatedKey(); got != "9999" {
|
||||
t.Errorf("全缺 → 9999,得到 %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFullNameFallbacks(t *testing.T) {
|
||||
pr := &PullRequest{
|
||||
HTMLURL: "https://gitea.alterminal.com/alterminal/teai/pulls/2",
|
||||
Base: &PRRef{Repo: &Repository{FullName: "alterminal/teai"}},
|
||||
}
|
||||
if got := pr.FullName(); got != "alterminal/teai" {
|
||||
t.Errorf("base.repo 優先,得到 %q", got)
|
||||
}
|
||||
pr2 := &PullRequest{HTMLURL: "https://gitea.alterminal.com/alterminal/teai/pulls/2"}
|
||||
if got := pr2.FullName(); got != "alterminal/teai" {
|
||||
t.Errorf("html_url 回退,得到 %q", got)
|
||||
}
|
||||
i := &Issue{Repository: &Repository{FullName: "alterminal/agents"}}
|
||||
if got := i.FullName(); got != "alterminal/agents" {
|
||||
t.Errorf("repository 欄位,得到 %q", got)
|
||||
}
|
||||
if got := (&Issue{}).FullName(); got != "" {
|
||||
t.Errorf("全缺 → 空,得到 %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// errIncompatibleFlags 對應 gitea.py 的「--mine 與 --reviewer 不能併用」。
|
||||
var errIncompatibleFlags = errors.New("--mine 與 --reviewer 不能併用")
|
||||
|
||||
// Work 是 next 命令的輸出物件:Type 為 "pull" 或 "issue";Role 僅 pull 帶
|
||||
// ("author" 或 "reviewer"),對應 gitea.py 的 _work_dict。
|
||||
type Work struct {
|
||||
Type string `json:"type"`
|
||||
Role string `json:"role,omitempty"`
|
||||
Repo string `json:"repo"`
|
||||
Number int64 `json:"number"`
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// issueNumber 回傳 issue 編號:number 缺漏時回退 index(gitea.py 語義)。
|
||||
func (i *Issue) issueNumber() int64 {
|
||||
if i.Number != 0 {
|
||||
return i.Number
|
||||
}
|
||||
return i.Index
|
||||
}
|
||||
|
||||
// Num 是 issueNumber 的公開介面(CLI 輸出用)。
|
||||
func (i *Issue) Num() int64 { return i.issueNumber() }
|
||||
|
||||
// Next 回傳下一件未完成工作:先自己發起的待跟進 PR(role=author),再待審核
|
||||
// 的 PR(role=reviewer,含尚無留言),再分派給自己的 open issue。各層皆以
|
||||
// 「最久未更新優先」排序後取第一件(gitea.py 的 find_next_work)。
|
||||
// 沒有任何工作時回傳 nil。
|
||||
func (s *Scanner) Next() (*Work, error) {
|
||||
username, err := s.Whoami()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = username
|
||||
|
||||
// 第一層:自己發起、最後一則留言不是自己的 open PR。
|
||||
minePulls, err := s.Pulls(true, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(minePulls) > 0 {
|
||||
sorted := sortPullItemsByUpdated(minePulls)
|
||||
return workFromPull(sorted[0], "author"), nil
|
||||
}
|
||||
|
||||
// 第二層:自己是審核者、最後一則留言不是自己的 open PR。
|
||||
reviewerPulls, err := s.Pulls(false, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(reviewerPulls) > 0 {
|
||||
sorted := sortPullItemsByUpdated(reviewerPulls)
|
||||
return workFromPull(sorted[0], "reviewer"), nil
|
||||
}
|
||||
|
||||
// 第三層:分派給自己、最後一則留言不是 assignee 的 open issue。
|
||||
issues, err := s.Mine()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(issues) > 0 {
|
||||
sorted := sortIssuesByUpdated(issues)
|
||||
return workFromIssue(&sorted[0]), nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// sortPullItemsByUpdated 依 updatedKey 升冪(最久未更新在前)穩定排序。
|
||||
func sortPullItemsByUpdated(items []PullItem) []PullItem {
|
||||
out := append([]PullItem(nil), items...)
|
||||
sort.SliceStable(out, func(a, b int) bool {
|
||||
return out[a].Pull.updatedKey() < out[b].Pull.updatedKey()
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// sortIssuesByUpdated 依 updatedKey 升冪(最久未更新在前)穩定排序。
|
||||
func sortIssuesByUpdated(items []Issue) []Issue {
|
||||
out := append([]Issue(nil), items...)
|
||||
sort.SliceStable(out, func(a, b int) bool {
|
||||
return out[a].updatedKey() < out[b].updatedKey()
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// workFromPull 由 PR 組出 Work 物件。
|
||||
func workFromPull(item PullItem, role string) *Work {
|
||||
return &Work{
|
||||
Type: "pull",
|
||||
Role: role,
|
||||
Repo: item.Owner + "/" + item.Repo,
|
||||
Number: item.Pull.Number,
|
||||
Title: item.Pull.Title,
|
||||
URL: item.Pull.WebURL(),
|
||||
}
|
||||
}
|
||||
|
||||
// workFromIssue 由 issue 組出 Work 物件。
|
||||
func workFromIssue(issue *Issue) *Work {
|
||||
return &Work{
|
||||
Type: "issue",
|
||||
Repo: issue.FullName(),
|
||||
Number: issue.issueNumber(),
|
||||
Title: issue.Title,
|
||||
URL: issue.WebURL(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
// Package workflow 實作 AGENTS.md 工作流判定:跟進、審核、next 拾取與排序。
|
||||
//
|
||||
// 行為基準是 alterminal/agents 的 scripts/lib/gitea.py;判定規則以 AGENTS.md
|
||||
// 為唯一來源,本套件只實作、不改義。API 存取以 Client 介面抽象,HTTP 實作
|
||||
// 由 internal/gitea(#5 基礎建設)提供;測試以假 client 注入。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"sort"
|
||||
)
|
||||
|
||||
// AgentsTeamName 是工作流團隊的名稱(AGENTS.md:調度成員由 Agents 團隊決定)。
|
||||
const AgentsTeamName = "Agents"
|
||||
|
||||
// Client 抽象 teai 需要的 Gitea API 讀取操作(僅唯讀)。
|
||||
// #5 的 internal/gitea HTTP 用戶端實作此介面;workflow 不依賴 HTTP 細節。
|
||||
type Client interface {
|
||||
// CurrentUser 回傳目前帳號名(GET /user)。
|
||||
CurrentUser() (string, error)
|
||||
// ListOrgs 回傳帳號所屬組織名(GET /user/orgs,分頁)。
|
||||
ListOrgs() ([]string, error)
|
||||
// ListTeams 回傳組織的團隊清單(GET /orgs/{org}/teams,分頁)。
|
||||
ListTeams(org string) ([]Team, error)
|
||||
// ListTeamMembers 回傳團隊成員帳號(GET /teams/{id}/members,分頁)。
|
||||
ListTeamMembers(teamID int64) ([]string, error)
|
||||
// ListOrgRepos 回傳組織的倉庫物件(GET /orgs/{org}/repos,分頁)。
|
||||
ListOrgRepos(org string) ([]Repo, error)
|
||||
// ListIssues 回傳倉庫的 open issues(GET /repos/{owner}/{repo}/issues?state=open&type=issues,
|
||||
// 分頁;已排除帶 pull_request 標記的 PR)。assignee/留言過濾由 workflow 層負責。
|
||||
ListIssues(owner, repo string) ([]Issue, error)
|
||||
// ListPulls 回傳倉庫的 open PR(GET /repos/{owner}/{repo}/pulls?state=open,分頁)。
|
||||
ListPulls(owner, repo string) ([]PullRequest, error)
|
||||
// ListComments 回傳 issue/PR 的留言(GET /repos/{owner}/{repo}/issues/{n}/comments,分頁)。
|
||||
ListComments(owner, repo string, number int64) ([]Comment, error)
|
||||
}
|
||||
|
||||
// RepoPulls 是單一倉庫的 open PR 清單(掃描的中間產物)。
|
||||
type RepoPulls struct {
|
||||
Owner string
|
||||
Repo string
|
||||
Pulls []PullRequest
|
||||
}
|
||||
|
||||
// PullItem 是跟進清單中的 PR,附掃描時的所屬倉庫(owner/repo),
|
||||
// 供輸出時補齊 gitea.py 工作物件的 repo 欄位。
|
||||
type PullItem struct {
|
||||
Owner string
|
||||
Repo string
|
||||
Pull PullRequest
|
||||
}
|
||||
|
||||
// Scanner 在 Client 之上組合出各命令的資料(whoami/orgs/members/mine/pulls/next)。
|
||||
type Scanner struct {
|
||||
Client Client
|
||||
}
|
||||
|
||||
// Whoami 回傳目前帳號。
|
||||
func (s *Scanner) Whoami() (string, error) {
|
||||
return s.Client.CurrentUser()
|
||||
}
|
||||
|
||||
// Orgs 回傳目前帳號所屬的組織(去重、排序)。
|
||||
func (s *Scanner) Orgs() ([]string, error) {
|
||||
names, err := s.Client.ListOrgs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
out := []string{}
|
||||
for _, n := range names {
|
||||
if n != "" && !seen[n] {
|
||||
seen[n] = true
|
||||
out = append(out, n)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// agentsTeamID 找出組織內名為 Agents 的團隊 ID;沒有回 (0,false)。
|
||||
func (s *Scanner) agentsTeamID(org string) (int64, bool, error) {
|
||||
teams, err := s.Client.ListTeams(org)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
for _, team := range teams {
|
||||
if team.Name == AgentsTeamName {
|
||||
return team.ID, true, nil
|
||||
}
|
||||
}
|
||||
return 0, false, nil
|
||||
}
|
||||
|
||||
// Members 回傳跨組織 Agents 團隊成員(去重、排序)。
|
||||
// hasWork 為 true 時只保留有未完成工作者(判定同 Next 的拾取規則)。
|
||||
func (s *Scanner) Members(hasWork bool) ([]string, error) {
|
||||
orgs, err := s.Orgs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
names := []string{}
|
||||
for _, org := range orgs {
|
||||
teamID, ok, err := s.agentsTeamID(org)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
members, err := s.Client.ListTeamMembers(teamID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, m := range members {
|
||||
if m != "" && !seen[m] {
|
||||
seen[m] = true
|
||||
names = append(names, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
if !hasWork {
|
||||
return names, nil
|
||||
}
|
||||
busy, err := s.usernamesWithUnfinishedWork(names)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]string, 0, len(names))
|
||||
for _, name := range names {
|
||||
if busy[name] {
|
||||
out = append(out, name)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// iterOrgRepos 產出 (org, repoName);空倉庫跳過(沒有內容可掃)。
|
||||
func (s *Scanner) iterOrgRepos() ([][2]string, error) {
|
||||
orgs, err := s.Orgs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := [][2]string{}
|
||||
for _, org := range orgs {
|
||||
repos, err := s.Client.ListOrgRepos(org)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, repo := range repos {
|
||||
if repo.Name == "" || repo.Empty {
|
||||
continue
|
||||
}
|
||||
out = append(out, [2]string{org, repo.Name})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// iterOpenPulls 跨倉庫收集 open PR(附所屬 owner/repo)。
|
||||
// 對應 gitea.py 的 _iter_open_pulls:空倉庫、明確停用 PR 的倉庫跳過。
|
||||
func (s *Scanner) iterOpenPulls() ([]RepoPulls, error) {
|
||||
orgs, err := s.Orgs()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := []RepoPulls{}
|
||||
for _, org := range orgs {
|
||||
repos, err := s.Client.ListOrgRepos(org)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, repo := range repos {
|
||||
if repo.Name == "" || repo.Empty {
|
||||
continue
|
||||
}
|
||||
if repo.HasPullRequests != nil && !*repo.HasPullRequests {
|
||||
continue
|
||||
}
|
||||
pulls, err := s.Client.ListPulls(org, repo.Name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(pulls) == 0 {
|
||||
continue
|
||||
}
|
||||
out = append(out, RepoPulls{Owner: org, Repo: repo.Name, Pulls: pulls})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// orgIssue 是掃描到的 issue,附所屬 owner/repo。
|
||||
type orgIssue struct {
|
||||
Owner string
|
||||
Repo string
|
||||
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(至少一人)且最後一則留言
|
||||
// 不是 assignee 的 open issues(gitea.py 的 for_all_organizations)。
|
||||
func (s *Scanner) collectMemberIssues(members []string) ([]orgIssue, error) {
|
||||
pairs, err := s.iterOrgRepos()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := []orgIssue{}
|
||||
for _, pair := range pairs {
|
||||
owner, repo := pair[0], pair[1]
|
||||
issues, err := s.Client.ListIssues(owner, repo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range issues {
|
||||
issue := &issues[i]
|
||||
if !AssigneeOverlaps(issue, members) {
|
||||
continue
|
||||
}
|
||||
comments, err := s.commentsFor(owner, repo, issue.issueNumber())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !LastCommentNotByAssignee(issue, comments) {
|
||||
continue
|
||||
}
|
||||
out = append(out, orgIssue{Owner: owner, Repo: repo, Issue: *issue})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Mine 回傳分派給目前帳號、且最後一則留言不是 assignee 的 open issues
|
||||
// (跨所屬組織;gitea.py 的 list_my_followup_issues)。
|
||||
func (s *Scanner) Mine() ([]Issue, error) {
|
||||
username, err := s.Whoami()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
found, err := s.collectMemberIssues([]string{username})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]Issue, 0, len(found))
|
||||
for _, item := range found {
|
||||
out = append(out, item.Issue)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Pulls 回傳跟進清單(跨倉庫;gitea.py 的 list_followup_pulls 系列):
|
||||
// - 預設:「有留言且最後一則不是作者」的 open PR。
|
||||
// - mine=true:再限定作者是目前帳號(list_my_followup_pulls)。
|
||||
// - reviewer=true:改為「自己是 requested reviewer、不是作者、最後一則
|
||||
// 留言不是自己(含尚無留言)」(list_my_reviewer_pulls)。
|
||||
//
|
||||
// mine 與 reviewer 不可併用。
|
||||
func (s *Scanner) Pulls(mine, reviewer bool) ([]PullItem, error) {
|
||||
if mine && reviewer {
|
||||
return nil, errIncompatibleFlags
|
||||
}
|
||||
username := ""
|
||||
if mine || reviewer {
|
||||
var err error
|
||||
username, err = s.Whoami()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
repoPulls, err := s.iterOpenPulls()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
found := []PullItem{}
|
||||
for _, rp := range repoPulls {
|
||||
for i := range rp.Pulls {
|
||||
pr := &rp.Pulls[i]
|
||||
comments, err := s.commentsFor(rp.Owner, rp.Repo, pr.Number)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var match bool
|
||||
switch {
|
||||
case reviewer:
|
||||
match = NeedsReviewerFollowup(pr, comments, username)
|
||||
case mine:
|
||||
match = NeedsAuthorFollowup(pr, comments) && pr.Author() == username
|
||||
default:
|
||||
match = NeedsAuthorFollowup(pr, comments)
|
||||
}
|
||||
if match {
|
||||
found = append(found, PullItem{Owner: rp.Owner, Repo: rp.Repo, Pull: *pr})
|
||||
}
|
||||
}
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
|
||||
// usernamesWithUnfinishedWork 從待跟進 issue/PR 清單收集有未完成工作的
|
||||
// 成員帳號(gitea.py 的 _usernames_with_unfinished_work;判定同 Next)。
|
||||
func (s *Scanner) usernamesWithUnfinishedWork(members []string) (map[string]bool, error) {
|
||||
memberSet := map[string]bool{}
|
||||
for _, m := range members {
|
||||
if m != "" {
|
||||
memberSet[m] = true
|
||||
}
|
||||
}
|
||||
busy := map[string]bool{}
|
||||
if len(memberSet) == 0 {
|
||||
return busy, nil
|
||||
}
|
||||
|
||||
// issues:分派給任一成員、最後留言不是 assignee。
|
||||
issues, err := s.collectMemberIssues(members)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, item := range issues {
|
||||
for _, name := range AssigneeNames(&item.Issue) {
|
||||
if memberSet[name] {
|
||||
busy[name] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PR:作者待跟進/審核者待審。
|
||||
repoPulls, err := s.iterOpenPulls()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, rp := range repoPulls {
|
||||
for i := range rp.Pulls {
|
||||
pr := &rp.Pulls[i]
|
||||
comments, err := s.commentsFor(rp.Owner, rp.Repo, pr.Number)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if NeedsAuthorFollowup(pr, comments) {
|
||||
if author := pr.Author(); memberSet[author] {
|
||||
busy[author] = true
|
||||
}
|
||||
}
|
||||
for _, reviewer := range ReviewerNames(pr) {
|
||||
if memberSet[reviewer] && NeedsReviewerFollowup(pr, comments, reviewer) {
|
||||
busy[reviewer] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return busy, nil
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
// scan_test.go — 以假 client 驗證 Scanner 的命令層語義(對照 gitea.py):
|
||||
// next 三層拾取與「最久未更新優先」、mine/pulls 過濾、members --has-work。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeClient 以記憶體資料實作 Client。
|
||||
type fakeClient struct {
|
||||
currentUser string
|
||||
orgs []Org
|
||||
teams map[string][]Team // org → teams
|
||||
teamMembers map[int64][]string // teamID → 帳號
|
||||
repos map[string][]Repo // org → repos
|
||||
issues map[string][]Issue // "owner/repo" → issues(open,不含 PR)
|
||||
pulls map[string][]PullRequest // "owner/repo" → open PR
|
||||
comments map[string][]Comment // "owner/repo#number" → 留言
|
||||
failOn map[string]error // 端點 → 錯誤(測失敗傳播)
|
||||
}
|
||||
|
||||
func (f *fakeClient) CurrentUser() (string, error) {
|
||||
if err := f.failOn["user"]; err != nil {
|
||||
return "", err
|
||||
}
|
||||
return f.currentUser, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) ListOrgs() ([]string, error) {
|
||||
if err := f.failOn["orgs"]; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]string, 0, len(f.orgs))
|
||||
for _, o := range f.orgs {
|
||||
out = append(out, o.Account())
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) ListTeams(org string) ([]Team, error) {
|
||||
if err := f.failOn["teams"]; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.teams[org], nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) ListTeamMembers(teamID int64) ([]string, error) {
|
||||
if err := f.failOn["members"]; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.teamMembers[teamID], nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) ListOrgRepos(org string) ([]Repo, error) {
|
||||
if err := f.failOn["repos"]; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.repos[org], nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) ListIssues(owner, repo string) ([]Issue, error) {
|
||||
if err := f.failOn["issues"]; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.issues[owner+"/"+repo], nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) ListPulls(owner, repo string) ([]PullRequest, error) {
|
||||
if err := f.failOn["pulls"]; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.pulls[owner+"/"+repo], nil
|
||||
}
|
||||
|
||||
func (f *fakeClient) ListComments(owner, repo string, number int64) ([]Comment, error) {
|
||||
if err := f.failOn["comments"]; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f.comments[fmt.Sprintf("%s/%s#%d", owner, repo, number)], nil
|
||||
}
|
||||
|
||||
// newTestScanner 構造測試情境:一個組織、一個 Agents 團隊、兩個倉庫。
|
||||
func newTestScanner() (*Scanner, *fakeClient) {
|
||||
fc := &fakeClient{
|
||||
currentUser: "alex",
|
||||
orgs: []Org{{UserName: "alterminal"}},
|
||||
teams: map[string][]Team{"alterminal": {{ID: 1, Name: "Agents"}}},
|
||||
teamMembers: map[int64][]string{1: {"alex", "max", "queena"}},
|
||||
repos: map[string][]Repo{"alterminal": {{Name: "teai"}, {Name: "agents"}}},
|
||||
issues: map[string][]Issue{},
|
||||
pulls: map[string][]PullRequest{},
|
||||
comments: map[string][]Comment{},
|
||||
failOn: map[string]error{},
|
||||
}
|
||||
return &Scanner{Client: fc}, fc
|
||||
}
|
||||
|
||||
func TestNextLayerPriority(t *testing.T) {
|
||||
s, fc := newTestScanner()
|
||||
// 三層各有工作:author PR、reviewer PR、issue。
|
||||
fc.pulls["alterminal/teai"] = []PullRequest{
|
||||
{
|
||||
Number: 10, Title: "我的 PR", UpdatedAt: "2026-09-09T00:00:00Z",
|
||||
User: mkUser("alex"),
|
||||
},
|
||||
{
|
||||
Number: 11, Title: "待我審核的 PR", UpdatedAt: "2026-09-09T01:00:00Z",
|
||||
User: mkUser("max"),
|
||||
RequestedReviewers: []User{*mkUser("alex")},
|
||||
},
|
||||
}
|
||||
// author PR #10 有他人留言 → 需跟進。
|
||||
fc.comments["alterminal/teai#10"] = []Comment{
|
||||
{CreatedAt: "2026-09-09T00:10:00Z", User: mkUser("ceo")},
|
||||
}
|
||||
// reviewer PR #11 尚無留言 → 審核者仍應被列入。
|
||||
fc.issues["alterminal/agents"] = []Issue{
|
||||
{Number: 30, Title: "分派給 alex", UpdatedAt: "2026-09-08T00:00:00Z", Assignees: []User{*mkUser("alex")}},
|
||||
}
|
||||
work, err := s.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if work.Type != "pull" || work.Role != "author" || work.Number != 10 {
|
||||
t.Errorf("第一層應選 author PR #10,得到 %+v", work)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextLayerFallbackToReviewer(t *testing.T) {
|
||||
s, fc := newTestScanner()
|
||||
fc.pulls["alterminal/teai"] = []PullRequest{
|
||||
{
|
||||
Number: 11, Title: "待審核", UpdatedAt: "2026-09-09T01:00:00Z",
|
||||
User: mkUser("max"),
|
||||
RequestedReviewers: []User{*mkUser("alex")},
|
||||
},
|
||||
}
|
||||
fc.issues["alterminal/agents"] = []Issue{
|
||||
{Number: 30, Title: "分派給 alex", UpdatedAt: "2026-09-08T00:00:00Z", Assignees: []User{*mkUser("alex")}},
|
||||
}
|
||||
work, err := s.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if work.Type != "pull" || work.Role != "reviewer" || work.Number != 11 {
|
||||
t.Errorf("第二層應選 reviewer PR #11,得到 %+v", work)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextLayerFallbackToIssue(t *testing.T) {
|
||||
s, fc := newTestScanner()
|
||||
fc.issues["alterminal/agents"] = []Issue{
|
||||
{Number: 30, Title: "分派給 alex", UpdatedAt: "2026-09-08T00:00:00Z", Assignees: []User{*mkUser("alex")}},
|
||||
}
|
||||
work, err := s.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if work.Type != "issue" || work.Number != 30 {
|
||||
t.Errorf("第三層應選 issue #30,得到 %+v", work)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextNone(t *testing.T) {
|
||||
s, _ := newTestScanner()
|
||||
work, err := s.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if work != nil {
|
||||
t.Errorf("無工作應回 nil,得到 %+v", work)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextOldestFirst(t *testing.T) {
|
||||
s, fc := newTestScanner()
|
||||
fc.issues["alterminal/agents"] = []Issue{
|
||||
{Number: 31, Title: "較新", UpdatedAt: "2026-09-09T00:00:00Z", Assignees: []User{*mkUser("alex")}},
|
||||
{Number: 30, Title: "較舊", UpdatedAt: "2026-09-08T00:00:00Z", Assignees: []User{*mkUser("alex")}},
|
||||
}
|
||||
work, err := s.Next()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if work.Number != 30 {
|
||||
t.Errorf("應選最久未更新的 #30,得到 %+v", work)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMineSkipsLastCommentByAssignee(t *testing.T) {
|
||||
s, fc := newTestScanner()
|
||||
fc.issues["alterminal/agents"] = []Issue{
|
||||
{Number: 30, Title: "已在處理", UpdatedAt: "a", Assignees: []User{*mkUser("alex")}},
|
||||
}
|
||||
fc.comments["alterminal/agents#30"] = []Comment{
|
||||
{CreatedAt: "b", User: mkUser("alex")},
|
||||
}
|
||||
issues, err := s.Mine()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 0 {
|
||||
t.Errorf("最後留言來自 assignee → 應略過,得到 %d 件", len(issues))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullsMineReviewersExclusive(t *testing.T) {
|
||||
s, _ := newTestScanner()
|
||||
if _, err := s.Pulls(true, true); !errors.Is(err, errIncompatibleFlags) {
|
||||
t.Errorf("--mine 與 --reviewer 併用應回 errIncompatibleFlags,得到 %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMembersHasWork(t *testing.T) {
|
||||
s, fc := newTestScanner()
|
||||
// alex 有待審核 PR;max 無任何工作;queena 有分派 issue。
|
||||
fc.pulls["alterminal/teai"] = []PullRequest{
|
||||
{
|
||||
Number: 11, UpdatedAt: "a", User: mkUser("max"),
|
||||
RequestedReviewers: []User{*mkUser("alex")},
|
||||
},
|
||||
}
|
||||
fc.issues["alterminal/agents"] = []Issue{
|
||||
{Number: 30, UpdatedAt: "b", Assignees: []User{*mkUser("queena")}},
|
||||
}
|
||||
got, err := s.Members(true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, []string{"alex", "queena"}) {
|
||||
t.Errorf("應只有 alex 與 queena 有工作,得到 %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorPropagation(t *testing.T) {
|
||||
s, fc := newTestScanner()
|
||||
fc.failOn["orgs"] = errors.New("boom")
|
||||
if _, err := s.Next(); err == nil {
|
||||
t.Errorf("API 錯誤應向上傳播,不應吞掉")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPullsDefault(t *testing.T) {
|
||||
s, fc := newTestScanner()
|
||||
fc.pulls["alterminal/teai"] = []PullRequest{
|
||||
{Number: 10, UpdatedAt: "a", User: mkUser("alex")},
|
||||
}
|
||||
fc.comments["alterminal/teai#10"] = []Comment{
|
||||
{CreatedAt: "b", User: mkUser("ceo")},
|
||||
}
|
||||
items, err := s.Pulls(false, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) != 1 || items[0].Repo != "teai" {
|
||||
t.Errorf("應列出待跟進 PR,得到 %+v", items)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
// stalled_entry_test.go — RunStalled/ResolveIssueXrefs 高階入口的單元測試
|
||||
//(#7 CLI 接線;資料源注入假實作,離線可測)。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeStalledSource 包 fakeSource 補上 StalledSource 面向。
|
||||
type fakeStalledSource struct {
|
||||
*fakeSource
|
||||
username string
|
||||
// getIssueErr 模擬 GetIssue 失敗(xrefs 的 404 路徑)。
|
||||
getIssueErr error
|
||||
}
|
||||
|
||||
func (f *fakeStalledSource) CurrentUser() (string, error) { return f.username, 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{}, ¬FoundError{}
|
||||
}
|
||||
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 = ¬FoundError{}
|
||||
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。
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// User 是 Gitea API 的使用者物件(僅取工作流判斷會用到的欄位)。
|
||||
type User struct {
|
||||
UserName string `json:"username"`
|
||||
Login string `json:"login"`
|
||||
}
|
||||
|
||||
// Name 回傳帳號名:先 username,缺漏時回退 login
|
||||
// (對應 gitea.py 的「username or login」取值順序)。
|
||||
func (u *User) Name() string {
|
||||
if u == nil {
|
||||
return ""
|
||||
}
|
||||
if u.UserName != "" {
|
||||
return u.UserName
|
||||
}
|
||||
return u.Login
|
||||
}
|
||||
|
||||
// Org 是帳號所屬的組織物件。
|
||||
type Org struct {
|
||||
UserName string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Account 回傳組織名:先 username,缺漏時回退 name
|
||||
// (對應 gitea.py 的取值順序)。
|
||||
func (o Org) Account() string {
|
||||
if o.UserName != "" {
|
||||
return o.UserName
|
||||
}
|
||||
return o.Name
|
||||
}
|
||||
|
||||
// Team 是組織內的團隊物件。
|
||||
type Team struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Repo 是組織倉庫清單中的倉庫物件。Empty 與 HasPullRequests
|
||||
// 對應 gitea.py _iter_open_pulls 的跳過條件:空倉庫、明確停用 PR
|
||||
// (has_pull_requests 為 false)者不列入 PR 掃描。
|
||||
type Repo struct {
|
||||
Name string `json:"name"`
|
||||
Empty bool `json:"empty"`
|
||||
HasPullRequests *bool `json:"has_pull_requests"`
|
||||
}
|
||||
|
||||
// Repository 是 issue/PR 物件內嵌的所屬倉庫資訊。
|
||||
type Repository struct {
|
||||
FullName string `json:"full_name"`
|
||||
}
|
||||
|
||||
// PRRef 是 PR 的 base/head 端點,含所屬倉庫。
|
||||
type PRRef struct {
|
||||
Repo *Repository `json:"repo"`
|
||||
}
|
||||
|
||||
// Comment 是 issue/PR 的討論留言(PR 的留言也走 issues comments 端點)。
|
||||
type Comment struct {
|
||||
Body string `json:"body"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
User *User `json:"user"`
|
||||
}
|
||||
|
||||
// Author 回傳留言者帳號;空字串表示未知。
|
||||
func (c *Comment) Author() string { return c.User.Name() }
|
||||
|
||||
// pullMarker 標記 /issues 端點回傳的物件其實是 PR
|
||||
// (Gitea 只會在 PR 上附帶 pull_request 欄位;issue 沒有此欄位)。
|
||||
type pullMarker struct{}
|
||||
|
||||
// Issue 是 issue 物件。/issues 端點也會以此形狀回傳 PR(帶非 nil 的
|
||||
// PullRequest 標記),判斷時一律排除(同 gitea.py list_issues_for_repository)。
|
||||
type Issue struct {
|
||||
Number int64 `json:"number"`
|
||||
Index int64 `json:"index"`
|
||||
Title string `json:"title"`
|
||||
State string `json:"state"`
|
||||
Body string `json:"body"`
|
||||
ClosedAt string `json:"closed_at"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
URL string `json:"url"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
Updated string `json:"updated"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
Created string `json:"created"`
|
||||
User *User `json:"user"`
|
||||
Assignee *User `json:"assignee"`
|
||||
Assignees []User `json:"assignees"`
|
||||
PullRequest *pullMarker `json:"pull_request"`
|
||||
Repository *Repository `json:"repository"`
|
||||
|
||||
// Raw 是本次回應的完整原始 JSON。清單類命令(mine/pulls)必須原樣輸出
|
||||
// (gitea.py 直接傾印 API 原始物件),作為交叉驗證一致的基礎。
|
||||
Raw json.RawMessage `json:"-"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON 解碼各判斷欄位,並保留原始 JSON 供原樣輸出。
|
||||
func (i *Issue) UnmarshalJSON(data []byte) error {
|
||||
type issueAlias Issue
|
||||
var a issueAlias
|
||||
if err := json.Unmarshal(data, &a); err != nil {
|
||||
return err
|
||||
}
|
||||
*i = Issue(a)
|
||||
i.Raw = append(json.RawMessage(nil), data...)
|
||||
return nil
|
||||
}
|
||||
|
||||
// updatedKey 對應 gitea.py 的 _updated_at 回退鏈
|
||||
// (updated_at → updated → created_at → created → "9999"),
|
||||
// 供「最久未更新優先」排序;ISO8601 字串字典序與時間序一致。
|
||||
func (i *Issue) updatedKey() string {
|
||||
for _, v := range []string{i.UpdatedAt, i.Updated, i.CreatedAt, i.Created} {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return "9999"
|
||||
}
|
||||
|
||||
// WebURL 回傳網頁網址:先 html_url,缺漏時回退 API url。
|
||||
func (i *Issue) WebURL() string {
|
||||
if i.HTMLURL != "" {
|
||||
return i.HTMLURL
|
||||
}
|
||||
return i.URL
|
||||
}
|
||||
|
||||
// PullRequest 是 pull request 物件(僅取判斷所需欄位)。
|
||||
type PullRequest struct {
|
||||
Number int64 `json:"number"`
|
||||
Title string `json:"title"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
URL string `json:"url"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
Updated string `json:"updated"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
Created string `json:"created"`
|
||||
User *User `json:"user"`
|
||||
RequestedReviewers []User `json:"requested_reviewers"`
|
||||
Base *PRRef `json:"base"`
|
||||
Head *PRRef `json:"head"`
|
||||
Repository *Repository `json:"repository"`
|
||||
|
||||
// Raw 意義同 Issue.Raw。
|
||||
Raw json.RawMessage `json:"-"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON 解碼各判斷欄位,並保留原始 JSON 供原樣輸出。
|
||||
func (p *PullRequest) UnmarshalJSON(data []byte) error {
|
||||
type pullAlias PullRequest
|
||||
var a pullAlias
|
||||
if err := json.Unmarshal(data, &a); err != nil {
|
||||
return err
|
||||
}
|
||||
*p = PullRequest(a)
|
||||
p.Raw = append(json.RawMessage(nil), data...)
|
||||
return nil
|
||||
}
|
||||
|
||||
// updatedKey 意義同 Issue.updatedKey。
|
||||
func (p *PullRequest) updatedKey() string {
|
||||
for _, v := range []string{p.UpdatedAt, p.Updated, p.CreatedAt, p.Created} {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return "9999"
|
||||
}
|
||||
|
||||
// Author 回傳 PR 發起者帳號(user 欄位)。
|
||||
func (p *PullRequest) Author() string { return p.User.Name() }
|
||||
|
||||
// WebURL 回傳網頁網址:先 html_url,缺漏時回退 API url。
|
||||
func (p *PullRequest) WebURL() string {
|
||||
if p.HTMLURL != "" {
|
||||
return p.HTMLURL
|
||||
}
|
||||
return p.URL
|
||||
}
|
||||
|
||||
// htmlURLRepoRe 從網頁網址推回 "owner/repo"
|
||||
// (gitea.py _full_name_of 的 html_url regex 回退)。
|
||||
var htmlURLRepoRe = regexp.MustCompile(`/([^/]+/[^/]+)/(?:issues|pulls)/[0-9]+`)
|
||||
|
||||
func repoFullNameFromURL(webURL string) string {
|
||||
if m := htmlURLRepoRe.FindStringSubmatch(webURL); m != nil {
|
||||
return m[1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// FullName 從 issue 物件推回 "owner/repo":先 repository 欄位,再以網頁網址回退。
|
||||
func (i *Issue) FullName() string {
|
||||
if i.Repository != nil && i.Repository.FullName != "" {
|
||||
return i.Repository.FullName
|
||||
}
|
||||
return repoFullNameFromURL(i.WebURL())
|
||||
}
|
||||
|
||||
// FullName 從 PR 物件推回 "owner/repo":repository → base.repo → head.repo →
|
||||
// 網頁網址回退(Gitea 的 /pulls 回應通常沒有 repository 欄位)。
|
||||
func (p *PullRequest) FullName() string {
|
||||
if p.Repository != nil && p.Repository.FullName != "" {
|
||||
return p.Repository.FullName
|
||||
}
|
||||
for _, ref := range []*PRRef{p.Base, p.Head} {
|
||||
if ref != nil && ref.Repo != nil && ref.Repo.FullName != "" {
|
||||
return ref.Repo.FullName
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,636 @@
|
||||
// 套件 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
|
||||
)
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// 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);時間未知則不排除
|
||||
}
|
||||
var ms []time.Time
|
||||
if m, ok := parseMoment(child.UpdatedAt); 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
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(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)
|
||||
var moments []time.Time
|
||||
if m, ok := parseMoment(issue.UpdatedAt); ok {
|
||||
moments = append(moments, m)
|
||||
}
|
||||
if m, ok := parseMoment(issue.CreatedAt); ok {
|
||||
moments = append(moments, m)
|
||||
}
|
||||
for _, c := range comments {
|
||||
if m, ok := parseMoment(c.CreatedAt); ok {
|
||||
moments = append(moments, m)
|
||||
}
|
||||
}
|
||||
moments = append(moments, childMoments...)
|
||||
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(pr PullRequest, comments []Comment, username string, threshold float64, now time.Time) (Item, bool) {
|
||||
reviewers := ReviewerNames(&pr)
|
||||
author := pr.Author()
|
||||
var moments []time.Time
|
||||
if m, ok := parseMoment(pr.UpdatedAt); ok {
|
||||
moments = append(moments, m)
|
||||
}
|
||||
if m, ok := parseMoment(pr.CreatedAt); ok {
|
||||
moments = append(moments, m)
|
||||
}
|
||||
for _, c := range comments {
|
||||
if m, ok := parseMoment(c.CreatedAt); ok {
|
||||
moments = append(moments, m)
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
// workflow 套件的單元測試(teai issue #7 驗收:xref 邊界案例與 stalled 判定)。
|
||||
//
|
||||
// fakeSource 以假資料實作 Source 介面,邏輯離線可測;
|
||||
// 語義對照組是 alterminal/agents scripts/lib/gitea.py。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
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) 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"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
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")
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user