Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9948357f52 | ||
|
|
0b0c3cefcb | ||
|
|
a8c1f3e018 | ||
|
|
0ed6f262c8 | ||
|
|
fb2990dc04 | ||
|
|
67cafcff59 | ||
|
|
4a34def1f5 | ||
|
|
c4fb641094 | ||
|
|
f7d63d6e8f | ||
|
|
f481377b9a | ||
|
|
b2dd2f3aac | ||
|
|
a86803d336 |
@@ -11,12 +11,47 @@ teai 是 Gitea 的命令列(CLI)工具,以更完整、更可靠的方式
|
||||
|
||||
## 安裝與建置
|
||||
|
||||
需要 Go 1.26 以上。
|
||||
### 需求
|
||||
|
||||
- **Go 1.26 以上**(`go version` 確認;本倉庫僅用標準庫,離線可建置)
|
||||
- **git**
|
||||
- Gitea 帳號的 **API token**(設定階段使用;在 Gitea「設定 → 應用程式」產生)
|
||||
|
||||
### 從原始碼建置
|
||||
|
||||
```sh
|
||||
git clone https://gitea.alterminal.com/alterminal/teai.git
|
||||
cd teai
|
||||
go build -o teai ./cmd/teai
|
||||
install -Dm755 teai ~/.local/bin/teai # 或複製到任何 PATH 內目錄
|
||||
teai version # 驗證:teai version 0.1.0-dev
|
||||
```
|
||||
|
||||
也可以直接裝進 `GOBIN`(預設 `~/go/bin`;該目錄已在 PATH 時最省事):
|
||||
|
||||
```sh
|
||||
go install ./cmd/teai
|
||||
```
|
||||
|
||||
> **注意:** `go install gitea.alterminal.com/alterminal/teai/cmd/teai@latest` 目前**不可用**——
|
||||
> module 尚未發佈任何 tag,`@latest` 會解析到任意中繼 commit(且 #21 修復前 main 建置失敗)。
|
||||
> 請在 clone 目錄內以版本控制的方式建置;發佈 tag 後再提供 `teai@<version>` 安裝路徑。
|
||||
|
||||
### 登入設定(首次使用)
|
||||
|
||||
teai 與 `tea` 共用同一份組態檔;若 `tea whoami` 已可正常輸出,可跳過本節。
|
||||
|
||||
```sh
|
||||
teai login add --url https://gitea.alterminal.com
|
||||
# 未給 --token 時自 stdin 讀一行:貼上 token 後按 Enter(不會進 shell 歷史)
|
||||
teai whoami # 驗證:應輸出 {"username":"<你的帳號>"}
|
||||
```
|
||||
|
||||
- token 驗證失敗(HTTP 401)不會寫入組態,結束碼 3。
|
||||
- 組態檔:`--config`/`TEA_CONFIG` 指定,預設 `~/.config/tea/config.yml`;teai 採行級編輯,
|
||||
不會改壞 tea 也在使用的欄位,檔案權限 `0600`。
|
||||
- 多站台以 `--name` 區分、`teai login default <名稱>` 切換預設;詳見下方 [`teai login`](#teai-login--管理登入) 一節。
|
||||
|
||||
## 指令設計
|
||||
|
||||
> 工作流規則的唯一來源是 [`alterminal/agents`](https://gitea.alterminal.com/alterminal/agents) 的 `AGENTS.md`;
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
// cmd/xcheck 是 #7 的交叉驗證工具(不屬於 teai 本體,PR 內附驗證說明)。
|
||||
//
|
||||
// 以真實 Gitea API 資料源實作 workflow.Source,跑 Go 版 ScanStalled,
|
||||
// 再與 gitea.py stalled(行為基準)的 JSON 輸出逐欄位比對。
|
||||
// 建立限制:與 teai 本體一致,僅標準庫。
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.alterminal.com/alterminal/teai/internal/workflow"
|
||||
)
|
||||
|
||||
// apiSource 以 Gitea API 實作 workflow.Source。
|
||||
type apiSource struct {
|
||||
base string
|
||||
token string
|
||||
hc *http.Client
|
||||
}
|
||||
|
||||
func (s *apiSource) get(path string, params map[string]string) ([]byte, int, error) {
|
||||
u := s.base + path
|
||||
if len(params) > 0 {
|
||||
q := url.Values{}
|
||||
for k, v := range params {
|
||||
q.Set(k, v)
|
||||
}
|
||||
u += "?" + q.Encode()
|
||||
}
|
||||
req, err := http.NewRequest("GET", u, nil)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Authorization", "token "+s.token)
|
||||
resp, err := s.hc.Do(req)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
return body, resp.StatusCode, err
|
||||
}
|
||||
|
||||
func (s *apiSource) getJSON(path string, params map[string]string, out any) error {
|
||||
body, code, err := s.get(path, params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if code != 200 {
|
||||
return fmt.Errorf("GET %s: HTTP %d", path, code)
|
||||
}
|
||||
return json.Unmarshal(body, out)
|
||||
}
|
||||
|
||||
// listAll 分頁拉取清單類 API(Gitea 上限 50/頁)。
|
||||
func (s *apiSource) listAll(path string, params map[string]string, out any) error {
|
||||
var items []json.RawMessage
|
||||
page := 1
|
||||
for {
|
||||
q := map[string]string{"page": fmt.Sprint(page), "limit": "50"}
|
||||
for k, v := range params {
|
||||
q[k] = v
|
||||
}
|
||||
var chunk json.RawMessage
|
||||
if err := s.getJSON(path, q, &chunk); err != nil {
|
||||
return err
|
||||
}
|
||||
var arr []json.RawMessage
|
||||
if err := json.Unmarshal(chunk, &arr); err != nil {
|
||||
return fmt.Errorf("GET %s: 回傳非陣列", path)
|
||||
}
|
||||
items = append(items, arr...)
|
||||
if len(arr) < 50 {
|
||||
break
|
||||
}
|
||||
page++
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteByte('[')
|
||||
for i, item := range items {
|
||||
if i > 0 {
|
||||
b.WriteByte(',')
|
||||
}
|
||||
b.Write(item)
|
||||
}
|
||||
b.WriteByte(']')
|
||||
return json.Unmarshal([]byte(b.String()), out)
|
||||
}
|
||||
|
||||
// CurrentUser 以 token 呼叫 /user 取實際帳號,與 gitea.py 的
|
||||
// get_current_username() 同源(token 決定帳號,不接受環境變數覆寫,
|
||||
// 失敗即報錯退出,不靜默退回預設值)。
|
||||
func (s *apiSource) CurrentUser() (string, error) {
|
||||
var user struct {
|
||||
Username string `json:"username"`
|
||||
Login string `json:"login"`
|
||||
}
|
||||
if err := s.getJSON("user", nil, &user); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if user.Username != "" {
|
||||
return user.Username, nil
|
||||
}
|
||||
if user.Login != "" {
|
||||
return user.Login, nil
|
||||
}
|
||||
return "", fmt.Errorf("無法從 Gitea API /user 取得目前帳號")
|
||||
}
|
||||
|
||||
func (s *apiSource) MyOrganizations() ([]string, error) {
|
||||
var orgs []struct {
|
||||
Username string `json:"username"`
|
||||
}
|
||||
if err := s.listAll("user/orgs", nil, &orgs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names := make([]string, 0, len(orgs))
|
||||
for _, o := range orgs {
|
||||
if o.Username != "" {
|
||||
names = append(names, o.Username)
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (s *apiSource) OrganizationRepositories(org string) ([]workflow.Repository, error) {
|
||||
var repos []workflow.Repository
|
||||
if err := s.listAll("orgs/"+org+"/repos", nil, &repos); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return repos, nil
|
||||
}
|
||||
|
||||
func (s *apiSource) OpenIssues(owner, repo string) ([]workflow.Issue, error) {
|
||||
var issues []workflow.Issue
|
||||
// 與 gitea.py 一致:type=issues 排除 PR;state=open。
|
||||
if err := s.listAll(fmt.Sprintf("repos/%s/%s/issues", owner, repo), map[string]string{"type": "issues", "state": "open"}, &issues); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return issues, nil
|
||||
}
|
||||
|
||||
func (s *apiSource) OpenPulls(owner, repo string) ([]workflow.PullRequest, error) {
|
||||
var pulls []workflow.PullRequest
|
||||
if err := s.listAll(fmt.Sprintf("repos/%s/%s/pulls", owner, repo), map[string]string{"state": "open"}, &pulls); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pulls, nil
|
||||
}
|
||||
|
||||
func (s *apiSource) IssueComments(owner, repo string, number int) ([]workflow.Comment, error) {
|
||||
var comments []workflow.Comment
|
||||
if err := s.listAll(fmt.Sprintf("repos/%s/%s/issues/%d/comments", owner, repo, number), nil, &comments); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return comments, nil
|
||||
}
|
||||
|
||||
func (s *apiSource) TryGetIssue(owner, repo string, number int) (workflow.Issue, bool, error) {
|
||||
var issue workflow.Issue
|
||||
body, code, err := s.get(fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, number), nil)
|
||||
if err != nil {
|
||||
return workflow.Issue{}, false, nil
|
||||
}
|
||||
if code != 200 {
|
||||
return workflow.Issue{}, false, nil
|
||||
}
|
||||
if err := json.Unmarshal(body, &issue); err != nil {
|
||||
return workflow.Issue{}, false, nil
|
||||
}
|
||||
return issue, true, nil
|
||||
}
|
||||
|
||||
// loadEnv 讀 agents 倉庫的 .env(ACCESS_TOKEN、GITEA_API_DOMAIN)。
|
||||
func loadEnv(path string) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
k, v, ok := strings.Cut(line, "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
k = strings.TrimSpace(k)
|
||||
v = strings.Trim(strings.TrimSpace(v), "'\"")
|
||||
if os.Getenv(k) == "" {
|
||||
os.Setenv(k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// --xrefs 模式:從 stdin 讀文字,輸出解析後的引用目標(與 gitea.py
|
||||
// _resolve_xref_targets 對照用)。組織與倉庫清單來自真實 API。
|
||||
if len(os.Args) > 1 && os.Args[1] == "--xrefs" {
|
||||
xrefsMain()
|
||||
return
|
||||
}
|
||||
loadEnv(os.Getenv("HOME") + "/agents/.env")
|
||||
domain := os.Getenv("GITEA_API_DOMAIN")
|
||||
token := os.Getenv("ACCESS_TOKEN")
|
||||
if domain == "" || token == "" {
|
||||
fmt.Fprintln(os.Stderr, "缺少 GITEA_API_DOMAIN/ACCESS_TOKEN")
|
||||
os.Exit(1)
|
||||
}
|
||||
src := &apiSource{
|
||||
base: "https://" + domain + "/api/v1/",
|
||||
token: token,
|
||||
hc: &http.Client{Timeout: 30 * time.Second},
|
||||
}
|
||||
username, err := src.CurrentUser()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "CurrentUser:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
hours := 4.0
|
||||
items, scanErr := workflow.ScanStalled(src, username, hours, time.Now())
|
||||
if scanErr != nil {
|
||||
fmt.Fprintln(os.Stderr, "ScanStalled:", scanErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
// json.Marshal* 會把 <、>、& 轉義成 \u003c 等(含自訂 MarshalJSON 的輸出),
|
||||
// 與 gitea.py(ensure_ascii=False)位元組不相容;必須停用 HTML 轉義。
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(items); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Encode:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Print(buf.String())
|
||||
}
|
||||
|
||||
// xrefsMain 對 stdin 的每行文字解析引用目標並輸出 JSON。
|
||||
func xrefsMain() {
|
||||
loadEnv(os.Getenv("HOME") + "/agents/.env")
|
||||
domain := os.Getenv("GITEA_API_DOMAIN")
|
||||
token := os.Getenv("ACCESS_TOKEN")
|
||||
if domain == "" || token == "" {
|
||||
fmt.Fprintln(os.Stderr, "缺少 GITEA_API_DOMAIN/ACCESS_TOKEN")
|
||||
os.Exit(1)
|
||||
}
|
||||
src := &apiSource{
|
||||
base: "https://" + domain + "/api/v1/",
|
||||
token: token,
|
||||
hc: &http.Client{Timeout: 30 * time.Second},
|
||||
}
|
||||
orgs, err := src.MyOrganizations()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "MyOrganizations:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
myOrgs := map[string]bool{}
|
||||
for _, o := range orgs {
|
||||
myOrgs[o] = true
|
||||
}
|
||||
data, _ := io.ReadAll(os.Stdin)
|
||||
repos, _ := src.OrganizationRepositories("alterminal")
|
||||
names := make([]string, 0, len(repos))
|
||||
for _, r := range repos {
|
||||
names = append(names, r.Name)
|
||||
}
|
||||
targets, err := workflow.ResolveXrefTargets("alterminal", "agents", []string{string(data)}, myOrgs, func(string) ([]string, error) {
|
||||
return names, nil
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "ResolveXrefTargets:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(targets); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "Encode:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Print(buf.String())
|
||||
}
|
||||
+36
-3
@@ -150,10 +150,31 @@ var globalFlags = map[string]bool{
|
||||
"--timeout": true,
|
||||
}
|
||||
|
||||
// reservedFlags 回傳 dispatch 不得搶走的旗標名稱(含 -- 前綴):這些
|
||||
// 旗標屬於目前命令(或其子命令),即使與全域選項同名也必須原樣留給
|
||||
// 命令剖析。目前唯一與全域同名的是 login add 的 --url/--token
|
||||
// (README「teai login add --url … --token …」)。其餘命令的旗標
|
||||
// (--repo、--has-work、--mine……)本來就不在 globalFlags 內,不受影響。
|
||||
func reservedFlags(name string) map[string]bool {
|
||||
reserved := make(map[string]bool)
|
||||
for _, f := range commandReservedFlags[name] {
|
||||
reserved[f] = true
|
||||
}
|
||||
return reserved
|
||||
}
|
||||
|
||||
// commandReservedFlags 登記每個命令「與全域選項同名」的自有旗標。
|
||||
// 命令旗標優先留給命令;新命令有同姓旗標時在這裡登記(#18)。
|
||||
var commandReservedFlags = map[string][]string{
|
||||
"login": {"--url", "--token"},
|
||||
}
|
||||
|
||||
// extractGlobals 從 args 中「抽取」全域選項(可出現在命令之後、與命令
|
||||
// 旗標交錯),其餘引數依原順序保留給子命令剖析。未知的選項一律留給
|
||||
// 子命令處理(可能是命令旗標,如 --has-work),不在這裡報錯。
|
||||
func extractGlobals(g *Globals, args []string) ([]string, error) {
|
||||
// reserved 是目前命令保留的旗標名稱(含 -- 前綴,見 reservedFlags):
|
||||
// 列於其中的選項即使與全域同名也原樣留給命令,命令旗標優先(#18)。
|
||||
func extractGlobals(g *Globals, args []string, reserved map[string]bool) ([]string, error) {
|
||||
rest := make([]string, 0, len(args))
|
||||
applyGlobal := func(name, value string) error {
|
||||
switch name {
|
||||
@@ -197,6 +218,17 @@ func extractGlobals(g *Globals, args []string) ([]string, error) {
|
||||
continue
|
||||
}
|
||||
name, inline, hasInline := strings.Cut(arg, "=")
|
||||
if reserved[name] {
|
||||
// 命令保留旗標:即使與全域選項同名也留給命令剖析(#18)。
|
||||
rest = append(rest, arg)
|
||||
if !hasInline && i+1 < len(args) {
|
||||
// 旗標值跟在下一個引數;一併保留,不當成全域值。
|
||||
rest = append(rest, args[i+1])
|
||||
i++
|
||||
}
|
||||
i++
|
||||
continue
|
||||
}
|
||||
_, ok := globalFlags[name]
|
||||
if !ok {
|
||||
// 不是全域選項:留給子命令(可能是 --has-work 這類命令旗標)。
|
||||
@@ -293,11 +325,12 @@ func parseGlobals(g *Globals, args []string) ([]string, error) {
|
||||
// 旗標剖析交由各命令自行處理(不同命令有不同旗標,如 pulls --mine);
|
||||
// 全域選項允許出現在命令之後(README 範例:teai next --output table),
|
||||
// dispatch 先從 args 剝離全域選項併入 Globals,其餘(含命令自己的旗標,
|
||||
// 如 --has-work)原樣交給命令,不會誤判為未知全域選項。
|
||||
// 如 --has-work)原樣交給命令,不會誤判為未知全域選項。與全域選項
|
||||
// 同名的命令旗標(登記於 commandReservedFlags)優先留給命令(#18)。
|
||||
func dispatch(env *Env, name string, args []string) int {
|
||||
cmd := commands[name]
|
||||
g := env.Globals
|
||||
rest, err := extractGlobals(&g, args)
|
||||
rest, err := extractGlobals(&g, args, reservedFlags(name))
|
||||
if err != nil {
|
||||
fmt.Fprintf(env.Err, "teai: %v\n\n", err)
|
||||
printUsage(env.Err)
|
||||
|
||||
@@ -51,8 +51,10 @@ func TestRunVersion(t *testing.T) {
|
||||
|
||||
func TestRunUnknownCommand(t *testing.T) {
|
||||
_, stderr, code := run("no-such-command")
|
||||
if code != int(ExitUsage) {
|
||||
t.Errorf("未知命令應回 ExitUsage(%d),得到 %d", int(ExitUsage), code)
|
||||
// 直接對照 README「輸出與結束碼」的數值(用法錯誤=2),
|
||||
// 不以常數互比,避免常數與規格再次脫鉤(#10)。
|
||||
if code != 2 {
|
||||
t.Errorf("未知命令應回 2(README 用法錯誤),得到 %d", code)
|
||||
}
|
||||
if !strings.Contains(stderr, "unknown command") {
|
||||
t.Errorf("未知命令應在 stderr 說明,得到:%q", stderr)
|
||||
|
||||
@@ -53,8 +53,9 @@ func TestIssuesListRequiresRepo(t *testing.T) {
|
||||
t.Errorf("不應發出任何請求")
|
||||
})
|
||||
_, stderr, code := run("issues", "list")
|
||||
if code != int(ExitUsage) {
|
||||
t.Errorf("缺 --repo 應回 ExitUsage,得到 %d", code)
|
||||
// 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
|
||||
if code != 2 {
|
||||
t.Errorf("缺 --repo 應回 2(README 用法錯誤),得到 %d", code)
|
||||
}
|
||||
if !strings.Contains(stderr, "--repo") {
|
||||
t.Errorf("錯誤訊息應提及 --repo,得到:%s", stderr)
|
||||
@@ -110,8 +111,9 @@ func TestWriteCommandsRequireYes(t *testing.T) {
|
||||
t.Errorf("%s:未帶 --yes 不得發出請求(%s %s)", tc.name, r.Method, r.URL.Path)
|
||||
})
|
||||
_, stderr, code := run(tc.args...)
|
||||
if code != int(ExitUsage) {
|
||||
t.Errorf("%s 未帶 --yes 應回 ExitUsage(2),得到 %d", tc.name, code)
|
||||
// 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
|
||||
if code != 2 {
|
||||
t.Errorf("%s 未帶 --yes 應回 2(README 用法錯誤),得到 %d", tc.name, code)
|
||||
}
|
||||
if !strings.Contains(stderr, "--yes") {
|
||||
t.Errorf("%s 錯誤訊息應提及 --yes,得到:%s", tc.name, stderr)
|
||||
@@ -235,7 +237,8 @@ func TestAPIDirectPassthrough(t *testing.T) {
|
||||
}
|
||||
|
||||
_, stderr, code := run("api", "--method", "POST", "/version")
|
||||
if code != int(ExitUsage) || !strings.Contains(stderr, "--yes") {
|
||||
// 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
|
||||
if code != 2 || !strings.Contains(stderr, "--yes") {
|
||||
t.Errorf("POST 未帶 --yes 應回 2 並提及 --yes,得到 %d:%s", code, stderr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,20 +10,22 @@ import (
|
||||
)
|
||||
|
||||
func TestExitCodeMapping(t *testing.T) {
|
||||
// want 直接寫 README「輸出與結束碼」的數值(0/2/3;內部錯誤 1),
|
||||
// 不以常數互比,避免常數與規格再次脫鉤(#10)。
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want ExitCode
|
||||
want int
|
||||
}{
|
||||
{"usage error", &ErrUsage{Msg: "bad flag"}, ExitUsage},
|
||||
{"api error 401", &gitea.ErrAPI{StatusCode: 401, Op: "GET /api/v1/user"}, ExitAPI},
|
||||
{"api error transport", &gitea.ErrAPI{Op: "GET /api/v1/user", Err: errString("dial tcp")}, ExitAPI},
|
||||
{"wrapped api error", wrapped(&gitea.ErrAPI{StatusCode: 500}), ExitAPI},
|
||||
{"other error", errString("boom"), ExitInternal},
|
||||
{"nil maps to OK", nil, ExitOK},
|
||||
{"usage error", &ErrUsage{Msg: "bad flag"}, 2},
|
||||
{"api error 401", &gitea.ErrAPI{StatusCode: 401, Op: "GET /api/v1/user"}, 3},
|
||||
{"api error transport", &gitea.ErrAPI{Op: "GET /api/v1/user", Err: errString("dial tcp")}, 3},
|
||||
{"wrapped api error", wrapped(&gitea.ErrAPI{StatusCode: 500}), 3},
|
||||
{"other error", errString("boom"), 1},
|
||||
{"nil maps to OK", nil, 0},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := exitCodeFor(tc.err); got != tc.want {
|
||||
if got := int(exitCodeFor(tc.err)); got != tc.want {
|
||||
t.Errorf("%s: exitCodeFor = %d, want %d", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
@@ -77,7 +79,7 @@ func TestExtractGlobals(t *testing.T) {
|
||||
"--output", "table",
|
||||
"--timeout", "45s",
|
||||
"next",
|
||||
})
|
||||
}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -98,7 +100,7 @@ func TestExtractGlobals(t *testing.T) {
|
||||
func TestExtractGlobalsAfterCommand(t *testing.T) {
|
||||
// 全域選項出現在命令之後也應抽出(README:teai next --output table)。
|
||||
g := defaultGlobals()
|
||||
rest, err := extractGlobals(&g, []string{"version", "--output", "table"})
|
||||
rest, err := extractGlobals(&g, []string{"version", "--output", "table"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -122,7 +124,7 @@ func TestExtractGlobalsKeepsCommandFlags(t *testing.T) {
|
||||
}
|
||||
for _, args := range cases {
|
||||
g := defaultGlobals()
|
||||
rest, err := extractGlobals(&g, args)
|
||||
rest, err := extractGlobals(&g, args, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("extractGlobals(%v) 不應報錯:%v", args, err)
|
||||
}
|
||||
@@ -143,7 +145,7 @@ func TestExtractGlobalsKeepsCommandFlags(t *testing.T) {
|
||||
|
||||
func TestExtractGlobalsDoubleDashStops(t *testing.T) {
|
||||
g := defaultGlobals()
|
||||
rest, err := extractGlobals(&g, []string{"--output", "table", "--", "--url", "x"})
|
||||
rest, err := extractGlobals(&g, []string{"--output", "table", "--", "--url", "x"}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -156,6 +158,56 @@ func TestExtractGlobalsDoubleDashStops(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractGlobalsReservedFlags 驗證 #18:與全域同名的命令旗標
|
||||
// (登記於 commandReservedFlags)必須留給命令,其餘全域選項照常抽取。
|
||||
func TestExtractGlobalsReservedFlags(t *testing.T) {
|
||||
g := defaultGlobals()
|
||||
rest, err := extractGlobals(&g, []string{
|
||||
"add",
|
||||
"--url", "https://srv.example.com", // login add 自有旗標:保留
|
||||
"--token=tok", // 同上(inline 形式):保留
|
||||
"--name", "test-site",
|
||||
"--output", "table", // 非保留:仍是全域
|
||||
}, reservedFlags("login"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"add", "--url", "https://srv.example.com", "--token=tok", "--name", "test-site"}
|
||||
if len(rest) != len(want) {
|
||||
t.Fatalf("rest = %v, want %v", rest, want)
|
||||
}
|
||||
for i := range want {
|
||||
if rest[i] != want[i] {
|
||||
t.Fatalf("rest = %v, want %v", rest, want)
|
||||
}
|
||||
}
|
||||
if g.Output != gitea.FormatTable {
|
||||
t.Fatalf("output = %v, want table", g.Output)
|
||||
}
|
||||
if g.URL != defaultGlobals().URL || g.Token != "" {
|
||||
t.Fatalf("reserved flags must not leak into globals: %+v", g)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractGlobalsNonReservedCommand 驗證 #13 行為不回歸:未登記保留
|
||||
// 旗標的命令(如 next/members/pulls),命令後的全域選項照常抽取、
|
||||
// 命令自己的旗標(--has-work 等)原樣保留。
|
||||
func TestExtractGlobalsNonReservedCommand(t *testing.T) {
|
||||
g := defaultGlobals()
|
||||
rest, err := extractGlobals(&g, []string{
|
||||
"members", "--has-work", "--output", "table",
|
||||
}, reservedFlags("members"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rest) != 2 || rest[0] != "members" || rest[1] != "--has-work" {
|
||||
t.Fatalf("rest = %v, want [members --has-work]", rest)
|
||||
}
|
||||
if g.Output != gitea.FormatTable {
|
||||
t.Fatalf("output = %v, want table", g.Output)
|
||||
}
|
||||
}
|
||||
|
||||
// errString 把字串轉成 error(測試輔助)。
|
||||
type errStr string
|
||||
|
||||
|
||||
@@ -145,8 +145,9 @@ func TestLoginAddRejected401NoWrite(t *testing.T) {
|
||||
`)
|
||||
_, stderr, code := run(append(prefix,
|
||||
"--url", srv.URL, "login", "add", "--token", "bad-tok")...)
|
||||
if code != int(ExitAPI) {
|
||||
t.Fatalf("401 should exit 3, got %d (stderr %s)", code, stderr)
|
||||
// 401 是 API 錯誤;對照 README「輸出與結束碼」=3(#10)。
|
||||
if code != 3 {
|
||||
t.Fatalf("401 should exit 3 (README api error), got %d (stderr %s)", code, stderr)
|
||||
}
|
||||
if !strings.Contains(stderr, "401") {
|
||||
t.Fatalf("stderr should mention 401: %s", stderr)
|
||||
@@ -250,8 +251,9 @@ func TestLoginRemoveAsksConfirmation(t *testing.T) {
|
||||
func TestLoginUnknownSubcommandUsage(t *testing.T) {
|
||||
prefix, _ := loginTestEnv(t, "")
|
||||
_, stderr, code := run(append(prefix, "login", "bogus")...)
|
||||
if code != int(ExitUsage) {
|
||||
t.Fatalf("want exit 2, got %d", code)
|
||||
// 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
|
||||
if code != 2 {
|
||||
t.Fatalf("want exit 2 (README usage), got %d", code)
|
||||
}
|
||||
if !strings.Contains(stderr, "unknown login subcommand") {
|
||||
t.Fatalf("stderr: %s", stderr)
|
||||
@@ -261,8 +263,9 @@ func TestLoginUnknownSubcommandUsage(t *testing.T) {
|
||||
func TestLoginNoSubcommandUsage(t *testing.T) {
|
||||
prefix, _ := loginTestEnv(t, "")
|
||||
_, stderr, code := run(append(prefix, "login")...)
|
||||
if code != int(ExitUsage) {
|
||||
t.Fatalf("want exit 2, got %d", code)
|
||||
// 對照 README「輸出與結束碼」:用法錯誤=2(#10)。
|
||||
if code != 2 {
|
||||
t.Fatalf("want exit 2 (README usage), got %d", code)
|
||||
}
|
||||
if !strings.Contains(stderr, "subcommand") {
|
||||
t.Fatalf("stderr: %s", stderr)
|
||||
@@ -272,8 +275,9 @@ func TestLoginNoSubcommandUsage(t *testing.T) {
|
||||
func TestLoginRemoveNotFound(t *testing.T) {
|
||||
prefix, _ := loginTestEnv(t, "logins: []\n")
|
||||
_, stderr, code := run(append(prefix, "login", "remove", "--yes", "ghost")...)
|
||||
if code != int(ExitInternal) {
|
||||
t.Fatalf("want exit 1, got %d", code)
|
||||
// ExitInternal 不在 README 保證範圍;此處固定為 1(內部錯誤,#10)。
|
||||
if code != 1 {
|
||||
t.Fatalf("want exit 1 (internal), got %d", code)
|
||||
}
|
||||
if !strings.Contains(stderr, `login "ghost" not found`) {
|
||||
t.Fatalf("stderr: %s", stderr)
|
||||
|
||||
@@ -0,0 +1,626 @@
|
||||
// 套件 workflow 實作 gitea.py 工作流的核心判定邏輯(teai issue #7)。
|
||||
//
|
||||
// 行為基準是 alterminal/agents 的 scripts/lib/gitea.py:xref 解析
|
||||
// (#N、repo#N、owner/repo#N)與 stalled 停滯掃描(reason 分類、催促冷卻、
|
||||
// 父追蹤項把子項活動計入 last_activity)。判定規則以 AGENTS.md 為準,
|
||||
// 本套件只實作、不改義。
|
||||
//
|
||||
// 資料以 Source 介面注入:CLI 層負責拉取 API,測試用假資料源,
|
||||
// 邏輯本身離線可測(README 設計原則 4:可直接替換原型、交叉驗證)。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// 常數與 gitea.py 保持一致(STALLED_DEFAULT_HOURS、NUDGE_COOLDOWN_HOURS)。
|
||||
const (
|
||||
// StalledDefaultHours 是 stalled 掃描的預設門檻(小時)。
|
||||
StalledDefaultHours = 4.0
|
||||
// NudgeCooldownHours 是「最後留言出自目前帳號」項目的催促冷卻(小時)。
|
||||
NudgeCooldownHours = 24.0
|
||||
)
|
||||
|
||||
// xrefPattern 對應 gitea.py 的 XREF_PATTERN:#N、repo#N、owner/repo#N。
|
||||
//
|
||||
// 前面不得是文數字/底線/斜線(避免切進 alterminal/bear#47 的後半段);
|
||||
// owner/repo 兩段之間必須有斜線(避免把 bear-cli#10 誤判成 cli#10)。
|
||||
// Go 的 regexp 不支援 lookbehind,改在掃描時檢查前一字元。
|
||||
var xrefPattern = regexp.MustCompile(`([A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)?)?#(\d+)`)
|
||||
|
||||
// User 是 Gitea user 物件的精簡投影。
|
||||
type User struct {
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
// Comment 是 issue/PR 留言的精簡投影。
|
||||
type Comment struct {
|
||||
User User `json:"user"`
|
||||
Body string `json:"body"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// Author 回傳留言作者帳號;空字串表示無法判定。
|
||||
func (c Comment) Author() string { return c.User.Username }
|
||||
|
||||
// Issue 是 issue 的精簡投影(Gitea /repos/{owner}/{repo}/issues,不含 PR)。
|
||||
type Issue struct {
|
||||
Number int `json:"number"`
|
||||
Title string `json:"title"`
|
||||
State string `json:"state"`
|
||||
Body string `json:"body"`
|
||||
Author User `json:"user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ClosedAt *time.Time `json:"closed_at,omitempty"`
|
||||
// URL 對應 API 的 html_url。
|
||||
URL string `json:"html_url"`
|
||||
Assignees []User `json:"assignees"`
|
||||
Repository Reference `json:"repository"`
|
||||
// PullRequest 非 nil 表示這其實是 PR(Gitea 的 /issues API 兩者都回)。
|
||||
PullRequest any `json:"pull_request,omitempty"`
|
||||
}
|
||||
|
||||
// Reference 是 repository 物件的精簡投影(issue 物件帶 full_name)。
|
||||
type Reference struct {
|
||||
FullName string `json:"full_name"`
|
||||
}
|
||||
|
||||
// Ref 是 PR base/head 的精簡投影(PR 物件沒有 repository 欄位,改讀 base/head.repo)。
|
||||
type Ref struct {
|
||||
Repo Reference `json:"repo"`
|
||||
}
|
||||
|
||||
// PullRequest 是 /repos/{owner}/{repo}/pulls 物件的精簡投影。
|
||||
type PullRequest struct {
|
||||
Number int `json:"number"`
|
||||
Title string `json:"title"`
|
||||
State string `json:"state"`
|
||||
Author User `json:"user"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ClosedAt *time.Time `json:"closed_at,omitempty"`
|
||||
// URL 對應 API 的 html_url。
|
||||
URL string `json:"html_url"`
|
||||
Base Ref `json:"base"`
|
||||
Head Ref `json:"head"`
|
||||
RequestedReviewers []User `json:"requested_reviewers"`
|
||||
}
|
||||
|
||||
// FullName 回傳 "owner/repo";PR 沒有 repository 欄位,改讀 base(再退 head)。
|
||||
func (p PullRequest) FullName() string {
|
||||
if p.Base.Repo.FullName != "" {
|
||||
return p.Base.Repo.FullName
|
||||
}
|
||||
return p.Head.Repo.FullName
|
||||
}
|
||||
|
||||
// Repository 是 /orgs/{org}/repos 物件的精簡投影。
|
||||
type Repository struct {
|
||||
Name string `json:"name"`
|
||||
Empty bool `json:"empty"`
|
||||
HasPullRequests *bool `json:"has_pull_requests"`
|
||||
}
|
||||
|
||||
// Item 是 stalled 掃描的單筆輸出(欄位對應 gitea.py 的 find_stalled_work)。
|
||||
type Item struct {
|
||||
Type string
|
||||
Repo string
|
||||
Number int
|
||||
Title string
|
||||
URL string
|
||||
Assignees []string
|
||||
Author string
|
||||
Reviewers []string
|
||||
LastCommentBy string
|
||||
LastActivityAt time.Time
|
||||
StalledHours float64
|
||||
Reason string
|
||||
ChildActivity []Child
|
||||
}
|
||||
|
||||
// MarshalJSON 輸出鍵集與鍵序與 gitea.py 完全一致的物件:
|
||||
// issue 帶 assignees;pull 帶 author 與 reviewers;
|
||||
// child_activity 僅在有子項摘要時輸出。
|
||||
func (i Item) MarshalJSON() ([]byte, error) {
|
||||
var b strings.Builder
|
||||
b.WriteString(`{"type":`)
|
||||
writeJSON(&b, i.Type)
|
||||
b.WriteString(`,"repo":`)
|
||||
writeJSON(&b, i.Repo)
|
||||
b.WriteString(`,"number":`)
|
||||
fmt.Fprintf(&b, "%d", i.Number)
|
||||
b.WriteString(`,"title":`)
|
||||
writeJSON(&b, i.Title)
|
||||
b.WriteString(`,"url":`)
|
||||
writeJSON(&b, i.URL)
|
||||
if i.Type == "pull" {
|
||||
b.WriteString(`,"author":`)
|
||||
writeJSON(&b, i.Author)
|
||||
b.WriteString(`,"reviewers":`)
|
||||
writeJSON(&b, i.Reviewers)
|
||||
} else {
|
||||
b.WriteString(`,"assignees":`)
|
||||
writeJSON(&b, i.Assignees)
|
||||
}
|
||||
b.WriteString(`,"last_comment_by":`)
|
||||
writeJSON(&b, i.LastCommentBy)
|
||||
b.WriteString(`,"last_activity_at":`)
|
||||
writeJSON(&b, FormatMoment(i.LastActivityAt))
|
||||
b.WriteString(`,"stalled_hours":`)
|
||||
// Python round(x, 1) 的 json 輸出是 48.0/10.4(repr 帶 .0);
|
||||
// %g 會輸出 48,極大值還會變 1e+06,改定點一位小數。
|
||||
b.WriteString(strconv.FormatFloat(i.StalledHours, 'f', 1, 64))
|
||||
b.WriteString(`,"reason":`)
|
||||
writeJSON(&b, i.Reason)
|
||||
if len(i.ChildActivity) > 0 {
|
||||
b.WriteString(`,"child_activity":`)
|
||||
writeJSON(&b, i.ChildActivity)
|
||||
}
|
||||
b.WriteString(`}`)
|
||||
return []byte(b.String()), nil
|
||||
}
|
||||
|
||||
// FormatMoment 輸出與 Python datetime.isoformat() 一致的時刻字串
|
||||
// (UTC 以 +00:00 表示,不用 Z;秒以下省略)。
|
||||
func FormatMoment(t time.Time) string {
|
||||
if t.Nanosecond() != 0 {
|
||||
return t.Format("2006-01-02T15:04:05.999999999-07:00")
|
||||
}
|
||||
return t.Format("2006-01-02T15:04:05-07:00")
|
||||
}
|
||||
|
||||
// writeJSON 以停用 HTML 轉義的編碼器輸出:Python json.dumps(ensure_ascii=False)
|
||||
// 不會把 <、>、& 轉成 \u003c 等逸出,json.Marshal 預設會,造成位元組不相容。
|
||||
// Encoder 會在結尾補換行, trim 掉。
|
||||
func writeJSON(b *strings.Builder, v any) {
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
if err := enc.Encode(v); err != nil {
|
||||
return
|
||||
}
|
||||
b.Write(bytes.TrimSuffix(buf.Bytes(), []byte{'\n'}))
|
||||
}
|
||||
|
||||
// Child 是父追蹤項的子項活動摘要。
|
||||
type Child struct {
|
||||
Repo string `json:"repo"`
|
||||
Number int `json:"number"`
|
||||
Title string `json:"title"`
|
||||
State string `json:"state"`
|
||||
// LastActivityAt 用指標:子項無可解析時刻時 Python 輸出 null(不是 "")。
|
||||
LastActivityAt *string `json:"last_activity_at"`
|
||||
}
|
||||
|
||||
// XrefTarget 是解析後的引用目標(owner、repo、number)。
|
||||
type XrefTarget struct {
|
||||
Owner string
|
||||
Repo string
|
||||
Number int
|
||||
}
|
||||
|
||||
// Source 是 stalled 掃描需要的資料源(CLI 層以 API 實作;測試注入假資料)。
|
||||
type Source interface {
|
||||
// MyOrganizations 回傳目前帳號所屬組織清單。
|
||||
MyOrganizations() ([]string, error)
|
||||
// OrganizationRepositories 回傳組織的倉庫清單。
|
||||
OrganizationRepositories(org string) ([]Repository, error)
|
||||
// OpenIssues 回傳倉庫的 open issues(Gitea 會混入 PR,由掃描端過濾)。
|
||||
OpenIssues(owner, repo string) ([]Issue, error)
|
||||
// OpenPulls 回傳倉庫的 open pull requests。
|
||||
OpenPulls(owner, repo string) ([]PullRequest, error)
|
||||
// IssueComments 回傳 issue/PR 的留言。
|
||||
IssueComments(owner, repo string, number int) ([]Comment, error)
|
||||
// TryGetIssue 寬容版單一 issue 查詢:失敗(含 404)回 (零值, false, nil)。
|
||||
TryGetIssue(owner, repo string, number int) (Issue, bool, error)
|
||||
}
|
||||
|
||||
// iterXrefs 產出文字中的 (prefix, number) 配對(對應 _iter_issue_xrefs)。
|
||||
//
|
||||
// Python 原版以 lookbehind (?<![\w/#]) 在匹配起點檢查前一「字元」,
|
||||
// 且 \w 採 Unicode(中日韓、全形數字都算)。Go regexp 不支援 lookbehind,
|
||||
// 改為掃描時檢查起點前一 rune:是文數字(Unicode)/底線/斜線/# 者略過,
|
||||
// 並從起點的下一個 rune 重試——與 Python finditer 的逐位置語義一致,
|
||||
// 否則「修復bear-cli#9」這種寫法會整段被丟棄(Python 只匹配後半 cli#9)。
|
||||
func iterXrefs(text string) [][2]string {
|
||||
var out [][2]string
|
||||
pos := 0
|
||||
for pos <= len(text) {
|
||||
m := xrefPattern.FindStringIndex(text[pos:])
|
||||
if m == nil {
|
||||
break
|
||||
}
|
||||
start, end := pos+m[0], pos+m[1]
|
||||
if start > 0 {
|
||||
prev, _ := utf8.DecodeLastRuneInString(text[:start])
|
||||
if isWordChar(prev) || prev == '/' || prev == '#' {
|
||||
_, size := utf8.DecodeRuneInString(text[start:])
|
||||
pos = start + size
|
||||
continue
|
||||
}
|
||||
}
|
||||
match := text[start:end]
|
||||
i := strings.IndexByte(match, '#')
|
||||
prefix := match[:i]
|
||||
number := match[i+1:]
|
||||
out = append(out, [2]string{prefix, number})
|
||||
pos = end
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// isWordChar 對應 Python \w(Unicode):字母/數字/底線。
|
||||
// 前一版只認 ASCII,中文緊鄰 #N 時(「修復#12」)與 Python 行為分歧。
|
||||
func isWordChar(r rune) bool {
|
||||
return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
|
||||
}
|
||||
|
||||
// ResolveXrefTargets 把內文/留言中的引用解析成目標清單(對應 _resolve_xref_targets)。
|
||||
//
|
||||
// 單段 #N 指向父項所在倉庫;單段 repo#N 需 repo 存在於父項所屬組織
|
||||
// (「PR#50」這類寫法因 repo 不存在而自動略過);owner/repo#N 需 owner
|
||||
// 為目前帳號所屬組織(跨倉庫子項,如 bear-cli#9 → bear#35 的同組織判定)。
|
||||
// 去重、保留出現順序。
|
||||
func ResolveXrefTargets(org, repo string, texts []string, myOrgs map[string]bool, orgRepos func(org string) ([]string, error)) ([]XrefTarget, error) {
|
||||
var resolved []XrefTarget
|
||||
seen := map[XrefTarget]bool{}
|
||||
var orgRepoSet map[string]bool
|
||||
for _, text := range texts {
|
||||
for _, pair := range iterXrefs(text) {
|
||||
prefix, numberStr := pair[0], pair[1]
|
||||
var number int
|
||||
if _, err := fmt.Sscanf(numberStr, "%d", &number); err != nil || number <= 0 {
|
||||
continue
|
||||
}
|
||||
var target XrefTarget
|
||||
switch {
|
||||
case strings.Contains(prefix, "/"):
|
||||
parts := strings.SplitN(prefix, "/", 2)
|
||||
owner, name := parts[0], parts[1]
|
||||
if owner != "" && name != "" && myOrgs[owner] {
|
||||
target = XrefTarget{owner, name, number}
|
||||
}
|
||||
case prefix != "":
|
||||
if orgRepoSet == nil {
|
||||
names, err := orgRepos(org)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
orgRepoSet = map[string]bool{}
|
||||
for _, n := range names {
|
||||
orgRepoSet[n] = true
|
||||
}
|
||||
}
|
||||
if orgRepoSet[prefix] {
|
||||
target = XrefTarget{org, prefix, number}
|
||||
}
|
||||
default:
|
||||
target = XrefTarget{org, repo, number}
|
||||
}
|
||||
if target != (XrefTarget{}) && !seen[target] {
|
||||
seen[target] = true
|
||||
resolved = append(resolved, target)
|
||||
}
|
||||
}
|
||||
}
|
||||
return resolved, nil
|
||||
}
|
||||
|
||||
// childActivity 計算父追蹤項的子項活動(對應 _child_activity)。
|
||||
//
|
||||
// 只採計向下引用:子項建立時間需晚於父項(父項內文回指更早的規劃 issue
|
||||
// 是上行引用,不採計)。資料源失敗(含編號不存在)靜默略過,不影響掃描。
|
||||
func childActivity(src Source, org, repo string, parent Issue, comments []Comment, myOrgs map[string]bool, orgRepos func(string) ([]string, error)) (moments []time.Time, children []Child) {
|
||||
texts := []string{parent.Body}
|
||||
for _, c := range comments {
|
||||
texts = append(texts, c.Body)
|
||||
}
|
||||
targets, err := ResolveXrefTargets(org, repo, texts, myOrgs, orgRepos)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
for _, t := range targets {
|
||||
child, ok, gerr := src.TryGetIssue(t.Owner, t.Repo, t.Number)
|
||||
if gerr != nil || !ok {
|
||||
continue
|
||||
}
|
||||
if t.Owner == org && t.Repo == repo && child.Number == parent.Number {
|
||||
continue // 自我引用
|
||||
}
|
||||
if !parent.CreatedAt.IsZero() && !child.CreatedAt.IsZero() && !child.CreatedAt.After(parent.CreatedAt) {
|
||||
continue // 上行引用(父項回指更早或同時的 issue);時間未知則不排除
|
||||
}
|
||||
var ms []time.Time
|
||||
if !child.UpdatedAt.IsZero() {
|
||||
ms = append(ms, child.UpdatedAt)
|
||||
}
|
||||
if child.ClosedAt != nil && !child.ClosedAt.IsZero() {
|
||||
ms = append(ms, *child.ClosedAt)
|
||||
}
|
||||
if cs, cerr := src.IssueComments(t.Owner, t.Repo, t.Number); cerr == nil {
|
||||
for _, c := range cs {
|
||||
if !c.CreatedAt.IsZero() {
|
||||
ms = append(ms, c.CreatedAt)
|
||||
}
|
||||
}
|
||||
}
|
||||
var last *string
|
||||
if len(ms) > 0 {
|
||||
latest := maxTime(ms)
|
||||
moments = append(moments, latest)
|
||||
// 與 Item 相同用 FormatMoment(Python isoformat:UTC 記 +00:00);
|
||||
// RFC3339 對 UTC 會輸出 Z,與基準不相容。
|
||||
s := FormatMoment(latest)
|
||||
last = &s
|
||||
}
|
||||
children = append(children, Child{
|
||||
Repo: t.Owner + "/" + t.Repo,
|
||||
Number: child.Number,
|
||||
Title: child.Title,
|
||||
State: child.State,
|
||||
LastActivityAt: last,
|
||||
})
|
||||
}
|
||||
return moments, children
|
||||
}
|
||||
|
||||
func maxTime(ts []time.Time) time.Time {
|
||||
best := ts[0]
|
||||
for _, t := range ts[1:] {
|
||||
if t.After(best) {
|
||||
best = t
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
func usernames(users []User) []string {
|
||||
var out []string
|
||||
seen := map[string]bool{}
|
||||
for _, u := range users {
|
||||
if u.Username == "" || seen[u.Username] {
|
||||
continue
|
||||
}
|
||||
seen[u.Username] = true
|
||||
out = append(out, u.Username)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// ScanStalled 掃描跨組織的停滯 open issues/PR(對應 find_stalled_work)。
|
||||
//
|
||||
// 判定:最後活動(留言時間與本身 updated_at 取較晚者,父追蹤項再加計
|
||||
// 子項活動)距今超過 threshold 小時。刻意包含拾取死角形態:最後一則留言
|
||||
// 出自 assignee/PR 作者本人且超過時限——工作休眠、無人催促。最後留言
|
||||
// 出自目前帳號(username)的項目在冷卻期間不列入(已催促過);冷卻後
|
||||
// 仍停滯會再出現。輸出依停滯時間由長到短排序。
|
||||
func ScanStalled(src Source, username string, threshold float64, now time.Time) ([]Item, error) {
|
||||
orgs, err := src.MyOrganizations()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
myOrgs := make(map[string]bool, len(orgs))
|
||||
for _, o := range orgs {
|
||||
myOrgs[o] = true
|
||||
}
|
||||
orgRepos := func(org string) ([]string, error) {
|
||||
repos, err := src.OrganizationRepositories(org)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names := make([]string, 0, len(repos))
|
||||
for _, r := range repos {
|
||||
if r.Name != "" {
|
||||
names = append(names, r.Name)
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
var items []Item
|
||||
for _, org := range orgs {
|
||||
repos, err := src.OrganizationRepositories(org)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, r := range repos {
|
||||
if r.Name == "" || r.Empty {
|
||||
continue
|
||||
}
|
||||
// 停用 PR 的倉庫沒有 PR 可掃;issues 照常(gitea.py _iter_open_issues 不檢查此欄位)。
|
||||
scanPulls := r.HasPullRequests == nil || *r.HasPullRequests
|
||||
issues, err := src.OpenIssues(org, r.Name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, issue := range issues {
|
||||
if issue.PullRequest != nil {
|
||||
continue
|
||||
}
|
||||
comments, err := src.IssueComments(org, r.Name, issue.Number)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
item, ok := considerIssue(src, org, r.Name, issue, comments, username, threshold, now, myOrgs, orgRepos)
|
||||
if ok {
|
||||
items = append(items, item)
|
||||
}
|
||||
}
|
||||
if !scanPulls {
|
||||
continue
|
||||
}
|
||||
pulls, err := src.OpenPulls(org, r.Name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, pr := range pulls {
|
||||
comments, err := src.IssueComments(org, r.Name, pr.Number)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if item, ok := considerPull(pr, comments, username, threshold, now); ok {
|
||||
items = append(items, item)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.SliceStable(items, func(i, j int) bool {
|
||||
return items[i].StalledHours > items[j].StalledHours
|
||||
})
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// considerIssue 對單一 issue 套用停滯判定(對應 _consider 的 issue 分支)。
|
||||
func considerIssue(src Source, org, repo string, issue Issue, comments []Comment, username string, threshold float64, now time.Time, myOrgs map[string]bool, orgRepos func(string) ([]string, error)) (Item, bool) {
|
||||
childMoments, children := childActivity(src, org, repo, issue, comments, myOrgs, orgRepos)
|
||||
assignees := usernames(issue.Assignees)
|
||||
moments := []time.Time{issue.UpdatedAt, issue.CreatedAt}
|
||||
for _, c := range comments {
|
||||
if !c.CreatedAt.IsZero() {
|
||||
moments = append(moments, c.CreatedAt)
|
||||
}
|
||||
}
|
||||
moments = append(moments, childMoments...)
|
||||
moments = nonZero(moments)
|
||||
if len(moments) == 0 {
|
||||
return Item{}, false
|
||||
}
|
||||
lastActivity := maxTime(moments)
|
||||
stalled := now.Sub(lastActivity).Hours()
|
||||
if stalled < threshold {
|
||||
return Item{}, false
|
||||
}
|
||||
lastCommentAt, lastCommentBy := lastComment(comments)
|
||||
if lastCommentBy == username && !lastCommentAt.IsZero() &&
|
||||
now.Sub(lastCommentAt).Hours() < NudgeCooldownHours {
|
||||
return Item{}, false
|
||||
}
|
||||
reason := "waiting-outside"
|
||||
switch {
|
||||
case len(assignees) == 0:
|
||||
reason = "no-assignee"
|
||||
case lastCommentBy != "" && containsStr(assignees, lastCommentBy):
|
||||
reason = "assignee-idle"
|
||||
case lastCommentBy == "":
|
||||
reason = "no-commenter"
|
||||
}
|
||||
if len(children) > 0 && anyOpen(children) {
|
||||
reason = "parent-tracking"
|
||||
}
|
||||
item := Item{
|
||||
Type: "issue", Repo: issue.Repository.FullName, Number: issue.Number,
|
||||
Title: issue.Title, URL: issue.URL,
|
||||
Assignees: assignees,
|
||||
LastCommentBy: lastCommentBy, LastActivityAt: lastActivity,
|
||||
StalledHours: round1(stalled), Reason: reason,
|
||||
}
|
||||
if len(children) > 0 {
|
||||
item.ChildActivity = children
|
||||
}
|
||||
return item, true
|
||||
}
|
||||
|
||||
// considerPull 對單一 PR 套用停滯判定(對應 _consider 的 pull 分支)。
|
||||
func considerPull(pr PullRequest, comments []Comment, username string, threshold float64, now time.Time) (Item, bool) {
|
||||
reviewers := usernames(pr.RequestedReviewers)
|
||||
author := pr.Author.Username
|
||||
moments := []time.Time{pr.UpdatedAt, pr.CreatedAt}
|
||||
for _, c := range comments {
|
||||
if !c.CreatedAt.IsZero() {
|
||||
moments = append(moments, c.CreatedAt)
|
||||
}
|
||||
}
|
||||
moments = nonZero(moments)
|
||||
if len(moments) == 0 {
|
||||
return Item{}, false
|
||||
}
|
||||
lastActivity := maxTime(moments)
|
||||
stalled := now.Sub(lastActivity).Hours()
|
||||
if stalled < threshold {
|
||||
return Item{}, false
|
||||
}
|
||||
lastCommentAt, lastCommentBy := lastComment(comments)
|
||||
if lastCommentBy == username && !lastCommentAt.IsZero() &&
|
||||
now.Sub(lastCommentAt).Hours() < NudgeCooldownHours {
|
||||
return Item{}, false
|
||||
}
|
||||
reason := "no-commenter"
|
||||
switch {
|
||||
case len(reviewers) == 0:
|
||||
reason = "no-reviewer"
|
||||
case lastCommentBy == author:
|
||||
reason = "author-idle"
|
||||
case lastCommentBy != "" && containsStr(reviewers, lastCommentBy):
|
||||
reason = "reviewer-idle"
|
||||
}
|
||||
item := Item{
|
||||
Type: "pull", Repo: pr.FullName(), Number: pr.Number,
|
||||
Title: pr.Title, URL: pr.URL,
|
||||
Author: author, Reviewers: reviewers,
|
||||
LastCommentBy: lastCommentBy, LastActivityAt: lastActivity,
|
||||
StalledHours: round1(stalled), Reason: reason,
|
||||
}
|
||||
return item, true
|
||||
}
|
||||
|
||||
// lastComment 回傳最後一則留言(created_at 最新者)的時間與作者。
|
||||
func lastComment(comments []Comment) (time.Time, string) {
|
||||
var best time.Time
|
||||
by := ""
|
||||
for _, c := range comments {
|
||||
if c.CreatedAt.After(best) {
|
||||
best = c.CreatedAt
|
||||
by = c.Author()
|
||||
}
|
||||
}
|
||||
return best, by
|
||||
}
|
||||
|
||||
func anyOpen(children []Child) bool {
|
||||
for _, c := range children {
|
||||
if c.State == "open" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func containsStr(list []string, s string) bool {
|
||||
for _, x := range list {
|
||||
if x == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func nonZero(ts []time.Time) []time.Time {
|
||||
out := make([]time.Time, 0, len(ts))
|
||||
for _, t := range ts {
|
||||
if !t.IsZero() {
|
||||
out = append(out, t)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// round1 舍入到小數一位(對應 Python round(x, 1))。
|
||||
// 經 strconv 的十進位正確舍入(半偶數),與 Python 的浮點 round 行為一致,
|
||||
// 避免 (x*10+0.5) 截斷在 .x5 邊界產生偏差。
|
||||
func round1(v float64) float64 {
|
||||
r, err := strconv.ParseFloat(strconv.FormatFloat(v, 'f', 1, 64), 64)
|
||||
if err != nil {
|
||||
return v
|
||||
}
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,532 @@
|
||||
// workflow 套件的單元測試(teai issue #7 驗收:xref 邊界案例與 stalled 判定)。
|
||||
//
|
||||
// fakeSource 以假資料實作 Source 介面,邏輯離線可測;
|
||||
// 語義對照組是 alterminal/agents scripts/lib/gitea.py。
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func at(minutes int) time.Time {
|
||||
return time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC).Add(time.Duration(minutes) * time.Minute)
|
||||
}
|
||||
|
||||
// fakeSource 是注入假資料的 Source。
|
||||
type fakeSource struct {
|
||||
orgs []string
|
||||
repos map[string][]Repository
|
||||
// issues[owner/repo][number]
|
||||
issues map[string]map[int]Issue
|
||||
// pulls[owner/repo]
|
||||
pulls map[string][]PullRequest
|
||||
// comments[owner/repo/number]
|
||||
comments map[string][]Comment
|
||||
}
|
||||
|
||||
func (f *fakeSource) MyOrganizations() ([]string, error) { return f.orgs, nil }
|
||||
|
||||
func (f *fakeSource) OrganizationRepositories(org string) ([]Repository, error) {
|
||||
return f.repos[org], nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) OpenIssues(owner, repo string) ([]Issue, error) {
|
||||
var out []Issue
|
||||
for _, i := range f.issues[owner+"/"+repo] {
|
||||
out = append(out, i)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) OpenPulls(owner, repo string) ([]PullRequest, error) {
|
||||
return f.pulls[owner+"/"+repo], nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) IssueComments(owner, repo string, number int) ([]Comment, error) {
|
||||
return f.comments[fmt.Sprintf("%s/%s/%d", owner, repo, number)], nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) TryGetIssue(owner, repo string, number int) (Issue, bool, error) {
|
||||
i, ok := f.issues[owner+"/"+repo][number]
|
||||
if !ok {
|
||||
return Issue{}, false, nil
|
||||
}
|
||||
return i, true, nil
|
||||
}
|
||||
|
||||
func repoWith(name string, hasPR bool) []Repository {
|
||||
h := hasPR
|
||||
return []Repository{{Name: name, HasPullRequests: &h}}
|
||||
}
|
||||
|
||||
func mustResolve(t *testing.T, org, repo string, texts []string, myOrgs map[string]bool, orgRepos func(string) ([]string, error)) []XrefTarget {
|
||||
t.Helper()
|
||||
targets, err := ResolveXrefTargets(org, repo, texts, myOrgs, orgRepos)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveXrefTargets: %v", err)
|
||||
}
|
||||
return targets
|
||||
}
|
||||
|
||||
// TestIterXrefsEdges 驗證 regex 邊界:lookbehind 等價實作與兩段式斜線限制。
|
||||
func TestIterXrefsEdges(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
text string
|
||||
want [][2]string
|
||||
}{
|
||||
{"單段 #N", "父項:#3。", [][2]string{{"3"}, {"", "3"}}[1:]},
|
||||
{"單段 repo#N 存在", "見 agents#10", [][2]string{{"agents", "10"}}},
|
||||
{"PR#50 寫法不是 repo", "PR#50 與 issue#49", [][2]string{{"PR", "50"}, {"issue", "49"}}},
|
||||
{"owner/repo#N", "alterminal/agents#32", [][2]string{{"alterminal/agents", "32"}}},
|
||||
{"斜線後不切半段", "alterminal/bear#47 只應匹配整段", [][2]string{{"alterminal/bear", "47"}}},
|
||||
{"連字號 repo 名", "bear-cli#9", [][2]string{{"bear-cli", "9"}}},
|
||||
{"路徑後的 #N 不匹配", "see https://x/a/#frag not #5", [][2]string{{"", "5"}}},
|
||||
// Python \w 是 Unicode:CJK 緊鄰 #N 時整體視為 \w,lookbehind 擋下。
|
||||
{"CJK 緊鄰 #N 略過", "修復#12的問題,見 #5", [][2]string{{"", "5"}}},
|
||||
{"CJK 緊鄰 repo#N 整段略過", "修復agents#12", nil},
|
||||
{"CJK 緊鄰連字號 repo 匹配後半", "修復bear-cli#9 見 #5", [][2]string{{"cli", "9"}, {"", "5"}}},
|
||||
{"連續井號", "##5", nil},
|
||||
{"全形數字後 #N", "12#5", nil},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := iterXrefs(tc.text)
|
||||
if len(got) != len(tc.want) {
|
||||
t.Fatalf("iterXrefs(%q) = %v, want %v", tc.text, got, tc.want)
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tc.want[i] {
|
||||
t.Fatalf("iterXrefs(%q)[%d] = %v, want %v", tc.text, i, got[i], tc.want[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveXrefTargets 驗證三種形態的解析與單段 repo 的存在性邊界(#7 驗收)。
|
||||
func TestResolveXrefTargets(t *testing.T) {
|
||||
myOrgs := map[string]bool{"alterminal": true}
|
||||
orgRepos := func(string) ([]string, error) { return []string{"agents", "teai", "bear-cli"}, nil }
|
||||
texts := []string{"父項:#3,子項 teai#7,跨倉 alterminal/bear#35,不存在 nope#9,PR#50"}
|
||||
|
||||
got := mustResolve(t, "alterminal", "agents", texts, myOrgs, orgRepos)
|
||||
want := []XrefTarget{
|
||||
{Owner: "alterminal", Repo: "agents", Number: 3},
|
||||
{Owner: "alterminal", Repo: "teai", Number: 7},
|
||||
{Owner: "alterminal", Repo: "bear", Number: 35},
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("got %v, want %v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("got[%d] %v, want %v", i, got[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveXrefTargetsOwnerNotMyOrg owner/repo#N 的 owner 非所屬組織 → 不解析。
|
||||
func TestResolveXrefTargetsOwnerNotMyOrg(t *testing.T) {
|
||||
myOrgs := map[string]bool{"alterminal": true}
|
||||
orgRepos := func(string) ([]string, error) { return nil, nil }
|
||||
got := mustResolve(t, "alterminal", "agents", []string{"other/repo#1"}, myOrgs, orgRepos)
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("owner 非所屬組織應略過,got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveXrefTargetsDedup 同一目標重複出現只保留第一個。
|
||||
func TestResolveXrefTargetsDedup(t *testing.T) {
|
||||
myOrgs := map[string]bool{"alterminal": true}
|
||||
orgRepos := func(string) ([]string, error) { return []string{"teai"}, nil }
|
||||
got := mustResolve(t, "alterminal", "agents", []string{"#7 又 teai#7"}, myOrgs, orgRepos)
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("應兩筆(#7 同倉庫、teai#7 跨倉庫),got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanStalledIssueReasons 驗證 issue 的 reason 分類與排序。
|
||||
func TestScanStalledIssueReasons(t *testing.T) {
|
||||
now := at(0)
|
||||
src := &fakeSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]Repository{
|
||||
"alterminal": repoWith("agents", true),
|
||||
},
|
||||
issues: map[string]map[int]Issue{
|
||||
"alterminal/agents": {
|
||||
1: {Number: 1, Title: "無分派者", State: "open", CreatedAt: at(-600), UpdatedAt: at(-600), Repository: Reference{"alterminal/agents"}, URL: "u1"},
|
||||
2: {Number: 2, Title: "分派者自己最後留言", State: "open", Author: User{"ceo"}, CreatedAt: at(-600), UpdatedAt: at(-300), Assignees: []User{{"ceo"}}, Repository: Reference{"alterminal/agents"}, URL: "u2"},
|
||||
3: {Number: 3, Title: "無留言", State: "open", CreatedAt: at(-600), UpdatedAt: at(-300), Assignees: []User{{"ceo"}}, Repository: Reference{"alterminal/agents"}, URL: "u3"},
|
||||
4: {Number: 4, Title: "等外部回應", State: "open", CreatedAt: at(-600), UpdatedAt: at(-300), Assignees: []User{{"ceo"}}, Repository: Reference{"alterminal/agents"}, URL: "u4"},
|
||||
5: {Number: 5, Title: "太新不在門檻內", State: "open", CreatedAt: at(-30), UpdatedAt: at(-30), Assignees: []User{{"ceo"}}, Repository: Reference{"alterminal/agents"}, URL: "u5"},
|
||||
},
|
||||
},
|
||||
comments: map[string][]Comment{
|
||||
"alterminal/agents/2": {{User: User{"ceo"}, CreatedAt: at(-300)}},
|
||||
"alterminal/agents/4": {{User: User{"dan"}, CreatedAt: at(-300)}},
|
||||
},
|
||||
}
|
||||
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanStalled: %v", err)
|
||||
}
|
||||
// 1: no-assignee(10h)、2: assignee-idle(5h)、3: no-commenter(5h)、4: waiting-outside(5h)、5: 不列入
|
||||
if len(got) != 4 {
|
||||
t.Fatalf("應 4 筆,got %d:%v", len(got), got)
|
||||
}
|
||||
byNumber := map[int]Item{}
|
||||
for _, it := range got {
|
||||
byNumber[it.Number] = it
|
||||
}
|
||||
for n, wantReason := range map[int]string{1: "no-assignee", 2: "assignee-idle", 3: "no-commenter", 4: "waiting-outside"} {
|
||||
if byNumber[n].Reason != wantReason {
|
||||
t.Errorf("issue %d reason = %q, want %q", n, byNumber[n].Reason, wantReason)
|
||||
}
|
||||
}
|
||||
if got[0].Number != 1 || got[0].StalledHours != 10 {
|
||||
t.Errorf("排序應由長到短,首筆 issue 1(10h),got %v", got[0])
|
||||
}
|
||||
if byNumber[2].LastCommentBy != "ceo" {
|
||||
t.Errorf("issue 2 last_comment_by 應為 ceo,got %q", byNumber[2].LastCommentBy)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanStalledNudgeCooldown 最後留言出自掃描者本人 → 24 小時內冷卻不列入。
|
||||
func TestScanStalledNudgeCooldown(t *testing.T) {
|
||||
now := at(0)
|
||||
src := &fakeSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]Repository{"alterminal": repoWith("agents", true)},
|
||||
issues: map[string]map[int]Issue{
|
||||
"alterminal/agents": {
|
||||
1: {Number: 1, State: "open", CreatedAt: at(-600), UpdatedAt: at(-600), Assignees: []User{{"max"}}, Repository: Reference{"alterminal/agents"}},
|
||||
},
|
||||
},
|
||||
comments: map[string][]Comment{
|
||||
// admin(掃描者)10 小時前催促過 → 冷卻中,不列入。
|
||||
"alterminal/agents/1": {{User: User{"admin"}, CreatedAt: at(-600)}},
|
||||
},
|
||||
}
|
||||
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanStalled: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("催促冷卻中的項目不應列入,got %v", got)
|
||||
}
|
||||
// 冷卻過了(25 小時前催促)→ 重新列入。
|
||||
src.comments["alterminal/agents/1"] = []Comment{{User: User{"admin"}, CreatedAt: at(-1500)}}
|
||||
got, err = ScanStalled(src, "admin", 4.0, now)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanStalled: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Reason != "waiting-outside" {
|
||||
t.Fatalf("冷卻後應重新列入,got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanStalledParentTracking 父追蹤項:子項活動計入 last_activity、reason 標記。
|
||||
func TestScanStalledParentTracking(t *testing.T) {
|
||||
now := at(0)
|
||||
// 父項與子項都 5 小時沒動:父項 last_activity 計入子項活動後同為 5h,
|
||||
// 應以 parent-tracking 列入並附子項摘要;子項本身則是 assignee-idle。
|
||||
src := &fakeSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]Repository{"alterminal": repoWith("teai", true)},
|
||||
issues: map[string]map[int]Issue{
|
||||
"alterminal/teai": {
|
||||
3: {Number: 3, Title: "父", State: "open", Body: "子項:#7", CreatedAt: at(-700), UpdatedAt: at(-300), Assignees: []User{{"ceo"}}, Repository: Reference{"alterminal/teai"}},
|
||||
7: {Number: 7, Title: "子", State: "open", CreatedAt: at(-650), UpdatedAt: at(-300), Assignees: []User{{"max"}}, Repository: Reference{"alterminal/teai"}},
|
||||
},
|
||||
},
|
||||
comments: map[string][]Comment{
|
||||
"alterminal/teai/7": {{User: User{"max"}, CreatedAt: at(-300)}},
|
||||
},
|
||||
}
|
||||
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanStalled: %v", err)
|
||||
}
|
||||
var parent3, child7 *Item
|
||||
for i := range got {
|
||||
switch got[i].Number {
|
||||
case 3:
|
||||
parent3 = &got[i]
|
||||
case 7:
|
||||
child7 = &got[i]
|
||||
}
|
||||
}
|
||||
if child7 == nil {
|
||||
t.Fatalf("子項 7 應列入(5h 無活動),got %v", got)
|
||||
}
|
||||
if child7.Reason != "assignee-idle" {
|
||||
t.Errorf("子項 7 reason = %q, want assignee-idle", child7.Reason)
|
||||
}
|
||||
if parent3 == nil {
|
||||
t.Fatalf("父項 3 應列入,got %v", got)
|
||||
}
|
||||
if parent3.Reason != "parent-tracking" {
|
||||
t.Errorf("父項 3 reason = %q, want parent-tracking", parent3.Reason)
|
||||
}
|
||||
if len(parent3.ChildActivity) != 1 || parent3.ChildActivity[0].Number != 7 {
|
||||
t.Errorf("父項 3 應附子項摘要,got %v", parent3.ChildActivity)
|
||||
}
|
||||
if parent3.StalledHours != 5 {
|
||||
t.Errorf("父項 3 stalled_hours = %v, want 5", parent3.StalledHours)
|
||||
}
|
||||
|
||||
// 子項 1 小時前恢復活動 → 父項 last_activity 跟著更新,未達門檻不列入;
|
||||
// 子項本身也不停滯。整份輸出應為空。
|
||||
child := src.issues["alterminal/teai"][7]
|
||||
child.UpdatedAt = at(-60)
|
||||
src.issues["alterminal/teai"][7] = child
|
||||
src.comments["alterminal/teai/7"] = []Comment{{User: User{"max"}, CreatedAt: at(-60)}}
|
||||
got, err = ScanStalled(src, "admin", 4.0, now)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanStalled: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("子項推進中 → 父項不應誤報停滯,got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanStalledParentTrackingNotChild 上行引用:引用對象早於父項 → 非子項,不採計。
|
||||
func TestScanStalledParentTrackingNotChild(t *testing.T) {
|
||||
now := at(0)
|
||||
src := &fakeSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]Repository{"alterminal": repoWith("teai", true)},
|
||||
issues: map[string]map[int]Issue{
|
||||
"alterminal/teai": {
|
||||
47: {Number: 47, State: "open", Body: "規劃見 #39(更早)", CreatedAt: at(-700), UpdatedAt: at(-600), Assignees: []User{{"ceo"}}, Repository: Reference{"alterminal/teai"}},
|
||||
39: {Number: 39, State: "open", CreatedAt: at(-2000), UpdatedAt: at(-60), Repository: Reference{"alterminal/teai"}},
|
||||
},
|
||||
},
|
||||
}
|
||||
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanStalled: %v", err)
|
||||
}
|
||||
// #39 是上行引用,不採計 → 父項 47 停滯 10h(assignee-idle:ceo 分派、無留言)→ no-commenter。
|
||||
var n47 *Item
|
||||
for i := range got {
|
||||
if got[i].Number == 47 {
|
||||
n47 = &got[i]
|
||||
}
|
||||
}
|
||||
if n47 == nil {
|
||||
t.Fatalf("上行引用不採計 → 47 應停滯列入,got %v", got)
|
||||
}
|
||||
if n47.Reason != "no-commenter" {
|
||||
t.Errorf("47 reason = %q, want no-commenter", n47.Reason)
|
||||
}
|
||||
if len(n47.ChildActivity) != 0 {
|
||||
t.Errorf("上行引用不應產生子項摘要,got %v", n47.ChildActivity)
|
||||
}
|
||||
// #39 本身 updated 1 小時前 → 不列入。
|
||||
for _, it := range got {
|
||||
if it.Number == 39 {
|
||||
t.Errorf("39 未達門檻不應列入:%v", it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanStalledPullReasons 驗證 PR 的 reason 分類。
|
||||
func TestScanStalledPullReasons(t *testing.T) {
|
||||
now := at(0)
|
||||
h := true
|
||||
src := &fakeSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]Repository{"alterminal": {{Name: "teai", HasPullRequests: &h}}},
|
||||
pulls: map[string][]PullRequest{
|
||||
"alterminal/teai": {
|
||||
{Number: 10, State: "open", Author: User{"max"}, CreatedAt: at(-600), UpdatedAt: at(-600)},
|
||||
{Number: 11, State: "open", Author: User{"max"}, CreatedAt: at(-600), UpdatedAt: at(-300), RequestedReviewers: []User{{"ceo"}}},
|
||||
{Number: 12, State: "open", Author: User{"max"}, CreatedAt: at(-600), UpdatedAt: at(-300), RequestedReviewers: []User{{"ceo"}}},
|
||||
{Number: 13, State: "open", Author: User{"max"}, CreatedAt: at(-600), UpdatedAt: at(-300), RequestedReviewers: []User{{"ceo"}}},
|
||||
},
|
||||
},
|
||||
comments: map[string][]Comment{
|
||||
"alterminal/teai/11": {{User: User{"max"}, CreatedAt: at(-300)}}, // author-idle
|
||||
"alterminal/teai/12": {{User: User{"ceo"}, CreatedAt: at(-300)}}, // reviewer-idle
|
||||
"alterminal/teai/13": {{User: User{"dan"}, CreatedAt: at(-300)}}, // no-commenter(外部留言)
|
||||
},
|
||||
}
|
||||
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanStalled: %v", err)
|
||||
}
|
||||
byNumber := map[int]Item{}
|
||||
for _, it := range got {
|
||||
byNumber[it.Number] = it
|
||||
}
|
||||
for n, wantReason := range map[int]string{10: "no-reviewer", 11: "author-idle", 12: "reviewer-idle", 13: "no-commenter"} {
|
||||
item, ok := byNumber[n]
|
||||
if !ok {
|
||||
t.Fatalf("PR %d 應列入,got %v", n, got)
|
||||
}
|
||||
if item.Reason != wantReason {
|
||||
t.Errorf("PR %d reason = %q, want %q", n, item.Reason, wantReason)
|
||||
}
|
||||
}
|
||||
if len(got) != 4 {
|
||||
t.Fatalf("應 4 筆,got %d", len(got))
|
||||
}
|
||||
if byNumber[10].Author != "max" {
|
||||
t.Errorf("PR 10 author 應為 max,got %q", byNumber[10].Author)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanStalledNoPullsFlag 停用 PR 的倉庫仍掃 issues,只跳過 PR。
|
||||
func TestScanStalledNoPullsFlag(t *testing.T) {
|
||||
now := at(0)
|
||||
h := false
|
||||
src := &fakeSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]Repository{"alterminal": {{Name: "docs", HasPullRequests: &h}}},
|
||||
issues: map[string]map[int]Issue{
|
||||
"alterminal/docs": {
|
||||
1: {Number: 1, State: "open", CreatedAt: at(-600), UpdatedAt: at(-600), Repository: Reference{"alterminal/docs"}},
|
||||
},
|
||||
},
|
||||
pulls: map[string][]PullRequest{
|
||||
// 即使假資料有 PR,flag 關閉也不應掃。
|
||||
"alterminal/docs": {{Number: 2, State: "open", Author: User{"max"}, CreatedAt: at(-600), UpdatedAt: at(-600)}},
|
||||
},
|
||||
}
|
||||
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanStalled: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Number != 1 || got[0].Type != "issue" {
|
||||
t.Fatalf("應只有 issue 1,got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanStalledSkipsPRsInIssues 確認 /issues 混入的 PR 會被過濾。
|
||||
func TestScanStalledSkipsPRsInIssues(t *testing.T) {
|
||||
now := at(0)
|
||||
src := &fakeSource{
|
||||
orgs: []string{"alterminal"},
|
||||
repos: map[string][]Repository{"alterminal": repoWith("teai", true)},
|
||||
issues: map[string]map[int]Issue{
|
||||
"alterminal/teai": {
|
||||
1: {Number: 1, State: "open", CreatedAt: at(-600), UpdatedAt: at(-600), Repository: Reference{"alterminal/teai"}, PullRequest: struct{}{}},
|
||||
},
|
||||
},
|
||||
}
|
||||
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanStalled: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("/issues 混入的 PR 應過濾,got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestItemJSON 與 gitea.py 的 JSON 位元組相容(鍵序、HTML 不轉義、48.0、null)。
|
||||
func TestItemJSON(t *testing.T) {
|
||||
ts := at(-600)
|
||||
activity := FormatMoment(ts)
|
||||
item := Item{
|
||||
Type: "issue", Repo: "alterminal/teai", Number: 7, Title: "R,D <v2> & 規劃", URL: "u",
|
||||
Assignees: []string{"ceo"}, LastCommentBy: "max",
|
||||
LastActivityAt: ts, StalledHours: 48, Reason: "assignee-idle",
|
||||
ChildActivity: []Child{
|
||||
{Repo: "alterminal/teai", Number: 3, Title: "父", State: "open", LastActivityAt: &activity},
|
||||
{Repo: "alterminal/teai", Number: 4, Title: "無時刻", State: "open"},
|
||||
},
|
||||
}
|
||||
// json.Marshal 會把 <、>、& 重新轉義,必須用停用 HTML 轉義的編碼器。
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
if err := enc.Encode(item); err != nil {
|
||||
t.Fatalf("Encode: %v", err)
|
||||
}
|
||||
got := strings.TrimSuffix(buf.String(), "\n")
|
||||
want := `{"type":"issue","repo":"alterminal/teai","number":7,"title":"R,D <v2> & 規劃","url":"u","assignees":["ceo"],"last_comment_by":"max","last_activity_at":"2026-09-09T22:00:00+00:00","stalled_hours":48.0,"reason":"assignee-idle","child_activity":[{"repo":"alterminal/teai","number":3,"title":"父","state":"open","last_activity_at":"2026-09-09T22:00:00+00:00"},{"repo":"alterminal/teai","number":4,"title":"無時刻","state":"open","last_activity_at":null}]}`
|
||||
if got != want {
|
||||
t.Fatalf("JSON 位元組不相容:\n got %s\nwant %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPullJSON:pull 的鍵序(author、reviewers)與非整數 stalled_hours。
|
||||
func TestPullJSON(t *testing.T) {
|
||||
item := Item{
|
||||
Type: "pull", Repo: "alterminal/teai", Number: 12, Title: "t", URL: "u",
|
||||
Author: "ceo", Reviewers: []string{"queena"},
|
||||
LastActivityAt: at(-600), StalledHours: 10.44, Reason: "reviewer-idle",
|
||||
}
|
||||
b, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal: %v", err)
|
||||
}
|
||||
got := string(b)
|
||||
want := `{"type":"pull","repo":"alterminal/teai","number":12,"title":"t","url":"u","author":"ceo","reviewers":["queena"],"last_comment_by":"","last_activity_at":"2026-09-09T22:00:00+00:00","stalled_hours":10.4,"reason":"reviewer-idle"}`
|
||||
if got != want {
|
||||
t.Fatalf("JSON 位元組不相容:\n got %s\nwant %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanStalledEmpty 無停滯項目 → 空輸出(CLI 層輸出 [])。
|
||||
func TestScanStalledEmpty(t *testing.T) {
|
||||
now := at(0)
|
||||
src := &fakeSource{orgs: []string{"alterminal"}, repos: map[string][]Repository{"alterminal": repoWith("teai", true)}}
|
||||
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||
if err != nil {
|
||||
t.Fatalf("ScanStalled: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("應空,got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestScanStalledOrgError 組織層錯誤應回傳(不靜默)。
|
||||
func TestScanStalledOrgError(t *testing.T) {
|
||||
src := &errSource{}
|
||||
if _, err := ScanStalled(src, "admin", 4.0, at(0)); err == nil {
|
||||
t.Fatal("組織清單失敗應回傳錯誤")
|
||||
}
|
||||
}
|
||||
|
||||
type errSource struct{}
|
||||
|
||||
func (errSource) MyOrganizations() ([]string, error) { return nil, errors.New("boom") }
|
||||
func (e errSource) OrganizationRepositories(string) ([]Repository, error) {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
func (e errSource) OpenIssues(string, string) ([]Issue, error) { return nil, errors.New("boom") }
|
||||
func (e errSource) OpenPulls(string, string) ([]PullRequest, error) { return nil, errors.New("boom") }
|
||||
func (e errSource) IssueComments(string, string, int) ([]Comment, error) {
|
||||
return nil, errors.New("boom")
|
||||
}
|
||||
func (e errSource) TryGetIssue(string, string, int) (Issue, bool, error) {
|
||||
return Issue{}, false, errors.New("boom")
|
||||
}
|
||||
|
||||
// TestRound1 round1 十進位舍入到一位小數(與 Python round(x,1) 半偶數一致)。
|
||||
func TestRound1(t *testing.T) {
|
||||
cases := []struct {
|
||||
in float64
|
||||
want float64
|
||||
}{
|
||||
{10.44, 10.4}, {10.46, 10.5}, {10.0, 10.0},
|
||||
// 半偶數(與 Python round(x,1) 對二進位真值的行為一致):
|
||||
// 10.45、5.25、5.15 的二進位真值都略低於表值 → 舍到偶數位。
|
||||
{10.45, 10.4}, {0.05, 0.1}, {5.25, 5.2}, {5.15, 5.2},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := round1(tc.in); got != tc.want {
|
||||
t.Errorf("round1(%v) = %v, want %v", tc.in, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user