Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c311f02e0f | ||
|
|
7badd9e46d | ||
|
|
a7952c6834 | ||
|
|
afdead46e2 | ||
|
|
9e46d233fb |
@@ -1,12 +1,13 @@
|
|||||||
# teai
|
# teai
|
||||||
|
|
||||||
teai 是 Gitea 的命令列(CLI)輔助工具,補足官方 `tea` CLI 缺少的功能。
|
teai 是 Gitea 的命令列(CLI)工具,以更完整、更可靠的方式操作 Gitea。
|
||||||
名稱取「**te**a + **AI**」:這套工具主要為了讓 AI agent 能以更完整、更可靠的
|
名稱取「**te**a + **AI**」:這套工具主要為了讓 AI agent 能以更完整、更可靠的
|
||||||
方式操作 Gitea(查詢、回覆、審核、自動化……)。
|
方式操作 Gitea(查詢、回覆、審核、自動化……)。
|
||||||
|
|
||||||
- **語言:** Go(與 Gitea 本體一致),僅用標準庫,離線可建置
|
- **語言:** Go(與 Gitea 本體一致),僅用標準庫,離線可建置
|
||||||
- **目標站點:** `https://gitea.alterminal.com`
|
- **目標站點:** `https://gitea.alterminal.com`
|
||||||
- **狀態:** 基礎建設(#5:internal/gitea)與工作流命令(#6:whoami/orgs/members/mine/pulls/next)已實作;stalled/xrefs(#7)與日常操作命令(#8)進行中
|
- **狀態:** 基礎建設(#5:internal/gitea)、工作流命令(#6:whoami/orgs/members/mine/pulls/next)與日常操作命令(#8:issues/pulls/labels/milestones/releases/repos/api)已實作;stalled/xrefs(#7)進行中
|
||||||
|
- **範圍(#3):** 不避開 tea 已有的功能;單一工具涵蓋完整操作
|
||||||
|
|
||||||
## 安裝與建置
|
## 安裝與建置
|
||||||
|
|
||||||
@@ -23,12 +24,43 @@ go build -o teai ./cmd/teai
|
|||||||
|
|
||||||
### 設計原則
|
### 設計原則
|
||||||
|
|
||||||
1. **與 tea 互補,不重複**:`tea` 已有的功能(clone、issues、pulls、labels、milestones、release、api……)一律用 `tea`。teai 只做 tea 做不到的事:跨倉庫/跨組織聚合、工作流判定(跟進/審核/停滯)、機器可讀輸出。
|
1. **功能自主完整(#3)**:teai 自行實作完整的功能集,**不**以「tea 已有」為由略過(tea 本身存在諸多問題,見 #3)。除了 gitea.py 工作流(跨倉庫/跨組織聚合、工作流判定、機器可讀輸出),也涵蓋日常操作(issues/pulls/labels/milestones/release……),tea 只是相容參考與對照組。由單一二進位檔提供一致介面,避免多工具拼接。
|
||||||
2. **規則單一來源**:「最後一則留言不是自己」等工作流判定規則以 `AGENTS.md` 為準,teai 只實作、不改義。規則要變更,先改 AGENTS.md,teai 跟著改。
|
2. **規則單一來源**:「最後一則留言不是自己」等工作流判定規則以 `AGENTS.md` 為準,teai 只實作、不改義。規則要變更,先改 AGENTS.md,teai 跟著改。
|
||||||
3. **機器可讀優先**:預設輸出 JSON;`--output table` 僅供人工抽查。
|
3. **機器可讀優先**:預設輸出 JSON;`--output table` 僅供人工抽查。
|
||||||
4. **可直接替換原型**:`gitea.py` 的每個子命令在 teai 都有語義相同的對應命令,可交叉驗證、平滑遷移。
|
4. **可直接替換原型**:`gitea.py` 的每個子命令在 teai 都有語義相同的對應命令,可交叉驗證、平滑遷移。
|
||||||
5. **認證沿用 tea**:讀 `tea` 的登入組態(`TEA_CONFIG` 或 `~/.config/tea/config.yml`),不另建認證體系。
|
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`)時會正確傳遞。
|
||||||
|
|
||||||
### 全域介面
|
### 全域介面
|
||||||
|
|
||||||
@@ -184,15 +216,6 @@ teai whoami # 目前帳號(讀 tea 組態)
|
|||||||
| `mine` | `teai mine` | 相同 |
|
| `mine` | `teai mine` | 相同 |
|
||||||
| (底線函式) | `internal/` 套件 | 不設 CLI 命令;`xrefs` 為其邏輯的公開化 |
|
| (底線函式) | `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 為行為基準:同帳號同時跑兩者,輸出應一致(交叉驗證)。
|
1. 以 gitea.py 為行為基準:同帳號同時跑兩者,輸出應一致(交叉驗證)。
|
||||||
|
|||||||
+131
-66
@@ -12,6 +12,7 @@ package cli
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"sort"
|
"sort"
|
||||||
@@ -97,9 +98,8 @@ var commands = map[string]*command{
|
|||||||
|
|
||||||
// Run 剖析引數並分派到對應子命令,回傳行程結束碼。
|
// Run 剖析引數並分派到對應子命令,回傳行程結束碼。
|
||||||
//
|
//
|
||||||
// 引數結構:teai [全域選項] <命令> [命令參數]。全域選項可出現在命令
|
// 引數結構:teai [全域選項] <命令> [命令參數]。全域選項須在命令之前;
|
||||||
// 之前或之後(README 範例:teai next --output table);無引數或要求說明
|
// 無引數或要求說明(-h/--help)時印出用法;未知命令或無效選項回 ExitUsage。
|
||||||
// (-h/--help)時印出用法;未知命令或無效選項回 ExitUsage。
|
|
||||||
func Run(stdout, stderr io.Writer, args []string) int {
|
func Run(stdout, stderr io.Writer, args []string) int {
|
||||||
env := &Env{Out: stdout, Err: stderr, Globals: defaultGlobals()}
|
env := &Env{Out: stdout, Err: stderr, Globals: defaultGlobals()}
|
||||||
|
|
||||||
@@ -108,7 +108,7 @@ func Run(stdout, stderr io.Writer, args []string) int {
|
|||||||
return int(ExitOK)
|
return int(ExitOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
rest, err := extractGlobals(&env.Globals, args)
|
rest, err := parseGlobals(&env.Globals, args)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(stderr, "teai: %v\n\n", err)
|
fmt.Fprintf(stderr, "teai: %v\n\n", err)
|
||||||
printUsage(stderr)
|
printUsage(stderr)
|
||||||
@@ -127,11 +127,6 @@ func Run(stdout, stderr io.Writer, args []string) int {
|
|||||||
return dispatch(env, "version", rest[1:])
|
return dispatch(env, "version", rest[1:])
|
||||||
default:
|
default:
|
||||||
name := rest[0]
|
name := rest[0]
|
||||||
if strings.HasPrefix(name, "-") {
|
|
||||||
fmt.Fprintf(stderr, "teai: unknown global option %q\n\n", name)
|
|
||||||
printUsage(stderr)
|
|
||||||
return int(ExitUsage)
|
|
||||||
}
|
|
||||||
if _, ok := commands[name]; !ok {
|
if _, ok := commands[name]; !ok {
|
||||||
fmt.Fprintf(stderr, "teai: unknown command %q\n\n", name)
|
fmt.Fprintf(stderr, "teai: unknown command %q\n\n", name)
|
||||||
printUsage(stderr)
|
printUsage(stderr)
|
||||||
@@ -141,7 +136,7 @@ func Run(stdout, stderr io.Writer, args []string) int {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// globalFlags 列出全域選項的長名稱(目前全部都需要值)。
|
// globalFlags 列出全域選項的長名稱與是否需要值。
|
||||||
var globalFlags = map[string]bool{
|
var globalFlags = map[string]bool{
|
||||||
"--url": true,
|
"--url": true,
|
||||||
"--token": true,
|
"--token": true,
|
||||||
@@ -150,24 +145,40 @@ var globalFlags = map[string]bool{
|
|||||||
"--timeout": true,
|
"--timeout": true,
|
||||||
}
|
}
|
||||||
|
|
||||||
// extractGlobals 從 args 中抽出全域選項(可出現在命令之前或之後),
|
// extractGlobals 從 args 中「抽取」全域選項(可出現在命令之後、與命令
|
||||||
// 回傳其餘引數(命令與其參數,順序保留)。
|
// 旗標交錯),其餘引數依原順序保留給子命令剖析。未知的選項一律留給
|
||||||
//
|
// 子命令處理(可能是命令旗標,如 --has-work),不在這裡報錯。
|
||||||
// 採「抽取式」剖析:只取走已知的全域選項;任何其他引數——位置參數或
|
|
||||||
// 子命令自己的旗標(如 members 的 --has-work、pulls 的 --mine/--reviewer/
|
|
||||||
// --repo)——原樣依序交回,由子命令的 flagset 解析。因此
|
|
||||||
//
|
|
||||||
// teai members --has-work --output table
|
|
||||||
// teai pulls --mine --repo alterminal/teai
|
|
||||||
// teai next --output table
|
|
||||||
//
|
|
||||||
// 都能正確分派(全域與命令旗標可交錯出現)。
|
|
||||||
//
|
|
||||||
// 停止條件:遇到 --(剝除它,其後全部交回,不再抽取)或
|
|
||||||
// -h/--help/-v/--version(不是全域選項,交回 Run 的分派處理)。
|
|
||||||
// 全域選項缺少值或值無效時回 ErrUsage。
|
|
||||||
func extractGlobals(g *Globals, args []string) ([]string, error) {
|
func extractGlobals(g *Globals, args []string) ([]string, error) {
|
||||||
rest := make([]string, 0, len(args))
|
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
|
i := 0
|
||||||
for i < len(args) {
|
for i < len(args) {
|
||||||
arg := args[i]
|
arg := args[i]
|
||||||
@@ -175,19 +186,15 @@ func extractGlobals(g *Globals, args []string) ([]string, error) {
|
|||||||
rest = append(rest, args[i+1:]...)
|
rest = append(rest, args[i+1:]...)
|
||||||
return rest, nil
|
return rest, nil
|
||||||
}
|
}
|
||||||
if arg == "-" || !strings.HasPrefix(arg, "-") {
|
if !strings.HasPrefix(arg, "--") {
|
||||||
rest = append(rest, arg)
|
rest = append(rest, arg)
|
||||||
i++
|
i++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
name, inline, hasInline := strings.Cut(arg, "=")
|
name, inline, hasInline := strings.Cut(arg, "=")
|
||||||
switch name {
|
_, ok := globalFlags[name]
|
||||||
case "-h", "--help", "-v", "--version":
|
if !ok {
|
||||||
rest = append(rest, args[i:]...)
|
// 不是全域選項:留給子命令(可能是 --has-work 這類命令旗標)。
|
||||||
return rest, nil
|
|
||||||
}
|
|
||||||
if _, ok := globalFlags[name]; !ok {
|
|
||||||
// 非全域選項:屬於子命令,原樣交回(順序保留)。
|
|
||||||
rest = append(rest, arg)
|
rest = append(rest, arg)
|
||||||
i++
|
i++
|
||||||
continue
|
continue
|
||||||
@@ -202,7 +209,7 @@ func extractGlobals(g *Globals, args []string) ([]string, error) {
|
|||||||
i++
|
i++
|
||||||
value = args[i]
|
value = args[i]
|
||||||
}
|
}
|
||||||
if err := applyGlobal(g, name, value); err != nil {
|
if err := applyGlobal(name, value); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
i++
|
i++
|
||||||
@@ -210,50 +217,111 @@ func extractGlobals(g *Globals, args []string) ([]string, error) {
|
|||||||
return rest, nil
|
return rest, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// applyGlobal 套用單一全域選項的值;值無效時回 ErrUsage。
|
// parseGlobals 從 args 前端取走全域選項,回傳剩餘引數(命令與其參數)。
|
||||||
func applyGlobal(g *Globals, name, value string) error {
|
// 遇到第一個非選項引數即停;不認得的選項或缺少值都回 ErrUsage。
|
||||||
switch name {
|
func parseGlobals(g *Globals, args []string) ([]string, error) {
|
||||||
case "--url":
|
i := 0
|
||||||
if strings.TrimSpace(value) == "" {
|
for i < len(args) {
|
||||||
return &ErrUsage{Msg: "--url must not be empty"}
|
arg := args[i]
|
||||||
|
if arg == "--" {
|
||||||
|
return args[i+1:], nil
|
||||||
}
|
}
|
||||||
g.URL = value
|
if !strings.HasPrefix(arg, "-") || arg == "-" {
|
||||||
case "--token":
|
return args[i:], nil
|
||||||
g.Token = value
|
|
||||||
case "--config":
|
|
||||||
if strings.TrimSpace(value) == "" {
|
|
||||||
return &ErrUsage{Msg: "--config must not be empty"}
|
|
||||||
}
|
}
|
||||||
g.ConfigPath = value
|
name, inline, hasInline := strings.Cut(arg, "=")
|
||||||
case "--output":
|
// -h/--help/-v/--version 不是全域選項;交回 Run 的分派處理。
|
||||||
f, err := gitea.ParseFormat(value)
|
switch name {
|
||||||
if err != nil {
|
case "-h", "--help", "-v", "--version":
|
||||||
return &ErrUsage{Msg: err.Error()}
|
return args[i:], nil
|
||||||
}
|
}
|
||||||
g.Output = f
|
need, ok := globalFlags[name]
|
||||||
case "--timeout":
|
if !ok {
|
||||||
d, err := time.ParseDuration(value)
|
return nil, &ErrUsage{Msg: fmt.Sprintf("unknown global option %q", name)}
|
||||||
if err != nil || d <= 0 {
|
|
||||||
return &ErrUsage{Msg: fmt.Sprintf("invalid --timeout %q (want e.g. 30s)", value)}
|
|
||||||
}
|
}
|
||||||
g.Timeout = d
|
var value string
|
||||||
|
if hasInline {
|
||||||
|
value = inline
|
||||||
|
} else {
|
||||||
|
if !need {
|
||||||
|
// 目前所有全域選項都需要值;保留機制給未來的布林選項。
|
||||||
|
value = ""
|
||||||
|
}
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return nil, &ErrUsage{Msg: fmt.Sprintf("global option %q requires a value", name)}
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
value = args[i]
|
||||||
|
}
|
||||||
|
switch name {
|
||||||
|
case "--url":
|
||||||
|
if strings.TrimSpace(value) == "" {
|
||||||
|
return nil, &ErrUsage{Msg: "--url must not be empty"}
|
||||||
|
}
|
||||||
|
g.URL = value
|
||||||
|
case "--token":
|
||||||
|
g.Token = value
|
||||||
|
case "--config":
|
||||||
|
if strings.TrimSpace(value) == "" {
|
||||||
|
return nil, &ErrUsage{Msg: "--config must not be empty"}
|
||||||
|
}
|
||||||
|
g.ConfigPath = value
|
||||||
|
case "--output":
|
||||||
|
f, err := gitea.ParseFormat(value)
|
||||||
|
if err != nil {
|
||||||
|
return nil, &ErrUsage{Msg: err.Error()}
|
||||||
|
}
|
||||||
|
g.Output = f
|
||||||
|
case "--timeout":
|
||||||
|
d, err := time.ParseDuration(value)
|
||||||
|
if err != nil || d <= 0 {
|
||||||
|
return nil, &ErrUsage{Msg: fmt.Sprintf("invalid --timeout %q (want e.g. 30s)", value)}
|
||||||
|
}
|
||||||
|
g.Timeout = d
|
||||||
|
}
|
||||||
|
i++
|
||||||
}
|
}
|
||||||
return nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// dispatch 執行已註冊的子命令,把錯誤轉成結束碼並輸出。
|
// dispatch 執行已註冊的子命令,把錯誤轉成結束碼並輸出。
|
||||||
// 全域選項已在 Run 的 extractGlobals 抽取完畢(允許出現在命令之後,
|
// 旗標剖析交由各命令自行處理(不同命令有不同旗標,如 pulls --mine);
|
||||||
// README 範例:teai next --output table);這裡把剩餘引數直接交給
|
// 全域選項允許出現在命令之後(README 範例:teai next --output table),
|
||||||
// 命令的 flagset 解析。
|
// dispatch 先從 args 剝離全域選項併入 Globals,其餘(含命令自己的旗標,
|
||||||
|
// 如 --has-work)原樣交給命令,不會誤判為未知全域選項。
|
||||||
func dispatch(env *Env, name string, args []string) int {
|
func dispatch(env *Env, name string, args []string) int {
|
||||||
cmd := commands[name]
|
cmd := commands[name]
|
||||||
if err := cmd.run(env, args); err != nil {
|
g := env.Globals
|
||||||
|
rest, err := extractGlobals(&g, args)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(env.Err, "teai: %v\n\n", err)
|
||||||
|
printUsage(env.Err)
|
||||||
|
return int(ExitUsage)
|
||||||
|
}
|
||||||
|
env.Globals = g
|
||||||
|
if err := cmd.run(env, rest); err != nil {
|
||||||
fmt.Fprintf(env.Err, "teai %s: %v\n", name, err)
|
fmt.Fprintf(env.Err, "teai %s: %v\n", name, err)
|
||||||
return int(exitCodeFor(err))
|
return int(exitCodeFor(err))
|
||||||
}
|
}
|
||||||
return int(ExitOK)
|
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,
|
// exitCodeFor 把命令錯誤映射到結束碼:用法錯誤 → 2,API 錯誤 → 3,
|
||||||
// 其他(內部)→ 1。
|
// 其他(內部)→ 1。
|
||||||
func exitCodeFor(err error) ExitCode {
|
func exitCodeFor(err error) ExitCode {
|
||||||
@@ -273,9 +341,6 @@ func exitCodeFor(err error) ExitCode {
|
|||||||
|
|
||||||
// runVersion 輸出版本資訊。
|
// runVersion 輸出版本資訊。
|
||||||
func runVersion(env *Env, args []string) error {
|
func runVersion(env *Env, args []string) error {
|
||||||
if len(args) != 0 {
|
|
||||||
return &ErrUsage{Msg: "version 不接受參數"}
|
|
||||||
}
|
|
||||||
fmt.Fprintf(env.Out, "teai version %s\n", Version)
|
fmt.Fprintf(env.Out, "teai version %s\n", Version)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,289 @@
|
|||||||
|
// 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")
|
||||||
|
if code != int(ExitUsage) {
|
||||||
|
t.Errorf("缺 --repo 應回 ExitUsage,得到 %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...)
|
||||||
|
if code != int(ExitUsage) {
|
||||||
|
t.Errorf("%s 未帶 --yes 應回 ExitUsage(2),得到 %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")
|
||||||
|
if code != int(ExitUsage) || !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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -68,9 +68,9 @@ func TestRunExitCodes(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExtractGlobals(t *testing.T) {
|
func TestParseGlobals(t *testing.T) {
|
||||||
g := defaultGlobals()
|
g := defaultGlobals()
|
||||||
rest, err := extractGlobals(&g, []string{
|
rest, err := parseGlobals(&g, []string{
|
||||||
"--url", "https://example.com",
|
"--url", "https://example.com",
|
||||||
"--token=tok",
|
"--token=tok",
|
||||||
"--config", "/tmp/c.yml",
|
"--config", "/tmp/c.yml",
|
||||||
@@ -95,65 +95,16 @@ func TestExtractGlobals(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestExtractGlobalsAfterCommand(t *testing.T) {
|
func TestParseGlobalsStopsAtCommand(t *testing.T) {
|
||||||
// 全域選項出現在命令之後也應抽出(README:teai next --output table)。
|
|
||||||
g := defaultGlobals()
|
g := defaultGlobals()
|
||||||
rest, err := extractGlobals(&g, []string{"version", "--output", "table"})
|
rest, err := parseGlobals(&g, []string{"version", "--output", "table"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if len(rest) != 1 || rest[0] != "version" {
|
// 命令之後的選項屬於命令,不屬於全域。
|
||||||
t.Fatalf("rest = %v, want [version]", rest)
|
if len(rest) != 3 || rest[0] != "version" {
|
||||||
}
|
|
||||||
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)
|
|
||||||
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"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
// -- 之後全部交回,--url 不再視為全域選項。
|
|
||||||
if len(rest) != 2 || rest[0] != "--url" || rest[1] != "x" {
|
|
||||||
t.Fatalf("rest = %v", rest)
|
t.Fatalf("rest = %v", rest)
|
||||||
}
|
}
|
||||||
if g.Output != gitea.FormatTable {
|
|
||||||
t.Fatalf("output = %v, want table", g.Output)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// errString 把字串轉成 error(測試輔助)。
|
// errString 把字串轉成 error(測試輔助)。
|
||||||
|
|||||||
@@ -23,18 +23,14 @@ func init() {
|
|||||||
register(&command{name: "orgs", usage: "我所屬的組織", run: runOrgs})
|
register(&command{name: "orgs", usage: "我所屬的組織", run: runOrgs})
|
||||||
register(&command{name: "members", usage: "Agents 團隊成員;--has-work 只列有未完成工作者", run: runMembers})
|
register(&command{name: "members", usage: "Agents 團隊成員;--has-work 只列有未完成工作者", run: runMembers})
|
||||||
register(&command{name: "mine", usage: "分派給我、待跟進的 issues", run: runMine})
|
register(&command{name: "mine", usage: "分派給我、待跟進的 issues", run: runMine})
|
||||||
register(&command{name: "pulls", usage: "跨倉庫 PR 跟進清單(--mine/--reviewer/--repo)", run: runPulls})
|
// pulls 由 dailyops_commands.go 註冊(#8):無子命令時走本檔的 runPulls
|
||||||
|
// 工作流清單,有子命令(list/view/create/merge/comment)走日常操作。
|
||||||
register(&command{name: "next", usage: "下一件該做的事", run: runNext})
|
register(&command{name: "next", usage: "下一件該做的事", run: runNext})
|
||||||
}
|
}
|
||||||
|
|
||||||
// errNoRepoFlag 是 --repo 值格式錯誤。
|
// errNoRepoFlag 是 --repo 值格式錯誤。
|
||||||
var errNoRepoFlag = errors.New("--repo 需為 owner/repo 形式")
|
var errNoRepoFlag = errors.New("--repo 需為 owner/repo 形式")
|
||||||
|
|
||||||
// newScannerFunc 建立工作流 Scanner;正式環境用 API client。
|
|
||||||
// 宣告為變數讓接線層測試可注入假 client(不走網路),
|
|
||||||
// 彌補 workflow 套件單元測試覆蓋不到 CLI 分派路徑的缺口。
|
|
||||||
var newScannerFunc = newWorkflowClient
|
|
||||||
|
|
||||||
// newWorkflowClient 依全域選項建立 workflow 所需的 API client。
|
// newWorkflowClient 依全域選項建立 workflow 所需的 API client。
|
||||||
func newWorkflowClient(env *Env) (*workflow.Scanner, error) {
|
func newWorkflowClient(env *Env) (*workflow.Scanner, error) {
|
||||||
token, _, err := gitea.ResolveToken(gitea.AuthOptions{
|
token, _, err := gitea.ResolveToken(gitea.AuthOptions{
|
||||||
@@ -62,7 +58,7 @@ func runWhoami(env *Env, args []string) error {
|
|||||||
if len(args) != 0 {
|
if len(args) != 0 {
|
||||||
return &ErrUsage{Msg: "whoami 不接受參數"}
|
return &ErrUsage{Msg: "whoami 不接受參數"}
|
||||||
}
|
}
|
||||||
s, err := newScannerFunc(env)
|
s, err := newWorkflowClient(env)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -81,7 +77,7 @@ func runOrgs(env *Env, args []string) error {
|
|||||||
if len(args) != 0 {
|
if len(args) != 0 {
|
||||||
return &ErrUsage{Msg: "orgs 不接受參數"}
|
return &ErrUsage{Msg: "orgs 不接受參數"}
|
||||||
}
|
}
|
||||||
s, err := newScannerFunc(env)
|
s, err := newWorkflowClient(env)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -110,7 +106,7 @@ func runMembers(env *Env, args []string) error {
|
|||||||
if fs.NArg() != 0 {
|
if fs.NArg() != 0 {
|
||||||
return &ErrUsage{Msg: "members 不接受位置參數"}
|
return &ErrUsage{Msg: "members 不接受位置參數"}
|
||||||
}
|
}
|
||||||
s, err := newScannerFunc(env)
|
s, err := newWorkflowClient(env)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -130,7 +126,7 @@ func runMine(env *Env, args []string) error {
|
|||||||
if len(args) != 0 {
|
if len(args) != 0 {
|
||||||
return &ErrUsage{Msg: "mine 不接受參數"}
|
return &ErrUsage{Msg: "mine 不接受參數"}
|
||||||
}
|
}
|
||||||
s, err := newScannerFunc(env)
|
s, err := newWorkflowClient(env)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -170,7 +166,7 @@ func runPulls(env *Env, args []string) error {
|
|||||||
}
|
}
|
||||||
owner, name = parts[0], parts[1]
|
owner, name = parts[0], parts[1]
|
||||||
}
|
}
|
||||||
s, err := newScannerFunc(env)
|
s, err := newWorkflowClient(env)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -203,7 +199,7 @@ func runNext(env *Env, args []string) error {
|
|||||||
if len(args) != 0 {
|
if len(args) != 0 {
|
||||||
return &ErrUsage{Msg: "next 不接受參數"}
|
return &ErrUsage{Msg: "next 不接受參數"}
|
||||||
}
|
}
|
||||||
s, err := newScannerFunc(env)
|
s, err := newWorkflowClient(env)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,233 +0,0 @@
|
|||||||
// 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
|
package gitea
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -79,36 +80,80 @@ const MaxLimit = 50
|
|||||||
// getJSON 對 path(相對 baseURL,以 / 開頭)發 GET,把 JSON 回應解到 out。
|
// getJSON 對 path(相對 baseURL,以 / 開頭)發 GET,把 JSON 回應解到 out。
|
||||||
// 失敗時回傳 *ErrAPI。rawQuery 為組好的查詢字串(見 ListOptions.query)。
|
// 失敗時回傳 *ErrAPI。rawQuery 為組好的查詢字串(見 ListOptions.query)。
|
||||||
func (c *Client) getJSON(ctx context.Context, path, rawQuery string, out any) error {
|
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 := *c.baseURL
|
||||||
u.Path += path
|
u.Path += path
|
||||||
u.RawQuery = rawQuery
|
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 {
|
if err != nil {
|
||||||
return &ErrAPI{Op: op, Err: err}
|
return nil, &ErrAPI{Op: op, Err: err}
|
||||||
}
|
}
|
||||||
req.Header.Set("Accept", "application/json")
|
req.Header.Set("Accept", "application/json")
|
||||||
|
if payload != nil && contentType != "" {
|
||||||
|
req.Header.Set("Content-Type", contentType)
|
||||||
|
}
|
||||||
if c.token != "" {
|
if c.token != "" {
|
||||||
req.Header.Set("Authorization", "token "+c.token)
|
req.Header.Set("Authorization", "token "+c.token)
|
||||||
}
|
}
|
||||||
resp, err := c.hc.Do(req)
|
resp, err := c.hc.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return &ErrAPI{Op: op, Err: err}
|
return nil, &ErrAPI{Op: op, Err: err}
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||||
// 把內容讀掉再丟棄,讓連線可重用;錯誤訊息不含回應內容。
|
// 把內容讀掉再丟棄,讓連線可重用;錯誤訊息不含回應內容。
|
||||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
_, _ = 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 {
|
data, err := io.ReadAll(resp.Body)
|
||||||
return nil
|
if err != nil {
|
||||||
|
return nil, &ErrAPI{Op: op, Err: err}
|
||||||
}
|
}
|
||||||
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
|
if out != nil && len(data) > 0 {
|
||||||
return &ErrAPI{Op: op, Err: fmt.Errorf("decode response: %w", err)}
|
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)使用。
|
// GetJSON 是 getJSON 的公開介面,供非清單端點(如 /user)使用。
|
||||||
|
|||||||
@@ -198,16 +198,6 @@ type orgIssue struct {
|
|||||||
Issue Issue
|
Issue Issue
|
||||||
}
|
}
|
||||||
|
|
||||||
// commentsFor 取回 issue/PR 的留言;number 缺漏(0)時直接視為無留言,
|
|
||||||
// 不打 API(gitea.py 在 number 為 None 時跳過留言檢查的語義——
|
|
||||||
// 避免拿 0 去 issues/0/comments 觸發 404 中斷整個掃描)。
|
|
||||||
func (s *Scanner) commentsFor(owner, repo string, number int64) ([]Comment, error) {
|
|
||||||
if number <= 0 {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return s.Client.ListComments(owner, repo, number)
|
|
||||||
}
|
|
||||||
|
|
||||||
// collectMemberIssues 跨組織收集分派給 members(至少一人)且最後一則留言
|
// collectMemberIssues 跨組織收集分派給 members(至少一人)且最後一則留言
|
||||||
// 不是 assignee 的 open issues(gitea.py 的 for_all_organizations)。
|
// 不是 assignee 的 open issues(gitea.py 的 for_all_organizations)。
|
||||||
func (s *Scanner) collectMemberIssues(members []string) ([]orgIssue, error) {
|
func (s *Scanner) collectMemberIssues(members []string) ([]orgIssue, error) {
|
||||||
@@ -227,7 +217,7 @@ func (s *Scanner) collectMemberIssues(members []string) ([]orgIssue, error) {
|
|||||||
if !AssigneeOverlaps(issue, members) {
|
if !AssigneeOverlaps(issue, members) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
comments, err := s.commentsFor(owner, repo, issue.issueNumber())
|
comments, err := s.Client.ListComments(owner, repo, issue.issueNumber())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -285,7 +275,7 @@ func (s *Scanner) Pulls(mine, reviewer bool) ([]PullItem, error) {
|
|||||||
for _, rp := range repoPulls {
|
for _, rp := range repoPulls {
|
||||||
for i := range rp.Pulls {
|
for i := range rp.Pulls {
|
||||||
pr := &rp.Pulls[i]
|
pr := &rp.Pulls[i]
|
||||||
comments, err := s.commentsFor(rp.Owner, rp.Repo, pr.Number)
|
comments, err := s.Client.ListComments(rp.Owner, rp.Repo, pr.Number)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -341,7 +331,7 @@ func (s *Scanner) usernamesWithUnfinishedWork(members []string) (map[string]bool
|
|||||||
for _, rp := range repoPulls {
|
for _, rp := range repoPulls {
|
||||||
for i := range rp.Pulls {
|
for i := range rp.Pulls {
|
||||||
pr := &rp.Pulls[i]
|
pr := &rp.Pulls[i]
|
||||||
comments, err := s.commentsFor(rp.Owner, rp.Repo, pr.Number)
|
comments, err := s.Client.ListComments(rp.Owner, rp.Repo, pr.Number)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user