Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d9092cdde | ||
|
|
540718dda7 | ||
|
|
8735e35db6 | ||
|
|
d89caf4af2 | ||
|
|
8e358185f4 | ||
|
|
8d446ed62b | ||
|
|
d45a8243c8 | ||
|
|
d0334434c5 | ||
|
|
5506daa5f5 | ||
|
|
9a4887a677 | ||
|
|
02fad53aa4 | ||
|
|
5a48fdd590 | ||
|
|
d01108bda3 | ||
|
|
3470a96392 | ||
|
|
36a50b95ed | ||
|
|
9e699f3b4e | ||
|
|
d689107eea | ||
|
|
027ed1ade9 | ||
|
|
e4212b9c90 | ||
|
|
a2baf55fce |
@@ -19,3 +19,4 @@ coverage.*
|
|||||||
# 作業系統
|
# 作業系統
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
teai-bin
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ teai 是 Gitea 的命令列(CLI)工具,以更完整、更可靠的方式
|
|||||||
|
|
||||||
- **語言:** Go(與 Gitea 本體一致),僅用標準庫,離線可建置
|
- **語言:** Go(與 Gitea 本體一致),僅用標準庫,離線可建置
|
||||||
- **目標站點:** `https://gitea.alterminal.com`
|
- **目標站點:** `https://gitea.alterminal.com`
|
||||||
- **狀態:** 基礎建設(#5:internal/gitea)、工作流命令(#6:whoami/orgs/members/mine/pulls/next)、日常操作命令(#8:issues/pulls/labels/milestones/releases/repos/api)與管理者巡邏命令(#7:stalled/xrefs)已實作
|
- **狀態:** 基礎建設(#5:internal/gitea)、工作流命令(#6:whoami/role/orgs/members/mine/pulls/next)、日常操作命令(#8:issues/pulls/labels/milestones/releases/repos/api)與管理者巡邏命令(#7:stalled/xrefs)已實作
|
||||||
- **範圍(#3):** 不避開 tea 已有的功能;單一工具涵蓋完整操作
|
- **範圍(#3):** 不避開 tea 已有的功能;單一工具涵蓋完整操作
|
||||||
|
|
||||||
## 安裝與建置
|
## 安裝與建置
|
||||||
@@ -17,30 +17,48 @@ teai 是 Gitea 的命令列(CLI)工具,以更完整、更可靠的方式
|
|||||||
- **git**
|
- **git**
|
||||||
- Gitea 帳號的 **API token**(設定階段使用;在 Gitea「設定 → 應用程式」產生)
|
- Gitea 帳號的 **API token**(設定階段使用;在 Gitea「設定 → 應用程式」產生)
|
||||||
|
|
||||||
### 從原始碼建置
|
### 以 go install 安裝(建議)
|
||||||
|
|
||||||
|
自 v0.1.0 起 module 已發佈 tag,可直接以版本安裝(二元檔裝進 `GOBIN`,預設 `~/go/bin`):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
go install gitea.alterminal.com/alterminal/teai/cmd/teai@latest # 最新 tag(亦可 @v<版本> 指定)
|
||||||
|
teai version # 驗證:顯示安裝的 tag 版本(見下方說明)
|
||||||
|
```
|
||||||
|
|
||||||
|
本 module 為公開倉庫,預設 `GOPROXY`/`GOSUMDB` 即可解析(已於乾淨環境驗證)。
|
||||||
|
若所在網路環境無法經公用 proxy 抓取,可改設 `GOPRIVATE=gitea.alterminal.com`
|
||||||
|
(略過 proxy 與 checksum database,直接從 Gitea 抓取)。
|
||||||
|
|
||||||
|
`teai version` 顯示建入的 module 版本,即安裝指定的 tag(如 `v0.1.1`)。
|
||||||
|
注意:讀 build info 顯示安裝版本的支援,自包含該變更的 tag 起(v0.1.1)才生效——
|
||||||
|
v0.1.0 早於此變更,以 `@v0.1.0` 安裝(或此變更前的 `@latest`)仍顯示舊行為 `0.1.0-dev`。
|
||||||
|
|
||||||
|
### 從原始碼建置(開發用)
|
||||||
|
|
||||||
|
開發、離線或想鎖定特定 commit 時,clone 後自行建置:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
git clone https://gitea.alterminal.com/alterminal/teai.git
|
git clone https://gitea.alterminal.com/alterminal/teai.git
|
||||||
cd teai
|
cd teai
|
||||||
go build -o teai ./cmd/teai
|
go build -o teai ./cmd/teai
|
||||||
install -Dm755 teai ~/.local/bin/teai # 或複製到任何 PATH 內目錄
|
install -Dm755 teai ~/.local/bin/teai # 或複製到任何 PATH 內目錄
|
||||||
teai version # 驗證:teai version 0.1.0-dev
|
teai version # 驗證:teai version v0.1.1-0.<時間戳>-<commit>(見下方說明)
|
||||||
```
|
```
|
||||||
|
|
||||||
也可以直接裝進 `GOBIN`(預設 `~/go/bin`;該目錄已在 PATH 時最省事):
|
也可以在 clone 目錄內直接裝進 `GOBIN`:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
go install ./cmd/teai
|
go install ./cmd/teai
|
||||||
```
|
```
|
||||||
|
|
||||||
> **注意:** `go install gitea.alterminal.com/alterminal/teai/cmd/teai@latest` 目前**不可用**——
|
clone 建置時 Go 會把 VCS 狀態寫進 build info:位於 tag 上顯示該 tag、
|
||||||
> module 尚未發佈任何 tag,`@latest` 會解析到任意中繼 commit(且 #21 修復前 main 建置失敗)。
|
其後的 commit 顯示 pseudo-version(如 `v0.1.1-0.20260912160956-5a48fdd590b2`)、
|
||||||
> 請在 clone 目錄內以版本控制的方式建置;發佈 tag 後再提供 `teai@<version>` 安裝路徑。
|
工作樹有修改再附加 `+dirty`;無 VCS 資訊(如從 tarball 解壓建置)時
|
||||||
|
`Main.Version` 為 `(devel)`,此時退回開發版本號 `0.1.0-dev`。
|
||||||
|
|
||||||
### 登入設定(首次使用)
|
### 登入設定(首次使用)
|
||||||
|
|
||||||
teai 與 `tea` 共用同一份組態檔;若 `tea whoami` 已可正常輸出,可跳過本節。
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
teai login add --url https://gitea.alterminal.com
|
teai login add --url https://gitea.alterminal.com
|
||||||
# 未給 --token 時自 stdin 讀一行:貼上 token 後按 Enter(不會進 shell 歷史)
|
# 未給 --token 時自 stdin 讀一行:貼上 token 後按 Enter(不會進 shell 歷史)
|
||||||
@@ -48,8 +66,7 @@ teai whoami # 驗證:應輸出 {"username":"<你的帳號>"}
|
|||||||
```
|
```
|
||||||
|
|
||||||
- token 驗證失敗(HTTP 401)不會寫入組態,結束碼 3。
|
- token 驗證失敗(HTTP 401)不會寫入組態,結束碼 3。
|
||||||
- 組態檔:`--config`/`TEA_CONFIG` 指定,預設 `~/.config/tea/config.yml`;teai 採行級編輯,
|
- 組態檔:`--config`/`TEAI_CONFIG` 指定,預設 `~/.config/teai/config.yml`;檔案權限 `0600`。
|
||||||
不會改壞 tea 也在使用的欄位,檔案權限 `0600`。
|
|
||||||
- 多站台以 `--name` 區分、`teai login default <名稱>` 切換預設;詳見下方 [`teai login`](#teai-login--管理登入) 一節。
|
- 多站台以 `--name` 區分、`teai login default <名稱>` 切換預設;詳見下方 [`teai login`](#teai-login--管理登入) 一節。
|
||||||
|
|
||||||
## 指令設計
|
## 指令設計
|
||||||
@@ -63,26 +80,31 @@ teai whoami # 驗證:應輸出 {"username":"<你的帳號>"}
|
|||||||
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. **自主認證組態**:登入資料寫在 teai 自己的組態(`TEAI_CONFIG` 或 `~/.config/teai/config.yml`),不依賴 tea。
|
||||||
6. **安全預設**:查詢類唯讀;寫入類命令(#8 起)一律要求明確 `--yes`,未確認時不發出任何請求、不產生任何遠端變更。
|
6. **安全預設**:查詢類唯讀;寫入類命令(#8 起)一律要求明確 `--yes`,未確認時不發出任何請求、不產生任何遠端變更。
|
||||||
|
|
||||||
### 日常操作(tea 對等指令;#3 不避開 tea 已有功能;#8 已實作)
|
### 日常操作(tea 對等指令;#3 不避開 tea 已有功能;#8 已實作)
|
||||||
|
|
||||||
issues/pulls/labels/milestones/releases/repos/api 的日常操作,自行實作、輸出一致 JSON、共用同一套認證與全域選項。介面語義以 `tea`/Gitea API 為相容參考。已實作:
|
issues/pulls/labels/milestones/releases/repos/organizations/api 的日常操作,自行實作、輸出一致 JSON、共用同一套認證與全域選項。介面語義以 `tea`/Gitea API 為相容參考。已實作:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# issues
|
# issues
|
||||||
teai issues list --repo <owner>/<repo> [--state open|closed|all]
|
teai issues list --repo <owner>/<repo> [--state open|closed|all] [--labels a,b] # 多標籤 AND
|
||||||
teai issues view --repo <owner>/<repo> <number> [--comments]
|
teai issues view --repo <owner>/<repo> <number> [--comments]
|
||||||
teai issues create --repo <owner>/<repo> --title … [--body …] [--assignees a,b] --yes
|
teai issues create --repo <owner>/<repo> --title … [--body …] [--assignees a,b] --yes
|
||||||
teai issues close --repo <owner>/<repo> --yes <number>
|
teai issues close --repo <owner>/<repo> --yes <number>
|
||||||
teai issues comment --repo <owner>/<repo> --body … --yes <number>
|
teai issues comment --repo <owner>/<repo> [--body …] --yes <number> [留言…] # 位置參數優先(#40)
|
||||||
# pulls(無子命令仍是工作流清單:--mine/--reviewer/--repo)
|
# pulls(無子命令仍是工作流清單:--mine/--reviewer/--repo)
|
||||||
teai pulls list --repo <owner>/<repo> [--state open|closed|all]
|
teai pulls list --repo <owner>/<repo> [--state open|closed|all]
|
||||||
teai pulls view --repo <owner>/<repo> <number> [--comments]
|
teai pulls view --repo <owner>/<repo> <number> [--comments]
|
||||||
teai pulls create --repo <owner>/<repo> --head <branch> [--base main] --title … [--body …] --yes
|
teai pulls create --repo <owner>/<repo> --head <branch> [--base main] --title … [--body …] --yes
|
||||||
teai pulls merge --repo <owner>/<repo> [--style merge|rebase|rebase-merge|squash] --yes <number>
|
teai pulls merge --repo <owner>/<repo> [--style merge|rebase|rebase-merge|squash] --yes <number>
|
||||||
teai pulls comment --repo <owner>/<repo> --body … --yes <number>
|
teai pulls approve --repo <owner>/<repo> [--body …] --yes <number> [意見…] # POST reviews,event=APPROVED(#40)
|
||||||
|
teai pulls close --repo <owner>/<repo> --yes <number> # 關閉不合併(PATCH state=closed;#40)
|
||||||
|
teai pulls checkout --repo <owner>/<repo> [--dir <path>] <number> # 本機 git 取得 head(#40)
|
||||||
|
teai pulls comment --repo <owner>/<repo> [--body …] --yes <number> [留言…]
|
||||||
|
# 通用留言(tea comment 對等;issue 與 PR 共用端點,#40)
|
||||||
|
teai comment --repo <owner>/<repo> [--body …] --yes <number> [留言…]
|
||||||
# labels/milestones/releases/repos
|
# labels/milestones/releases/repos
|
||||||
teai labels list --repo <owner>/<repo>
|
teai labels list --repo <owner>/<repo>
|
||||||
teai labels create --repo <owner>/<repo> --name … [--color #RRGGBB] [--description …] --yes
|
teai labels create --repo <owner>/<repo> --name … [--color #RRGGBB] [--description …] --yes
|
||||||
@@ -92,12 +114,17 @@ teai milestones list --repo <owner>/<repo> [--state open|closed|all]
|
|||||||
teai milestones create --repo <owner>/<repo> --title … [--description …] [--due RFC3339] --yes
|
teai milestones create --repo <owner>/<repo> --title … [--description …] [--due RFC3339] --yes
|
||||||
teai releases list --repo <owner>/<repo>
|
teai releases list --repo <owner>/<repo>
|
||||||
teai repos list [--org <org>]
|
teai repos list [--org <org>]
|
||||||
|
# 組織管理(tea organizations 對等;#45)
|
||||||
|
teai organizations list # 列出自己可存取的組織(GET /user/orgs)
|
||||||
|
teai organizations create --name <org> [--full-name …] [--description …] [--website …] [--location …] [--visibility public|limited|private] --yes
|
||||||
|
teai organizations delete <org> --yes # 刪除組織(不可逆;DELETE /orgs/{org})
|
||||||
# 任意 API 呼叫(逃生口)
|
# 任意 API 呼叫(逃生口)
|
||||||
teai api <path> [--method GET|POST|PATCH|DELETE] [--data '<json>'] [--yes]
|
teai api <path> [--method GET|POST|PATCH|DELETE] [--data '<json>'] [--yes]
|
||||||
```
|
```
|
||||||
|
|
||||||
> `--yes` 閘門:所有寫入類命令(create/close/comment/merge/labels create/milestones create/api 非 GET 動詞)未帶 `--yes` 時回 exit 2(用法錯誤),且不發出任何 HTTP 請求。
|
> `--yes` 閘門:所有寫入類命令(create/close/comment/merge/approve/labels create/milestones create/organizations create/delete/api 非 GET 動詞)未帶 `--yes` 時回 exit 2(用法錯誤),且不發出任何 HTTP 請求。
|
||||||
> `teai api` 的 path 內含查詢字串(如 `/repos/a/b/issues?state=closed`)時會正確傳遞。
|
> `teai api` 的 path 內含查詢字串(如 `/repos/a/b/issues?state=closed`)時會正確傳遞。
|
||||||
|
> `teai pulls checkout` 是本機唯讀輔助:同倉庫 head 在 `--dir`(預設當前目錄)的既有工作樹 `git fetch origin <ref> && git checkout -B <ref> FETCH_HEAD`;跨倉庫 head 需 `--dir`(新目錄)執行 `git clone --branch <ref> <clone_url>`。teai 不代管 git 認證,私有倉庫請自備 credential helper。
|
||||||
|
|
||||||
### 全域介面
|
### 全域介面
|
||||||
|
|
||||||
@@ -108,8 +135,8 @@ teai [全域選項] <命令> [參數]
|
|||||||
| 選項 | 說明 |
|
| 選項 | 說明 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `--url <URL>` | Gitea 站點,預設 `https://gitea.alterminal.com` |
|
| `--url <URL>` | Gitea 站點,預設 `https://gitea.alterminal.com` |
|
||||||
| `--token <TOKEN>` | API token;未給則依序嘗試 `TEAI_TOKEN` 環境變數、tea 登入組態 |
|
| `--token <TOKEN>` | API token;未給則依序嘗試 `TEAI_TOKEN` 環境變數、teai 登入組態 |
|
||||||
| `--config <path>` | tea 組態檔路徑,等同 `TEA_CONFIG` |
|
| `--config <path>` | teai 組態檔路徑,等同 `TEAI_CONFIG` |
|
||||||
| `--output json\|table` | 輸出格式,預設 `json` |
|
| `--output json\|table` | 輸出格式,預設 `json` |
|
||||||
| `--timeout <dur>` | HTTP 請求逾時,預設 `30s` |
|
| `--timeout <dur>` | HTTP 請求逾時,預設 `30s` |
|
||||||
|
|
||||||
@@ -117,9 +144,11 @@ teai [全域選項] <命令> [參數]
|
|||||||
|
|
||||||
| 命令 | 對應 gitea.py | 說明 |
|
| 命令 | 對應 gitea.py | 說明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `teai login list\|add\|default\|remove` | — | 管理 tea 相容登入組態(見下) |
|
| `teai login list\|add\|default\|remove` | — | 管理登入組態(見下) |
|
||||||
| `teai whoami` | `get_current_username` | 目前帳號 |
|
| `teai whoami` | `get_current_username` | 目前帳號 |
|
||||||
|
| `teai role` | — | 目前角色(Supervisor 團隊→supervisor,Agents 團隊→worker) |
|
||||||
| `teai orgs` | `for_all_organizations` | 我所屬的組織 |
|
| `teai orgs` | `for_all_organizations` | 我所屬的組織 |
|
||||||
|
| `teai organizations list\|create\|delete` | — | 組織管理(tea 對等日常操作;`orgs` 是工作流精簡版) |
|
||||||
| `teai members [--has-work]` | `members [--has-work]` | Agents 團隊成員;`--has-work` 只列有未完成工作者 |
|
| `teai members [--has-work]` | `members [--has-work]` | Agents 團隊成員;`--has-work` 只列有未完成工作者 |
|
||||||
| `teai mine` | `mine` | 分派給我、待跟進的 issues |
|
| `teai mine` | `mine` | 分派給我、待跟進的 issues |
|
||||||
| `teai pulls [--mine\|--reviewer] [--repo <owner>/<repo>]` | `pulls` 系列 | 跨倉庫 PR 跟進清單 |
|
| `teai pulls [--mine\|--reviewer] [--repo <owner>/<repo>]` | `pulls` 系列 | 跨倉庫 PR 跟進清單 |
|
||||||
@@ -158,9 +187,8 @@ teai next --output table # 人類可讀
|
|||||||
|
|
||||||
### `teai login` — 管理登入
|
### `teai login` — 管理登入
|
||||||
|
|
||||||
teai 與 tea 共用同一份組態檔(`--config`/`TEA_CONFIG`,預設 `~/.config/tea/config.yml`)。
|
登入組態由 teai 自行管理(`--config`/`TEAI_CONFIG`,預設 `~/.config/teai/config.yml`)。
|
||||||
寫入採行級編輯:只動目標項目的行,未知欄位(`ssh_*` 等)與 `preferences` 區段逐字保留,
|
寫入採行級編輯:只動目標項目的行,未知欄位與註解逐字保留;檔案權限 `0600`、暫存檔原子替換。
|
||||||
不改壞 tea 也在使用的檔案;檔案權限 `0600`、暫存檔原子替換。
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
teai login list # 列出登入(一律不含 token)
|
teai login list # 列出登入(一律不含 token)
|
||||||
@@ -209,6 +237,11 @@ PR 改帶 `author` 與 `reviewers` 欄位。`reason` 取值:
|
|||||||
- issue:`no-assignee`、`assignee-idle`、`no-commenter`、`waiting-outside`、`parent-tracking`
|
- issue:`no-assignee`、`assignee-idle`、`no-commenter`、`waiting-outside`、`parent-tracking`
|
||||||
- PR:`no-reviewer`、`author-idle`、`reviewer-idle`、`no-commenter`
|
- PR:`no-reviewer`、`author-idle`、`reviewer-idle`、`no-commenter`
|
||||||
|
|
||||||
|
`assignee-idle` 判定前會先檢查最後一則 assignee 留言是否為**交付報告**(agents #47):
|
||||||
|
逐項查核/驗收結果(結構訊號)∧ 回報他件/請他人確認關閉(交棒訊號)同時命中 →
|
||||||
|
改判 `waiting-outside`——已交付待發起人確認不是 assignee 停滯。認領/進度/預告式
|
||||||
|
留言(無交棒對象)維持 `assignee-idle`,不製造「認領後棄置永不被催」的新死角。
|
||||||
|
|
||||||
### `teai milestones` — 跨倉庫里程碑總覽
|
### `teai milestones` — 跨倉庫里程碑總覽
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -274,13 +307,21 @@ teai pulls --repo alterminal/teai # 限定單一倉庫
|
|||||||
teai mine # 分派給我、最後一則留言不是自己的 open issues(跨所屬組織)
|
teai mine # 分派給我、最後一則留言不是自己的 open issues(跨所屬組織)
|
||||||
```
|
```
|
||||||
|
|
||||||
### `teai orgs` / `teai whoami`
|
### `teai orgs` / `teai whoami` / `teai role`
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
teai orgs # 我所屬的組織
|
teai orgs # 我所屬的組織
|
||||||
teai whoami # 目前帳號(讀 tea 組態)
|
teai whoami # 目前帳號
|
||||||
|
teai role # 目前角色
|
||||||
```
|
```
|
||||||
|
|
||||||
|
角色由所屬組織的團隊決定:
|
||||||
|
|
||||||
|
- 在 **Supervisor** 團隊 → `{"role":"supervisor"}`
|
||||||
|
- 在 **Agents** 團隊 → `{"role":"worker"}`
|
||||||
|
- 同時屬於兩者時以 supervisor 為準
|
||||||
|
- 兩者都不屬於 → 輸出 `null`,exit 0
|
||||||
|
|
||||||
### `teai xrefs <owner>/<repo> <number>` — 引用解析
|
### `teai xrefs <owner>/<repo> <number>` — 引用解析
|
||||||
|
|
||||||
解析該 issue/PR 內文與全部留言中的 `#N`、`repo#N`、`owner/repo#N` 引用,輸出解析後的目標清單(去重):
|
解析該 issue/PR 內文與全部留言中的 `#N`、`repo#N`、`owner/repo#N` 引用,輸出解析後的目標清單(去重):
|
||||||
@@ -299,7 +340,7 @@ teai whoami # 目前帳號(讀 tea 組態)
|
|||||||
|
|
||||||
| 碼 | 意義 |
|
| 碼 | 意義 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 0 | 成功(含「沒有工作」→ 輸出 `null`/`[]`) |
|
| 0 | 成功(含「沒有結果」→ 清單類命令輸出 `[]`、`next`/`role` 輸出 `null`;#37 判決) |
|
||||||
| 2 | 用法錯誤(未知命令/參數) |
|
| 2 | 用法錯誤(未知命令/參數) |
|
||||||
| 3 | API 錯誤(連線失敗、401、403、5xx) |
|
| 3 | API 錯誤(連線失敗、401、403、5xx) |
|
||||||
|
|
||||||
@@ -318,8 +359,13 @@ teai whoami # 目前帳號(讀 tea 組態)
|
|||||||
已知輸出差異(刻意保留,機器可讀優先):
|
已知輸出差異(刻意保留,機器可讀優先):
|
||||||
|
|
||||||
- **空清單**:`gitea.py` 的 `_dump` 對空清單**不輸出任何內容**;teai 的清單類命令
|
- **空清單**:`gitea.py` 的 `_dump` 對空清單**不輸出任何內容**;teai 的清單類命令
|
||||||
(`mine`/`pulls`/`milestones` 總覽)空清單輸出 `[]`。對 JSON 消費者來說 `[]` 比「無輸出」更明確,
|
(`mine`/`pulls`/`stalled`/`milestones` 總覽)空清單一律輸出 `[]`(exit 0)。對 JSON
|
||||||
交叉驗證時以此差異為準。`next` 兩者語義相同(無工作 → `null`/「沒有未完成的工作」)。
|
消費者來說 `[]` 比「無輸出」更明確(可區分「沒有結果」與「查詢失敗無輸出」),交叉驗證時
|
||||||
|
以此差異為準。`next` 兩者語義相同:無工作時 teai 輸出 `null`(exit 0)、`gitea.py` 印
|
||||||
|
「沒有未完成的工作」。**判決 #37:維持 teai 現行 JSON 一致性(方向 2)**——消費端
|
||||||
|
(agents 倉庫巡邏提示與觸發腳本)應以「輸出 `[]`/`null` 且 exit 0」為「沒有」判據,
|
||||||
|
不得以「無輸出」判斷;`members [--has-work]` 維持逐行帳號、空時無輸出(兩者一致,不受影響)。
|
||||||
|
`teai role` 不在 Supervisor/Agents 時同樣輸出 `null`(exit 0)。
|
||||||
- **清單欄位集(`mine`/`pulls`)**:`gitea.py` 直接傾倒完整 Gitea API 物件
|
- **清單欄位集(`mine`/`pulls`)**:`gitea.py` 直接傾倒完整 Gitea API 物件
|
||||||
(`_dump` 的副作用,欄位集隨 Gitea 版本浮動);teai 輸出策展摘要欄位
|
(`_dump` 的副作用,欄位集隨 Gitea 版本浮動);teai 輸出策展摘要欄位
|
||||||
(`mine`:repo/number/title/url;`pulls`:number/title/state/author/
|
(`mine`:repo/number/title/url;`pulls`:number/title/state/author/
|
||||||
@@ -339,7 +385,7 @@ teai whoami # 目前帳號(讀 tea 組態)
|
|||||||
### 安全設計
|
### 安全設計
|
||||||
|
|
||||||
- 本期命令全部唯讀;寫入類命令未來加入時須 `--yes` 明確確認。
|
- 本期命令全部唯讀;寫入類命令未來加入時須 `--yes` 明確確認。
|
||||||
- token 不入輸出、不入日誌;建議用 `TEAI_TOKEN` 或 tea 組態,避免出現在命令列。
|
- token 不入輸出、不入日誌;建議用 `TEAI_TOKEN` 或 teai 組態,避免出現在命令列。
|
||||||
- 清單類 API 一律帶 `limit`(Gitea 預設上限 50),避免漏抓。
|
- 清單類 API 一律帶 `limit`(Gitea 預設上限 50),避免漏抓。
|
||||||
- 「有無實際產出」的判斷一律對照遠端實況(API 回傳),不信任回報文字。
|
- 「有無實際產出」的判斷一律對照遠端實況(API 回傳),不信任回報文字。
|
||||||
|
|
||||||
|
|||||||
@@ -165,6 +165,14 @@ func (s *apiSource) IssueComments(owner, repo string, number int64) ([]workflow.
|
|||||||
return comments, nil
|
return comments, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *apiSource) IssueTimeline(owner, repo string, number int64) ([]workflow.TimelineEvent, error) {
|
||||||
|
var events []workflow.TimelineEvent
|
||||||
|
if err := s.listAll(fmt.Sprintf("repos/%s/%s/issues/%d/timeline", owner, repo, number), nil, &events); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return events, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *apiSource) TryGetIssue(owner, repo string, number int64) (workflow.Issue, bool, error) {
|
func (s *apiSource) TryGetIssue(owner, repo string, number int64) (workflow.Issue, bool, error) {
|
||||||
var issue workflow.Issue
|
var issue workflow.Issue
|
||||||
body, code, err := s.get(fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, number), nil)
|
body, code, err := s.get(fmt.Sprintf("repos/%s/%s/issues/%d", owner, repo, number), nil)
|
||||||
|
|||||||
+22
-5
@@ -15,6 +15,7 @@ import (
|
|||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"runtime/debug"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -23,8 +24,24 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Version 是目前開發中的版本號。採用語意化版本;正式發佈前以 0 開頭。
|
// Version 是目前開發中的版本號。採用語意化版本;正式發佈前以 0 開頭。
|
||||||
|
// 僅作為 fallback:以 `go install module@version` 或納入其他 module 建置時,
|
||||||
|
// buildVersion 會改用 build info 內的 module 版本(見 runVersion)。
|
||||||
var Version = "0.1.0-dev"
|
var Version = "0.1.0-dev"
|
||||||
|
|
||||||
|
// buildVersion 回傳應顯示的版本字串。go install pkg@tag 建置的二元檔
|
||||||
|
// 會在 Main.Version 帶入 tag(如 v0.1.0);clone 目錄內本機建置則帶
|
||||||
|
// pseudo-version(如 v0.1.1-0.<時間戳>-<commit>,工作樹有修改時再附加
|
||||||
|
// "+dirty"),同樣直接顯示。Main.Version 為 "(devel)" 或空(go test 環境、
|
||||||
|
// 無 VCS 資訊的 tarball 建置)時,才退回開發版本號 Version。
|
||||||
|
func buildVersion() string {
|
||||||
|
if info, ok := debug.ReadBuildInfo(); ok {
|
||||||
|
if v := info.Main.Version; v != "" && v != "(devel)" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Version
|
||||||
|
}
|
||||||
|
|
||||||
// ExitCode 是 Run 回傳的行程結束碼。
|
// ExitCode 是 Run 回傳的行程結束碼。
|
||||||
type ExitCode int
|
type ExitCode int
|
||||||
|
|
||||||
@@ -58,9 +75,9 @@ type command struct {
|
|||||||
type Globals struct {
|
type Globals struct {
|
||||||
// URL 是 Gitea 站點網址。
|
// URL 是 Gitea 站點網址。
|
||||||
URL string
|
URL string
|
||||||
// Token 來自 --token 旗標;空字串表示未提供(依序退回環境變數與 tea 組態)。
|
// Token 來自 --token 旗標;空字串表示未提供(依序退回環境變數與 teai 組態)。
|
||||||
Token string
|
Token string
|
||||||
// ConfigPath 是 tea 組態路徑(--config,等同 TEA_CONFIG)。
|
// ConfigPath 是 teai 組態路徑(--config,等同 TEAI_CONFIG)。
|
||||||
ConfigPath string
|
ConfigPath string
|
||||||
// Output 是輸出格式。
|
// Output 是輸出格式。
|
||||||
Output gitea.Format
|
Output gitea.Format
|
||||||
@@ -437,7 +454,7 @@ func runVersion(env *Env, args []string) error {
|
|||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
return &ErrUsage{Msg: "version 不接受參數"}
|
return &ErrUsage{Msg: "version 不接受參數"}
|
||||||
}
|
}
|
||||||
fmt.Fprintf(env.Out, "teai version %s\n", Version)
|
fmt.Fprintf(env.Out, "teai version %s\n", buildVersion())
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -447,8 +464,8 @@ func printUsage(w io.Writer) {
|
|||||||
fmt.Fprintf(w, "用法:\n teai [全域選項] <命令> [參數]\n\n")
|
fmt.Fprintf(w, "用法:\n teai [全域選項] <命令> [參數]\n\n")
|
||||||
fmt.Fprintf(w, "全域選項:\n")
|
fmt.Fprintf(w, "全域選項:\n")
|
||||||
fmt.Fprintf(w, " --url <URL> Gitea 站點(預設 https://gitea.alterminal.com)\n")
|
fmt.Fprintf(w, " --url <URL> Gitea 站點(預設 https://gitea.alterminal.com)\n")
|
||||||
fmt.Fprintf(w, " --token <TOKEN> API token;未給則依序嘗試 TEAI_TOKEN、tea 登入組態\n")
|
fmt.Fprintf(w, " --token <TOKEN> API token;未給則依序嘗試 TEAI_TOKEN、teai 登入組態\n")
|
||||||
fmt.Fprintf(w, " --config <path> tea 組態檔路徑,等同 TEA_CONFIG\n")
|
fmt.Fprintf(w, " --config <path> teai 組態檔路徑,等同 TEAI_CONFIG\n")
|
||||||
fmt.Fprintf(w, " --output <format> 輸出格式 json|table(預設 json)\n")
|
fmt.Fprintf(w, " --output <format> 輸出格式 json|table(預設 json)\n")
|
||||||
fmt.Fprintf(w, " --timeout <dur> HTTP 逾時(預設 30s)\n\n")
|
fmt.Fprintf(w, " --timeout <dur> HTTP 逾時(預設 30s)\n\n")
|
||||||
fmt.Fprintf(w, "命令:\n")
|
fmt.Fprintf(w, "命令:\n")
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// dailyops_commands.go — 日常操作命令的 CLI 接線(#8):issues、pulls、
|
// dailyops_commands.go — 日常操作命令的 CLI 接線(#8):issues、pulls、
|
||||||
// labels、milestones、releases、repos、api(tea 對等指令)。
|
// labels、milestones、releases、repos、organizations、api(tea 對等指令)。
|
||||||
//
|
//
|
||||||
// 規則:
|
// 規則:
|
||||||
// - 寫入類命令(create/close/comment/merge…)一律要求 --yes,
|
// - 寫入類命令(create/close/comment/merge…)一律要求 --yes,
|
||||||
@@ -14,6 +14,9 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -23,12 +26,14 @@ import (
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
register := func(c *command) { commands[c.name] = c }
|
register := func(c *command) { commands[c.name] = c }
|
||||||
register(&command{name: "issues", usage: "issues 管理(list/view/create/close/comment)", run: runIssues})
|
register(&command{name: "issues", usage: "issues 管理(list/view/create/close/comment;list 支援 --labels 過濾)", run: runIssues})
|
||||||
register(&command{name: "pulls", usage: "PR 管理(list/view/create/merge/comment;無子命令=工作流清單)", run: runPullsDaily})
|
register(&command{name: "pulls", usage: "PR 管理(list/view/create/merge/approve/close/checkout/comment;無子命令=工作流清單)", run: runPullsDaily})
|
||||||
|
register(&command{name: "comment", usage: "對 issue 或 PR 留言(--repo owner/repo <number> --body …)", run: runCommentDirect})
|
||||||
register(&command{name: "labels", usage: "標籤管理(list/create)", run: runLabels})
|
register(&command{name: "labels", usage: "標籤管理(list/create)", run: runLabels})
|
||||||
register(&command{name: "milestones", usage: "里程碑(跨倉庫總覽;list/create 管理單倉庫)", run: runMilestones})
|
register(&command{name: "milestones", usage: "里程碑(跨倉庫總覽;list/create 管理單倉庫)", run: runMilestones})
|
||||||
register(&command{name: "releases", usage: "發佈清單(list)", run: runReleases})
|
register(&command{name: "releases", usage: "發佈清單(list)", run: runReleases})
|
||||||
register(&command{name: "repos", usage: "倉庫查詢(list)", run: runRepos})
|
register(&command{name: "repos", usage: "倉庫查詢(list)", run: runRepos})
|
||||||
|
register(&command{name: "organizations", usage: "組織管理(list/create/delete;tea organizations 對等)", run: runOrganizations})
|
||||||
register(&command{name: "api", usage: "任意 API 呼叫(--method/--data;寫入動詞需 --yes)", run: runAPIDirect})
|
register(&command{name: "api", usage: "任意 API 呼叫(--method/--data;寫入動詞需 --yes)", run: runAPIDirect})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,12 +127,13 @@ func runIssues(env *Env, args []string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// runIssuesList:teai issues list --repo owner/repo [--state open|closed|all]
|
// runIssuesList:teai issues list --repo owner/repo [--state open|closed|all] [--labels a,b]
|
||||||
func runIssuesList(env *Env, args []string) error {
|
func runIssuesList(env *Env, args []string) error {
|
||||||
fs := flag.NewFlagSet("teai issues list", flag.ContinueOnError)
|
fs := flag.NewFlagSet("teai issues list", flag.ContinueOnError)
|
||||||
fs.SetOutput(env.Err)
|
fs.SetOutput(env.Err)
|
||||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||||
state := fs.String("state", "open", "狀態:open|closed|all")
|
state := fs.String("state", "open", "狀態:open|closed|all")
|
||||||
|
labels := fs.String("labels", "", "標籤過濾(逗號分隔,可選;多標籤為 AND)")
|
||||||
if err := parseFlags(fs, args); err != nil {
|
if err := parseFlags(fs, args); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -141,11 +147,19 @@ func runIssuesList(env *Env, args []string) error {
|
|||||||
if owner == "" {
|
if owner == "" {
|
||||||
return &ErrUsage{Msg: "issues list 需要 --repo owner/repo"}
|
return &ErrUsage{Msg: "issues list 需要 --repo owner/repo"}
|
||||||
}
|
}
|
||||||
|
var labelList []string
|
||||||
|
if strings.TrimSpace(*labels) != "" {
|
||||||
|
for _, l := range strings.Split(*labels, ",") {
|
||||||
|
if l = strings.TrimSpace(l); l != "" {
|
||||||
|
labelList = append(labelList, l)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
ops, err := newOpsClient(env)
|
ops, err := newOpsClient(env)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
issues, err := ops.ListIssues(context.Background(), owner, name, *state)
|
issues, err := ops.ListIssues(context.Background(), owner, name, *state, labelList)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -316,6 +330,8 @@ func runIssuesClose(env *Env, args []string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// runComment:teai issues comment / teai pulls comment 共用。
|
// runComment:teai issues comment / teai pulls comment 共用。
|
||||||
|
// 相容 tea 用法:留言可作為位置參數(tea comment --repo a/b <index> "內容"),
|
||||||
|
// 亦可 teai 慣用的 --body;兩者同時給時位置參數優先(與 tea 行為一致)。
|
||||||
func runComment(env *Env, args []string, isPR bool) error {
|
func runComment(env *Env, args []string, isPR bool) error {
|
||||||
name := "issues comment"
|
name := "issues comment"
|
||||||
if isPR {
|
if isPR {
|
||||||
@@ -324,7 +340,7 @@ func runComment(env *Env, args []string, isPR bool) error {
|
|||||||
fs := flag.NewFlagSet("teai "+name, flag.ContinueOnError)
|
fs := flag.NewFlagSet("teai "+name, flag.ContinueOnError)
|
||||||
fs.SetOutput(env.Err)
|
fs.SetOutput(env.Err)
|
||||||
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||||
body := fs.String("body", "", "留言內容(必填)")
|
body := fs.String("body", "", "留言內容(可改用位置參數)")
|
||||||
yes := fs.Bool("yes", false, "確認寫入")
|
yes := fs.Bool("yes", false, "確認寫入")
|
||||||
if err := parseFlags(fs, args); err != nil {
|
if err := parseFlags(fs, args); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -336,16 +352,21 @@ func runComment(env *Env, args []string, isPR bool) error {
|
|||||||
if owner == "" {
|
if owner == "" {
|
||||||
return &ErrUsage{Msg: name + " 需要 --repo owner/repo"}
|
return &ErrUsage{Msg: name + " 需要 --repo owner/repo"}
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(*body) == "" {
|
// 位置參數:<number> [body…];尾端多餘引數以空格接成一則留言(tea 相容)。
|
||||||
return &ErrUsage{Msg: name + " 需要 --body"}
|
if fs.NArg() < 1 {
|
||||||
}
|
return &ErrUsage{Msg: name + " 需要恰好一個編號(可選加留言位置參數)"}
|
||||||
if fs.NArg() != 1 {
|
|
||||||
return &ErrUsage{Msg: name + " 需要恰好一個編號"}
|
|
||||||
}
|
}
|
||||||
num, err := parseNumber(fs.Arg(0))
|
num, err := parseNumber(fs.Arg(0))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
text := strings.TrimSpace(*body)
|
||||||
|
if fs.NArg() > 1 {
|
||||||
|
text = strings.TrimSpace(strings.Join(fs.Args()[1:], " "))
|
||||||
|
}
|
||||||
|
if text == "" {
|
||||||
|
return &ErrUsage{Msg: name + " 需要留言內容(--body 或位置參數)"}
|
||||||
|
}
|
||||||
if err := requireYes(*yes, name); err != nil {
|
if err := requireYes(*yes, name); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -353,7 +374,7 @@ func runComment(env *Env, args []string, isPR bool) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
comment, err := ops.AddComment(context.Background(), owner, rname, num, *body)
|
comment, err := ops.AddComment(context.Background(), owner, rname, num, text)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -381,13 +402,26 @@ func runPullsDaily(env *Env, args []string) error {
|
|||||||
return runPullsCreate(env, rest)
|
return runPullsCreate(env, rest)
|
||||||
case "merge":
|
case "merge":
|
||||||
return runPullsMerge(env, rest)
|
return runPullsMerge(env, rest)
|
||||||
|
case "approve":
|
||||||
|
return runPullsApprove(env, rest)
|
||||||
|
case "close":
|
||||||
|
return runPullsClose(env, rest)
|
||||||
|
case "checkout":
|
||||||
|
return runPullsCheckout(env, rest)
|
||||||
case "comment":
|
case "comment":
|
||||||
return runComment(env, rest, true)
|
return runComment(env, rest, true)
|
||||||
default:
|
default:
|
||||||
return &ErrUsage{Msg: fmt.Sprintf("pulls 未知子命令 %q(可用:list | view | create | merge | comment;或無子命令=工作流清單)", sub)}
|
return &ErrUsage{Msg: fmt.Sprintf("pulls 未知子命令 %q(可用:list | view | create | merge | approve | close | checkout | comment;或無子命令=工作流清單)", sub)}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runCommentDirect:teai comment --repo owner/repo <number> <body> [--yes]。
|
||||||
|
// tea 的通用留言指令:issue 與 PR 共用同一端點(Gitea 以 number 定位,
|
||||||
|
// issues/<n>/comments 對兩者皆有效),故不需 --type 旗標。
|
||||||
|
func runCommentDirect(env *Env, args []string) error {
|
||||||
|
return runComment(env, args, false)
|
||||||
|
}
|
||||||
|
|
||||||
// runPullsList:teai pulls list --repo owner/repo [--state open|closed|all]
|
// runPullsList:teai pulls list --repo owner/repo [--state open|closed|all]
|
||||||
func runPullsList(env *Env, args []string) error {
|
func runPullsList(env *Env, args []string) error {
|
||||||
fs := flag.NewFlagSet("teai pulls list", flag.ContinueOnError)
|
fs := flag.NewFlagSet("teai pulls list", flag.ContinueOnError)
|
||||||
@@ -560,6 +594,179 @@ func runPullsMerge(env *Env, args []string) error {
|
|||||||
}, gitea.Values{num, "merged"})
|
}, gitea.Values{num, "merged"})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runPullsApprove:teai pulls approve --repo owner/repo [--body …] --yes <number>。
|
||||||
|
// tea 相容:意見也可作為位置參數(teai pulls approve --repo a/b <n> "驗證通過。")。
|
||||||
|
func runPullsApprove(env *Env, args []string) error {
|
||||||
|
fs := flag.NewFlagSet("teai pulls approve", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(env.Err)
|
||||||
|
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||||
|
body := fs.String("body", "", "審核意見(可改用位置參數)")
|
||||||
|
yes := fs.Bool("yes", false, "確認寫入")
|
||||||
|
if err := parseFlags(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
owner, name, err := splitRepoFlag(*repo)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if owner == "" {
|
||||||
|
return &ErrUsage{Msg: "pulls approve 需要 --repo owner/repo"}
|
||||||
|
}
|
||||||
|
if fs.NArg() < 1 {
|
||||||
|
return &ErrUsage{Msg: "pulls approve 需要恰好一個編號(可選加意見位置參數)"}
|
||||||
|
}
|
||||||
|
num, err := parseNumber(fs.Arg(0))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
text := strings.TrimSpace(*body)
|
||||||
|
if fs.NArg() > 1 {
|
||||||
|
text = strings.TrimSpace(strings.Join(fs.Args()[1:], " "))
|
||||||
|
}
|
||||||
|
if err := requireYes(*yes, "pulls approve"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ops, err := newOpsClient(env)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
review, err := ops.ApprovePull(context.Background(), owner, name, num, text)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return printer(env).PrintOne([]gitea.Field{
|
||||||
|
{Name: "number"}, {Name: "state"}, {Name: "author"}, {Name: "body"},
|
||||||
|
}, gitea.Values{review.Number, review.State, review.Author(), review.Body})
|
||||||
|
}
|
||||||
|
|
||||||
|
// runPullsClose:teai pulls close --repo owner/repo --yes <number>。
|
||||||
|
// 關閉不合併;工作流約定 merge 才是正途(AGENTS.md 6.2),本指令提供語義對等。
|
||||||
|
func runPullsClose(env *Env, args []string) error {
|
||||||
|
fs := flag.NewFlagSet("teai pulls close", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(env.Err)
|
||||||
|
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||||
|
yes := fs.Bool("yes", false, "確認寫入")
|
||||||
|
if err := parseFlags(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
owner, name, err := splitRepoFlag(*repo)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if owner == "" {
|
||||||
|
return &ErrUsage{Msg: "pulls close 需要 --repo owner/repo"}
|
||||||
|
}
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return &ErrUsage{Msg: "pulls close 需要恰好一個編號"}
|
||||||
|
}
|
||||||
|
num, err := parseNumber(fs.Arg(0))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := requireYes(*yes, "pulls close"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ops, err := newOpsClient(env)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pr, err := ops.ClosePull(context.Background(), owner, name, num)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return printer(env).PrintOne([]gitea.Field{
|
||||||
|
{Name: "number"}, {Name: "title"}, {Name: "state"}, {Name: "url"},
|
||||||
|
}, gitea.Values{pr.Number, pr.Title, pr.State, pr.HTMLURL})
|
||||||
|
}
|
||||||
|
|
||||||
|
// runPullsCheckout:teai pulls checkout --repo owner/repo <number> [--dir <path>]。
|
||||||
|
// 唯讀輔助指令:取得 PR head 資訊,在本機以 git 取得工作副本——
|
||||||
|
// 同倉庫分支 → git fetch --quiet origin <ref> && git checkout -B <ref> FETCH_HEAD
|
||||||
|
// (在 --dir 指定的既有 git 工作樹內執行;預設當前目錄);
|
||||||
|
// 跨倉庫 head → git clone --branch <ref> <clone_url> <dir>(--dir 必填,目錄不得已存在)。
|
||||||
|
// teai 不碰認證:clone 走 https 公開網址,私有倉庫時請自備 git 認證(credential helper)。
|
||||||
|
func runPullsCheckout(env *Env, args []string) error {
|
||||||
|
fs := flag.NewFlagSet("teai pulls checkout", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(env.Err)
|
||||||
|
repo := fs.String("repo", "", "倉庫(owner/repo,必填)")
|
||||||
|
dir := fs.String("dir", "", "工作樹目錄(預設當前目錄;跨倉庫 head 時必填且不得已存在)")
|
||||||
|
if err := parseFlags(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
owner, name, err := splitRepoFlag(*repo)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if owner == "" {
|
||||||
|
return &ErrUsage{Msg: "pulls checkout 需要 --repo owner/repo"}
|
||||||
|
}
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return &ErrUsage{Msg: "pulls checkout 需要恰好一個編號"}
|
||||||
|
}
|
||||||
|
num, err := parseNumber(fs.Arg(0))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ops, err := newOpsClient(env)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
info, err := ops.PullHeadInfo(context.Background(), owner, name, num)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if info.Ref == "" {
|
||||||
|
return fmt.Errorf("PR #%d 缺少 head 分支資訊", num)
|
||||||
|
}
|
||||||
|
workDir := *dir
|
||||||
|
if workDir == "" {
|
||||||
|
workDir = "."
|
||||||
|
}
|
||||||
|
// git 指令一律固定參數(不經 shell、不插入使用者字串),分支名僅作為
|
||||||
|
// git 自身剖析的引數傳入;錯誤訊息往 env.Err,成功輸出到 env.Out。
|
||||||
|
// 注意:git clone 的目標目錄是位置參數,cmd.Dir 不可指向不存在目錄,
|
||||||
|
// 故 clone 一律在當前目錄執行(--dir 以絕對路徑傳入)。
|
||||||
|
runGit := func(dir string, args ...string) error {
|
||||||
|
cmd := exec.Command("git", args...)
|
||||||
|
cmd.Dir = dir
|
||||||
|
cmd.Stdout = env.Out
|
||||||
|
cmd.Stderr = env.Err
|
||||||
|
return cmd.Run()
|
||||||
|
}
|
||||||
|
if info.Repo == "" {
|
||||||
|
// 同倉庫:fetch 指定分支並建立/更新本地分支。
|
||||||
|
if err := runGit(workDir, "fetch", "--quiet", "origin", "--", info.Ref); err != nil {
|
||||||
|
return fmt.Errorf("git fetch origin %s 失敗(在 %s):%w", info.Ref, workDir, err)
|
||||||
|
}
|
||||||
|
if err := runGit(workDir, "checkout", "-q", "-B", info.Ref, "FETCH_HEAD"); err != nil {
|
||||||
|
return fmt.Errorf("git checkout -B %s 失敗:%w", info.Ref, err)
|
||||||
|
}
|
||||||
|
return printer(env).PrintOne([]gitea.Field{
|
||||||
|
{Name: "number"}, {Name: "branch"}, {Name: "workdir"},
|
||||||
|
}, gitea.Values{num, info.Ref, workDir})
|
||||||
|
}
|
||||||
|
// 跨倉庫 head:clone 到 --dir(不得已存在)。
|
||||||
|
if *dir == "" {
|
||||||
|
return &ErrUsage{Msg: "pulls checkout:跨倉庫 head(" + info.Repo + ")需要 --dir <目錄>"}
|
||||||
|
}
|
||||||
|
if st, err := os.Stat(*dir); err == nil && st.IsDir() {
|
||||||
|
return &ErrUsage{Msg: "pulls checkout:--dir 已存在(跨倉庫 head 需要新目錄):" + *dir}
|
||||||
|
}
|
||||||
|
if info.CloneURL == "" {
|
||||||
|
return fmt.Errorf("PR #%d 的 head 倉庫 %s 未提供 clone 網址", num, info.Repo)
|
||||||
|
}
|
||||||
|
abs, err := filepath.Abs(*dir)
|
||||||
|
if err != nil {
|
||||||
|
return &ErrUsage{Msg: "pulls checkout:無效的 --dir:" + err.Error()}
|
||||||
|
}
|
||||||
|
if err := runGit(".", "clone", "--quiet", "--branch", info.Ref, "--", info.CloneURL, abs); err != nil {
|
||||||
|
return fmt.Errorf("git clone %s 失敗:%w", info.CloneURL, err)
|
||||||
|
}
|
||||||
|
return printer(env).PrintOne([]gitea.Field{
|
||||||
|
{Name: "number"}, {Name: "branch"}, {Name: "repo"}, {Name: "workdir"},
|
||||||
|
}, gitea.Values{num, info.Ref, info.Repo, *dir})
|
||||||
|
}
|
||||||
|
|
||||||
// ---- labels ----
|
// ---- labels ----
|
||||||
|
|
||||||
// runLabels:teai labels list --repo owner/repo|teai labels create … --yes
|
// runLabels:teai labels list --repo owner/repo|teai labels create … --yes
|
||||||
@@ -891,3 +1098,134 @@ func runAPIDirect(env *Env, args []string) error {
|
|||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- organizations(#45,tea organizations 對等)----
|
||||||
|
|
||||||
|
// orgListFields 是 organizations 清單的欄位定義。
|
||||||
|
func orgListFields() []gitea.Field {
|
||||||
|
return []gitea.Field{
|
||||||
|
{Name: "name"}, {Name: "full_name"}, {Name: "website"},
|
||||||
|
{Name: "location"}, {Name: "description"}, {Name: "visibility"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// runOrganizations:teai organizations [list|create|delete] …。
|
||||||
|
// tea 對等:organizations list 列出自己可存取的組織;create/delete 是
|
||||||
|
// 寫入操作,比照慣例要求 --yes。
|
||||||
|
func runOrganizations(env *Env, args []string) error {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return &ErrUsage{Msg: "organizations 需要子命令:list | create | delete"}
|
||||||
|
}
|
||||||
|
sub, rest := args[0], args[1:]
|
||||||
|
switch sub {
|
||||||
|
case "list":
|
||||||
|
return runOrganizationsList(env, rest)
|
||||||
|
case "create":
|
||||||
|
return runOrganizationsCreate(env, rest)
|
||||||
|
case "delete":
|
||||||
|
return runOrganizationsDelete(env, rest)
|
||||||
|
default:
|
||||||
|
return &ErrUsage{Msg: fmt.Sprintf("organizations 未知子命令 %q(可用:list | create | delete)", sub)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// runOrganizationsList:teai organizations list。
|
||||||
|
// GET /user/orgs(與 teai orgs 工作流命令同一端點,但輸出完整欄位)。
|
||||||
|
func runOrganizationsList(env *Env, args []string) error {
|
||||||
|
fs := flag.NewFlagSet("teai organizations list", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(env.Err)
|
||||||
|
if err := parseFlags(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 0 {
|
||||||
|
return &ErrUsage{Msg: "organizations list 不接受位置參數"}
|
||||||
|
}
|
||||||
|
ops, err := newOpsClient(env)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
orgs, err := ops.ListMyOrganizations(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p := printer(env)
|
||||||
|
rows := make([]gitea.Values, 0, len(orgs))
|
||||||
|
for i := range orgs {
|
||||||
|
org := &orgs[i]
|
||||||
|
rows = append(rows, gitea.Values{
|
||||||
|
org.Account(), org.FullName, org.Website,
|
||||||
|
org.Location, org.Description, org.Visibility,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return p.PrintList(orgListFields(), rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
// runOrganizationsCreate:teai organizations create --name … [--full-name …]
|
||||||
|
// [--description …] [--website …] [--location …] [--visibility public|limited|private] --yes。
|
||||||
|
// tea 以位置參數給組織名;teai 慣例用 --name(語義等價,命名與其他 create 一致)。
|
||||||
|
func runOrganizationsCreate(env *Env, args []string) error {
|
||||||
|
fs := flag.NewFlagSet("teai organizations create", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(env.Err)
|
||||||
|
name := fs.String("name", "", "組織帳號名(必填,同 tea 的位置參數)")
|
||||||
|
fullName := fs.String("full-name", "", "顯示名稱")
|
||||||
|
desc := fs.String("description", "", "說明")
|
||||||
|
website := fs.String("website", "", "網站")
|
||||||
|
location := fs.String("location", "", "所在地")
|
||||||
|
visibility := fs.String("visibility", "", "可見度:public|limited|private(預設服務端決定)")
|
||||||
|
yes := fs.Bool("yes", false, "確認寫入")
|
||||||
|
if err := parseFlags(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(*name) == "" {
|
||||||
|
return &ErrUsage{Msg: "organizations create 需要 --name"}
|
||||||
|
}
|
||||||
|
switch *visibility {
|
||||||
|
case "", "public", "limited", "private":
|
||||||
|
default:
|
||||||
|
return &ErrUsage{Msg: "organizations create 的 --visibility 需為 public|limited|private"}
|
||||||
|
}
|
||||||
|
if err := requireYes(*yes, "organizations create"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ops, err := newOpsClient(env)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
org, err := ops.CreateOrganization(context.Background(), *name, *fullName, *desc, *website, *location, *visibility)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return printer(env).PrintOne(orgListFields(), gitea.Values{
|
||||||
|
org.Account(), org.FullName, org.Website,
|
||||||
|
org.Location, org.Description, org.Visibility,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// runOrganizationsDelete:teai organizations delete <name> --yes。
|
||||||
|
// tea 相容:組織名作為位置參數。
|
||||||
|
func runOrganizationsDelete(env *Env, args []string) error {
|
||||||
|
fs := flag.NewFlagSet("teai organizations delete", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(env.Err)
|
||||||
|
yes := fs.Bool("yes", false, "確認寫入")
|
||||||
|
if err := parseFlags(fs, args); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 1 {
|
||||||
|
return &ErrUsage{Msg: "organizations delete 需要恰好一個組織名"}
|
||||||
|
}
|
||||||
|
orgName := strings.TrimSpace(fs.Arg(0))
|
||||||
|
if orgName == "" {
|
||||||
|
return &ErrUsage{Msg: "organizations delete 需要組織名"}
|
||||||
|
}
|
||||||
|
if err := requireYes(*yes, "organizations delete"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ops, err := newOpsClient(env)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := ops.DeleteOrganization(context.Background(), orgName); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return printer(env).PrintOne([]gitea.Field{{Name: "name"}, {Name: "state"}}, gitea.Values{orgName, "deleted"})
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,289 @@
|
|||||||
|
// dailyops_parity_commands_test.go — #40 的驗收測試:補齊 tea 對等指令
|
||||||
|
// pulls approve/close/checkout、通用 comment、issues list --labels 過濾。
|
||||||
|
// 寫入命令未帶 --yes 不得發出任何請求;帶 --yes 時打對端點與 payload。
|
||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestParityWriteCommandsRequireYes 驗證新增寫入命令未帶 --yes:
|
||||||
|
// 回 2 且不發請求(#40 驗收:寫入閘門慣例)。
|
||||||
|
func TestParityWriteCommandsRequireYes(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
args []string
|
||||||
|
}{
|
||||||
|
{"pulls approve", []string{"pulls", "approve", "--repo", "a/b", "1"}},
|
||||||
|
{"pulls close", []string{"pulls", "close", "--repo", "a/b", "1"}},
|
||||||
|
{"comment direct", []string{"comment", "--repo", "a/b", "1", "內容"}},
|
||||||
|
{"comment direct body flag", []string{"comment", "--repo", "a/b", "--body", "內容", "1"}},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Errorf("%s:未帶 --yes 不得發出請求(%s %s)", tc.name, r.Method, r.URL.Path)
|
||||||
|
})
|
||||||
|
_, stderr, code := run(tc.args...)
|
||||||
|
if code != 2 {
|
||||||
|
t.Errorf("%s 未帶 --yes 應回 2,得到 %d", tc.name, code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr, "--yes") {
|
||||||
|
t.Errorf("%s 錯誤訊息應提及 --yes,得到:%s", tc.name, stderr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPullsApprovePostsReview 驗證 pulls approve --yes:
|
||||||
|
// POST /repos/{owner}/{repo}/pulls/{n}/reviews,payload 帶 event=APPROVED 與意見;
|
||||||
|
// 意見可用位置參數(tea 相容:teai pulls approve --repo a/b <n> "驗證通過。")。
|
||||||
|
func TestPullsApprovePostsReview(t *testing.T) {
|
||||||
|
var gotMethod, gotPath, gotBody string
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotMethod, gotPath = r.Method, r.URL.Path
|
||||||
|
buf := make([]byte, 512)
|
||||||
|
n, _ := r.Body.Read(buf)
|
||||||
|
gotBody = string(buf[:n])
|
||||||
|
fmt.Fprint(w, `{"ID":42,"number":13,"state":"APPROVED","body":"驗證通過。","submitted_at":"t","user":{"login":"max"}}`)
|
||||||
|
})
|
||||||
|
stdout, _, code := run("pulls", "approve", "--repo", "alterminal/teai", "--yes", "13", "驗證通過。")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("approve --yes 應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if gotMethod != "POST" || !strings.HasSuffix(gotPath, "/repos/alterminal/teai/pulls/13/reviews") {
|
||||||
|
t.Errorf("應 POST /repos/alterminal/teai/pulls/13/reviews,得到 %s %s", gotMethod, gotPath)
|
||||||
|
}
|
||||||
|
if !strings.Contains(gotBody, `"event":"APPROVED"`) || !strings.Contains(gotBody, "驗證通過。") {
|
||||||
|
t.Errorf("body 應含 event=APPROVED 與意見,得到:%s", gotBody)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stdout, `"state":"APPROVED"`) {
|
||||||
|
t.Errorf("輸出應含 APPROVED,得到:%s", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPullsClosePatchesState 驗證 pulls close --yes:
|
||||||
|
// PATCH /repos/{owner}/{repo}/pulls/{n},payload 帶 state=closed。
|
||||||
|
func TestPullsClosePatchesState(t *testing.T) {
|
||||||
|
var gotMethod, gotPath, gotBody string
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotMethod, gotPath = r.Method, r.URL.Path
|
||||||
|
buf := make([]byte, 512)
|
||||||
|
n, _ := r.Body.Read(buf)
|
||||||
|
gotBody = string(buf[:n])
|
||||||
|
fmt.Fprint(w, `{"number":13,"title":"PR","state":"closed","html_url":"https://x/13"}`)
|
||||||
|
})
|
||||||
|
_, _, code := run("pulls", "close", "--repo", "alterminal/teai", "--yes", "13")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("close --yes 應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if gotMethod != "PATCH" || !strings.HasSuffix(gotPath, "/repos/alterminal/teai/pulls/13") {
|
||||||
|
t.Errorf("應 PATCH /repos/alterminal/teai/pulls/13,得到 %s %s", gotMethod, gotPath)
|
||||||
|
}
|
||||||
|
if !strings.Contains(gotBody, `"state":"closed"`) {
|
||||||
|
t.Errorf("body 應含 state=closed,得到:%s", gotBody)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCommentDirectPostsComment 驗證通用 comment(tea 相容形式):
|
||||||
|
// --repo a/b <number> <body> --yes → POST issues/<n>/comments,
|
||||||
|
// issue 與 PR 共用(不需要 type 旗標)。
|
||||||
|
func TestCommentDirectPostsComment(t *testing.T) {
|
||||||
|
var gotMethod, gotPath, gotBody string
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotMethod, gotPath = r.Method, r.URL.Path
|
||||||
|
buf := make([]byte, 512)
|
||||||
|
n, _ := r.Body.Read(buf)
|
||||||
|
gotBody = string(buf[:n])
|
||||||
|
fmt.Fprint(w, `{"body":"已依評論更新:commit abc1234。","created_at":"t","user":{"login":"max"}}`)
|
||||||
|
})
|
||||||
|
stdout, _, code := run("comment", "--repo", "alterminal/teai", "--yes", "13", "已依評論更新:commit abc1234。")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("comment --yes 應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if gotMethod != "POST" || !strings.HasSuffix(gotPath, "/repos/alterminal/teai/issues/13/comments") {
|
||||||
|
t.Errorf("應 POST /repos/alterminal/teai/issues/13/comments,得到 %s %s", gotMethod, gotPath)
|
||||||
|
}
|
||||||
|
if !strings.Contains(gotBody, "已依評論更新:commit abc1234。") {
|
||||||
|
t.Errorf("body 應含留言內容,得到:%s", gotBody)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stdout, "已依評論更新") {
|
||||||
|
t.Errorf("輽出應含留言,得到:%s", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestCommentDirectBodyFlag 驗證 comment 也接受 --body(teai 慣用),
|
||||||
|
// 且位置參數與 --body 同時存在時位置參數優先。
|
||||||
|
func TestCommentDirectBodyFlag(t *testing.T) {
|
||||||
|
var gotBody string
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
buf := make([]byte, 512)
|
||||||
|
n, _ := r.Body.Read(buf)
|
||||||
|
gotBody = string(buf[:n])
|
||||||
|
fmt.Fprint(w, `{"body":"x","created_at":"t","user":{"login":"max"}}`)
|
||||||
|
})
|
||||||
|
if _, _, code := run("comment", "--repo", "a/b", "--body", "旗標版", "--yes", "5"); code != 0 {
|
||||||
|
t.Fatalf("--body 版應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(gotBody, "旗標版") {
|
||||||
|
t.Errorf("body 應為 --body 值,得到:%s", gotBody)
|
||||||
|
}
|
||||||
|
if _, _, code := run("comment", "--repo", "a/b", "--body", "旗標版", "--yes", "5", "位置版"); code != 0 {
|
||||||
|
t.Fatalf("位置參數版應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(gotBody, "位置版") || strings.Contains(gotBody, "旗標版") {
|
||||||
|
t.Errorf("位置參數應優先於 --body,得到:%s", gotBody)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIssuesListLabelsFilter 驗證 issues list --labels:
|
||||||
|
// 查詢參數帶 labels=a,b(多標籤 AND 語義),輸出仍為 JSON 陣列。
|
||||||
|
func TestIssuesListLabelsFilter(t *testing.T) {
|
||||||
|
var gotQuery string
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotQuery = r.URL.RawQuery
|
||||||
|
fmt.Fprint(w, `[{"number":9,"title":"标签過濾","state":"open","user":{"login":"ceo"},"updated_at":"t"}]`)
|
||||||
|
})
|
||||||
|
stdout, _, code := run("issues", "list", "--repo", "alterminal/teai", "--labels", "bug, help wanted")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("--labels 應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(gotQuery, "labels=bug%2Chelp+wanted") && !strings.Contains(gotQuery, "labels=bug%2C+help+wanted") {
|
||||||
|
t.Errorf("查詢應帶 labels=bug,help+wanted(URL 編碼後),得到 %q", gotQuery)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stdout, `"number":9`) {
|
||||||
|
t.Errorf("輽出應含過濾後的 issue,得到:%s", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPullsCheckoutSameRepo 驗證 checkout 同倉庫分支:
|
||||||
|
// 在 --dir 的 git 工作樹 fetch origin <ref> 並 checkout -B <ref>。
|
||||||
|
func TestPullsCheckoutSameRepo(t *testing.T) {
|
||||||
|
// 建立裸「origin」倉庫與分支 feat/x。
|
||||||
|
origin := t.TempDir()
|
||||||
|
gitRun := func(args ...string) {
|
||||||
|
t.Helper()
|
||||||
|
cmd := exec.Command("git", args...)
|
||||||
|
cmd.Dir = origin
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("git %v 失敗:%v\n%s", args, err, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gitRun("init", "-q", "-b", "main", ".")
|
||||||
|
gitRun("config", "user.email", "t@t")
|
||||||
|
gitRun("config", "user.name", "t")
|
||||||
|
gitRun("commit", "--allow-empty", "-m", "init")
|
||||||
|
gitRun("checkout", "-q", "-b", "feat/x")
|
||||||
|
gitRun("commit", "--allow-empty", "-m", "x1")
|
||||||
|
gitRun("checkout", "-q", "main")
|
||||||
|
// 工作樹 clone 自 origin(file:// 協定讓 fetch 生效)。
|
||||||
|
work := t.TempDir()
|
||||||
|
if out, err := exec.Command("git", "clone", "-q", "file://"+origin, work).CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("clone 失敗:%v\n%s", err, out)
|
||||||
|
}
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, `{"number":7,"title":"PR","state":"open","head":{"ref":"feat/x","repo":{"full_name":"alterminal/teai","clone_url":"https://gitea.alterminal.com/alterminal/teai.git"}},"base":{"ref":"main"}}`)
|
||||||
|
})
|
||||||
|
stdout, _, code := run("pulls", "checkout", "--repo", "alterminal/teai", "--dir", work, "7")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("checkout 應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
brOut, err := exec.Command("git", "-C", work, "branch", "--show-current").Output()
|
||||||
|
if err != nil || strings.TrimSpace(string(brOut)) != "feat/x" {
|
||||||
|
t.Errorf("工作樹應在 feat/x,得到 %q(err=%v)", string(brOut), err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stdout, `"branch":"feat/x"`) {
|
||||||
|
t.Errorf("輽出應含 branch 欄位,得到:%s", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPullsCheckoutCrossRepo 驗證 checkout 跨倉庫 head:
|
||||||
|
// 需 --dir(新目錄),git clone --branch <ref> <clone_url> <dir>。
|
||||||
|
func TestPullsCheckoutCrossRepo(t *testing.T) {
|
||||||
|
// 假伺服器同時當 git remote:把 PR head 指向本地裸倉庫。
|
||||||
|
origin := t.TempDir()
|
||||||
|
gitRun := func(args ...string) {
|
||||||
|
t.Helper()
|
||||||
|
cmd := exec.Command("git", args...)
|
||||||
|
cmd.Dir = origin
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("git %v 失敗:%v\n%s", args, err, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gitRun("init", "-q", "-b", "main", "--bare", ".")
|
||||||
|
seed := t.TempDir()
|
||||||
|
cmd := exec.Command("git", "clone", "-q", "file://"+origin, seed)
|
||||||
|
if out, err := cmd.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("clone seed 失敗:%v\n%s", err, out)
|
||||||
|
}
|
||||||
|
for _, args := range [][]string{
|
||||||
|
{"config", "user.email", "t@t"},
|
||||||
|
{"config", "user.name", "t"},
|
||||||
|
{"commit", "--allow-empty", "-m", "init"},
|
||||||
|
{"checkout", "-q", "-b", "feat/y"},
|
||||||
|
{"commit", "--allow-empty", "-m", "y1"},
|
||||||
|
{"push", "-q", "origin", "feat/y"},
|
||||||
|
} {
|
||||||
|
c := exec.Command("git", args...)
|
||||||
|
c.Dir = seed
|
||||||
|
if out, err := c.CombinedOutput(); err != nil {
|
||||||
|
t.Fatalf("git %v 失敗:%v\n%s", args, err, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
target := filepath.Join(t.TempDir(), "wk")
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprintf(w, `{"number":8,"title":"PR","state":"open","head":{"ref":"feat/y","repo":{"full_name":"other/fork","clone_url":"file://%s"}},"base":{"ref":"main"}}`, origin)
|
||||||
|
})
|
||||||
|
stdout, _, code := run("pulls", "checkout", "--repo", "alterminal/teai", "--dir", target, "8")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("checkout 跨倉庫應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
brOut, err := exec.Command("git", "-C", target, "branch", "--show-current").Output()
|
||||||
|
if err != nil || strings.TrimSpace(string(brOut)) != "feat/y" {
|
||||||
|
t.Errorf("工作樹應在 feat/y,得到 %q(err=%v)", string(brOut), err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stdout, `"repo":"other/fork"`) {
|
||||||
|
t.Errorf("輽出應含 head 倉庫,得到:%s", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPullsCheckoutCrossRepoRequiresDir 驗證跨倉庫 head 未帶 --dir:
|
||||||
|
// 用法錯誤(exit 2)。
|
||||||
|
func TestPullsCheckoutCrossRepoRequiresDir(t *testing.T) {
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, `{"number":8,"title":"PR","state":"open","head":{"ref":"feat/y","repo":{"full_name":"other/fork","clone_url":"https://x/y.git"}},"base":{"ref":"main"}}`)
|
||||||
|
})
|
||||||
|
_, stderr, code := run("pulls", "checkout", "--repo", "alterminal/teai", "8")
|
||||||
|
if code != 2 {
|
||||||
|
t.Errorf("跨倉庫 head 未帶 --dir 應回 2,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr, "--dir") {
|
||||||
|
t.Errorf("錯誤訊息應提及 --dir,得到:%s", stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIssuesCommentPositionalBody 驗證 issues comment 也吃位置參數留言
|
||||||
|
// (tea comment 相容语法在子命令下的行為)。
|
||||||
|
func TestIssuesCommentPositionalBody(t *testing.T) {
|
||||||
|
var gotBody string
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
buf := make([]byte, 512)
|
||||||
|
n, _ := r.Body.Read(buf)
|
||||||
|
gotBody = string(buf[:n])
|
||||||
|
fmt.Fprint(w, `{"body":"x","created_at":"t","user":{"login":"max"}}`)
|
||||||
|
})
|
||||||
|
if _, _, code := run("issues", "comment", "--repo", "a/b", "--yes", "3", "多餘", "引數", "串留言"); code != 0 {
|
||||||
|
t.Fatalf("issues comment 位置參數應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(gotBody, "多餘 引數 串留言") {
|
||||||
|
t.Errorf("尾端引數應串成留言,得到:%s", gotBody)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ = os.Getenv // 保持 import 一致(checkout 測試用 exec,此檔亦引用 os 於需要時)
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// login.go — teai login 指令:管理 tea 相容的登入組態。
|
// login.go — teai login 指令:管理 teai 自己的登入組態。
|
||||||
//
|
//
|
||||||
// teai 與 tea 共用同一份組態檔(README 設計原則 5),login 的職責是:
|
// 組態由 teai 自行讀寫(README 設計原則 5),不依賴 tea。login 的職責是:
|
||||||
// 以 token 向站點驗證(GET /user),成功後才寫入組態並記下帳號。
|
// 以 token 向站點驗證(GET /user),成功後才寫入組態並記下帳號。
|
||||||
// token 只走記憶體與組態檔,不進輸出、日誌或錯誤訊息。
|
// token 只走記憶體與組態檔,不進輸出、日誌或錯誤訊息。
|
||||||
//
|
//
|
||||||
@@ -25,20 +25,20 @@ import (
|
|||||||
// loginStdin 是讀 token 與確認的輸入(測試可替換)。
|
// loginStdin 是讀 token 與確認的輸入(測試可替換)。
|
||||||
var loginStdin io.Reader = os.Stdin
|
var loginStdin io.Reader = os.Stdin
|
||||||
|
|
||||||
// loginConfigPath 回傳組態檔路徑:--config/TEA_CONFIG 優先,其次
|
// loginConfigPath 回傳組態檔路徑:--config/TEAI_CONFIG 優先,其次
|
||||||
// ~/.config/tea/config.yml。找不到可用路徑回空字串。
|
// ~/.config/teai/config.yml。找不到可用路徑回空字串。
|
||||||
func loginConfigPath(g Globals) string {
|
func loginConfigPath(g Globals) string {
|
||||||
if p := strings.TrimSpace(g.ConfigPath); p != "" {
|
if p := strings.TrimSpace(g.ConfigPath); p != "" {
|
||||||
return expandHome(p)
|
return expandHome(p)
|
||||||
}
|
}
|
||||||
if p := os.Getenv("TEA_CONFIG"); strings.TrimSpace(p) != "" {
|
if p := os.Getenv("TEAI_CONFIG"); strings.TrimSpace(p) != "" {
|
||||||
return expandHome(strings.TrimSpace(p))
|
return expandHome(strings.TrimSpace(p))
|
||||||
}
|
}
|
||||||
home, err := os.UserHomeDir()
|
home, err := os.UserHomeDir()
|
||||||
if err != nil || home == "" {
|
if err != nil || home == "" {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
return filepath.Join(home, ".config", "tea", "config.yml")
|
return filepath.Join(home, ".config", "teai", "config.yml")
|
||||||
}
|
}
|
||||||
|
|
||||||
// expandHome 展開路徑開頭的 ~。
|
// expandHome 展開路徑開頭的 ~。
|
||||||
@@ -178,7 +178,7 @@ func runLoginAdd(env *Env, args []string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := gitea.SaveTeaConfigFile(path, out); err != nil {
|
if err := gitea.SaveConfigFile(path, out); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
p := gitea.Printer{Format: env.Globals.Output, Out: env.Out}
|
p := gitea.Printer{Format: env.Globals.Output, Out: env.Out}
|
||||||
@@ -329,7 +329,7 @@ func saveLoginConfig(env *Env, data []byte) error {
|
|||||||
if path == "" {
|
if path == "" {
|
||||||
return fmt.Errorf("cannot determine config path")
|
return fmt.Errorf("cannot determine config path")
|
||||||
}
|
}
|
||||||
return gitea.SaveTeaConfigFile(path, data)
|
return gitea.SaveConfigFile(path, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// findLoginByHost 在組態內容中找 URL 主機與 siteURL 相同的登入。
|
// findLoginByHost 在組態內容中找 URL 主機與 siteURL 相同的登入。
|
||||||
@@ -352,7 +352,7 @@ func findLogin(data []byte, name string) (gitea.LoginEntry, bool) {
|
|||||||
return gitea.LoginEntry{}, false
|
return gitea.LoginEntry{}, false
|
||||||
}
|
}
|
||||||
|
|
||||||
// defaultLoginName 以 URL 主機作為登入名稱(同 tea 的習慣)。
|
// defaultLoginName 以 URL 主機作為登入名稱。
|
||||||
func defaultLoginName(rawURL string) string {
|
func defaultLoginName(rawURL string) string {
|
||||||
s := rawURL
|
s := rawURL
|
||||||
if !strings.Contains(s, "://") {
|
if !strings.Contains(s, "://") {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ func loginTestEnv(t *testing.T, configContent string) (args []string, configPath
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
t.Setenv("TEA_CONFIG", configPath)
|
t.Setenv("TEAI_CONFIG", configPath)
|
||||||
return []string{"--config", configPath}, configPath
|
return []string{"--config", configPath}, configPath
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,6 +117,13 @@ func TestLoginAddVerifiesThenWrites(t *testing.T) {
|
|||||||
if info.Mode().Perm() != 0o600 {
|
if info.Mode().Perm() != 0o600 {
|
||||||
t.Fatalf("perm = %v", info.Mode().Perm())
|
t.Fatalf("perm = %v", info.Mode().Perm())
|
||||||
}
|
}
|
||||||
|
// 新項目只寫 teai 欄位,不含 tea 的 ssh_*/preferences。
|
||||||
|
s := string(data)
|
||||||
|
for _, ban := range []string{"ssh_", "insecure:", "version_check:", "preferences:"} {
|
||||||
|
if strings.Contains(s, ban) {
|
||||||
|
t.Fatalf("tea field leaked %q:\n%s", ban, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestLoginAddTokenFromStdin(t *testing.T) {
|
func TestLoginAddTokenFromStdin(t *testing.T) {
|
||||||
@@ -187,6 +194,7 @@ preferences:
|
|||||||
if strings.Contains(s, "old-tok") || !strings.Contains(s, "token: new-tok") {
|
if strings.Contains(s, "old-tok") || !strings.Contains(s, "token: new-tok") {
|
||||||
t.Fatalf("token not replaced:\n%s", s)
|
t.Fatalf("token not replaced:\n%s", s)
|
||||||
}
|
}
|
||||||
|
// 未知欄位與其他區段逐字保留(行級編輯,不整檔覆寫)。
|
||||||
if !strings.Contains(s, `ssh_key: "keep-me"`) || !strings.Contains(s, "editor: false") {
|
if !strings.Contains(s, `ssh_key: "keep-me"`) || !strings.Contains(s, "editor: false") {
|
||||||
t.Fatalf("unrelated content lost:\n%s", s)
|
t.Fatalf("unrelated content lost:\n%s", s)
|
||||||
}
|
}
|
||||||
@@ -290,3 +298,26 @@ func TestLoginRegisteredInUsage(t *testing.T) {
|
|||||||
t.Fatalf("usage should list login: %s", stdout)
|
t.Fatalf("usage should list login: %s", stdout)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLoginConfigPathIndependentOfTea(t *testing.T) {
|
||||||
|
t.Setenv("TEA_CONFIG", "/from-tea.yml")
|
||||||
|
t.Setenv("TEAI_CONFIG", "")
|
||||||
|
g := defaultGlobals()
|
||||||
|
got := loginConfigPath(g)
|
||||||
|
if got == "/from-tea.yml" {
|
||||||
|
t.Fatal("TEA_CONFIG must not be used")
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(filepath.ToSlash(got), ".config/teai/config.yml") {
|
||||||
|
t.Fatalf("default path want ~/.config/teai/config.yml, got %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Setenv("TEAI_CONFIG", "/from-teai.yml")
|
||||||
|
if got := loginConfigPath(g); got != "/from-teai.yml" {
|
||||||
|
t.Fatalf("TEAI_CONFIG: got %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
g.ConfigPath = "/explicit.yml"
|
||||||
|
if got := loginConfigPath(g); got != "/explicit.yml" {
|
||||||
|
t.Fatalf("--config: got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,169 @@
|
|||||||
|
// organizations_commands_test.go — #45 的驗收測試:tea organizations 對等指令
|
||||||
|
// list/create/delete。讀取 list 打對端點;寫入 create/delete 未帶 --yes
|
||||||
|
// 不得發出任何請求,帶 --yes 時打對端點與 payload。
|
||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestOrganizationsListGetsUserOrgs 驗證 organizations list:
|
||||||
|
// GET /user/orgs,輸出 name(username 優先)與 full_name 等欄位。
|
||||||
|
func TestOrganizationsListGetsUserOrgs(t *testing.T) {
|
||||||
|
var gotMethod, gotPath string
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotMethod, gotPath = r.Method, r.URL.Path
|
||||||
|
fmt.Fprint(w, `[{"username":"alterminal","name":"alterminal","full_name":"Alterminal Co., Ltd.","website":"","location":"","description":"","visibility":"public"},{"username":"","name":"fallback-org","full_name":"Fallback Org","visibility":"public"}]`)
|
||||||
|
})
|
||||||
|
stdout, _, code := run("organizations", "list")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("organizations list 應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if gotMethod != "GET" || !strings.HasSuffix(gotPath, "/user/orgs") {
|
||||||
|
t.Errorf("應 GET /user/orgs,得到 %s %s", gotMethod, gotPath)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stdout, `"name":"alterminal"`) || !strings.Contains(stdout, `"full_name":"Alterminal Co., Ltd."`) {
|
||||||
|
t.Errorf("輸出應含 name 與 full_name,得到:%s", stdout)
|
||||||
|
}
|
||||||
|
// username 缺漏時回退 name 欄位(同 workflow.Org.Account 取值順序)。
|
||||||
|
if !strings.Contains(stdout, `"name":"fallback-org"`) {
|
||||||
|
t.Errorf("username 缺漏時 name 应回退 name 欄位,得到:%s", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOrganizationsListRejectsPositionalArgs 驗證 list 不接受位置參數(回 2)。
|
||||||
|
func TestOrganizationsListRejectsPositionalArgs(t *testing.T) {
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Errorf("不應發出任何請求")
|
||||||
|
})
|
||||||
|
_, stderr, code := run("organizations", "list", "alterminal")
|
||||||
|
if code != 2 {
|
||||||
|
t.Errorf("list 帶位置參數應回 2,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr, "位置參數") {
|
||||||
|
t.Errorf("錯誤訊息應提及位置參數,得到:%s", stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOrganizationsCreateRequiresYes 驗證 create 未帶 --yes:回 2 且不發請求。
|
||||||
|
func TestOrganizationsCreateRequiresYes(t *testing.T) {
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Errorf("未帶 --yes 不得發出請求(%s %s)", r.Method, r.URL.Path)
|
||||||
|
})
|
||||||
|
_, stderr, code := run("organizations", "create", "--name", "neworg")
|
||||||
|
if code != 2 {
|
||||||
|
t.Errorf("create 未帶 --yes 應回 2,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr, "--yes") {
|
||||||
|
t.Errorf("錯誤訊息應提及 --yes,得到:%s", stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOrganizationsCreateRequiresName 驗證 create 缺 --name:回 2(且在 --yes 閘門之前檢查)。
|
||||||
|
func TestOrganizationsCreateRequiresName(t *testing.T) {
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Errorf("缺 --name 不應發出請求")
|
||||||
|
})
|
||||||
|
_, stderr, code := run("organizations", "create", "--yes")
|
||||||
|
if code != 2 {
|
||||||
|
t.Errorf("create 缺 --name 應回 2,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr, "--name") {
|
||||||
|
t.Errorf("錯誤訊息應提及 --name,得到:%s", stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOrganizationsCreatePostsOrg 驗證 create --yes:
|
||||||
|
// POST /orgs,payload 帶 username 與 full_name;visibility 空時不傳。
|
||||||
|
func TestOrganizationsCreatePostsOrg(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, 1024)
|
||||||
|
n, _ := r.Body.Read(buf)
|
||||||
|
gotBody = string(buf[:n])
|
||||||
|
fmt.Fprint(w, `{"username":"neworg","name":"neworg","full_name":"New Org","website":"https://x","location":"TW","description":"d","visibility":"public"}`)
|
||||||
|
})
|
||||||
|
stdout, _, code := run("organizations", "create", "--yes", "--name", "neworg", "--full-name", "New Org", "--website", "https://x", "--location", "TW", "--description", "d")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("create --yes 應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if gotMethod != "POST" || !strings.HasSuffix(gotPath, "/orgs") {
|
||||||
|
t.Errorf("應 POST /orgs,得到 %s %s", gotMethod, gotPath)
|
||||||
|
}
|
||||||
|
for _, want := range []string{`"username":"neworg"`, `"full_name":"New Org"`, `"website":"https://x"`, `"location":"TW"`, `"description":"d"`} {
|
||||||
|
if !strings.Contains(gotBody, want) {
|
||||||
|
t.Errorf("body 應含 %s,得到:%s", want, gotBody)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(gotBody, "visibility") {
|
||||||
|
t.Errorf("未指定 --visibility 時 body 不應含 visibility,得到:%s", gotBody)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stdout, `"name":"neworg"`) || !strings.Contains(stdout, `"full_name":"New Org"`) {
|
||||||
|
t.Errorf("輸出應含 name 與 full_name,得到:%s", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOrganizationsCreateRejectsBadVisibility 驗證 --visibility 值域檢查(回 2,不發請求)。
|
||||||
|
func TestOrganizationsCreateRejectsBadVisibility(t *testing.T) {
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Errorf("值域檢查失敗不應發出請求")
|
||||||
|
})
|
||||||
|
_, stderr, code := run("organizations", "create", "--yes", "--name", "neworg", "--visibility", "secret")
|
||||||
|
if code != 2 {
|
||||||
|
t.Errorf("--visibility secret 應回 2,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr, "visibility") {
|
||||||
|
t.Errorf("錯誤訊息應提及 visibility,得到:%s", stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOrganizationsDeleteRequiresYes 驗證 delete 未帶 --yes:回 2 且不發請求。
|
||||||
|
func TestOrganizationsDeleteRequiresYes(t *testing.T) {
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Errorf("未帶 --yes 不得發出請求(%s %s)", r.Method, r.URL.Path)
|
||||||
|
})
|
||||||
|
_, stderr, code := run("organizations", "delete", "oldorg")
|
||||||
|
if code != 2 {
|
||||||
|
t.Errorf("delete 未帶 --yes 應回 2,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr, "--yes") {
|
||||||
|
t.Errorf("錯誤訊息應提及 --yes,得到:%s", stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOrganizationsDeleteOrg 驗證 delete --yes:DELETE /orgs/{org}。
|
||||||
|
func TestOrganizationsDeleteOrg(t *testing.T) {
|
||||||
|
var gotMethod, gotPath string
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
gotMethod, gotPath = r.Method, r.URL.Path
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
})
|
||||||
|
stdout, _, code := run("organizations", "delete", "--yes", "oldorg")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("delete --yes 應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if gotMethod != "DELETE" || !strings.HasSuffix(gotPath, "/orgs/oldorg") {
|
||||||
|
t.Errorf("應 DELETE /orgs/oldorg,得到 %s %s", gotMethod, gotPath)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stdout, `"state":"deleted"`) {
|
||||||
|
t.Errorf("輸出應含 state=deleted,得到:%s", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOrganizationsUnknownSubcommand 驗證未知子命令回 2。
|
||||||
|
func TestOrganizationsUnknownSubcommand(t *testing.T) {
|
||||||
|
run := opsTestServer(t, func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
t.Errorf("未知子命令不應發出請求")
|
||||||
|
})
|
||||||
|
_, stderr, code := run("organizations", "rename")
|
||||||
|
if code != 2 {
|
||||||
|
t.Errorf("未知子命令應回 2,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stderr, "organizations") {
|
||||||
|
t.Errorf("錯誤訊息應提及 organizations,得到:%s", stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -46,6 +46,9 @@ func (s *stubStalledSource) TryGetIssue(owner, repo string, number int64) (workf
|
|||||||
i, ok := s.issues[owner+"/"+repo][number]
|
i, ok := s.issues[owner+"/"+repo][number]
|
||||||
return i, ok, nil
|
return i, ok, nil
|
||||||
}
|
}
|
||||||
|
func (s *stubStalledSource) IssueTimeline(owner, repo string, number int64) ([]workflow.TimelineEvent, error) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
func (s *stubStalledSource) GetIssue(owner, repo string, number int64) (workflow.Issue, error) {
|
func (s *stubStalledSource) GetIssue(owner, repo string, number int64) (workflow.Issue, error) {
|
||||||
if s.getErr != nil {
|
if s.getErr != nil {
|
||||||
return workflow.Issue{}, s.getErr
|
return workflow.Issue{}, s.getErr
|
||||||
@@ -114,6 +117,24 @@ func TestWiringStalled(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestWiringStalledEmpty 驗證 stalled 無任何條目時輸出 []、exit 0(#37)。
|
||||||
|
func TestWiringStalledEmpty(t *testing.T) {
|
||||||
|
newStubStalledEnv(t, &stubStalledSource{
|
||||||
|
username: "ceo",
|
||||||
|
orgs: []string{"alterminal"},
|
||||||
|
repos: map[string][]workflow.Repo{"alterminal": {}},
|
||||||
|
issues: map[string]map[int64]workflow.Issue{},
|
||||||
|
comments: map[string][]workflow.Comment{},
|
||||||
|
}, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
|
||||||
|
stdout, _, code := run("stalled")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("stalled 空情境應回 0,得到 %d(stdout=%q)", code, stdout)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(stdout) != "[]" {
|
||||||
|
t.Fatalf("stalled 無條目應輸出 [],得到 %q", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestWiringStalledHoursFlag 驗證 --hours 覆寫門檻與非正數被攔。
|
// TestWiringStalledHoursFlag 驗證 --hours 覆寫門檻與非正數被攔。
|
||||||
func TestWiringStalledHoursFlag(t *testing.T) {
|
func TestWiringStalledHoursFlag(t *testing.T) {
|
||||||
freeze := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
|
freeze := time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC)
|
||||||
@@ -157,7 +178,7 @@ func TestWiringXrefs(t *testing.T) {
|
|||||||
src := newStubStalledData()
|
src := newStubStalledData()
|
||||||
src.issues["alterminal/agents"][1] = workflow.Issue{
|
src.issues["alterminal/agents"][1] = workflow.Issue{
|
||||||
Number: 1, Title: "父項", State: "open",
|
Number: 1, Title: "父項", State: "open",
|
||||||
Body: "子項:agents#2",
|
Body: "子項:agents#2",
|
||||||
Repository: &workflow.Repository{FullName: "alterminal/agents"},
|
Repository: &workflow.Repository{FullName: "alterminal/agents"},
|
||||||
}
|
}
|
||||||
src.issues["alterminal/agents"][2] = workflow.Issue{
|
src.issues["alterminal/agents"][2] = workflow.Issue{
|
||||||
@@ -185,7 +206,7 @@ func TestWiringXrefsEmpty(t *testing.T) {
|
|||||||
src := newStubStalledData()
|
src := newStubStalledData()
|
||||||
src.issues["alterminal/agents"][1] = workflow.Issue{
|
src.issues["alterminal/agents"][1] = workflow.Issue{
|
||||||
Number: 1, Title: "無引用", State: "open",
|
Number: 1, Title: "無引用", State: "open",
|
||||||
Body: "沒有任何引用",
|
Body: "沒有任何引用",
|
||||||
Repository: &workflow.Repository{FullName: "alterminal/agents"},
|
Repository: &workflow.Repository{FullName: "alterminal/agents"},
|
||||||
}
|
}
|
||||||
newStubStalledEnv(t, src, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
|
newStubStalledEnv(t, src, time.Date(2026, 9, 10, 8, 0, 0, 0, time.UTC))
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// version_test.go 驗證版本字串解析:go test 環境 Main.Version 為 "(devel)"
|
||||||
|
// 時應退回開發版本號;tag 與 pseudo-version 行為由建置驗證涵蓋
|
||||||
|
// (go install pkg@tag 顯示 tag;clone 建置顯示 pseudo-version)。
|
||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestBuildVersionFallsBackToDev 確認本地測試環境(Main.Version == "(devel)")
|
||||||
|
// 退回 Version;同時確保輸出是可讀版本字串(非空、無括號)。
|
||||||
|
func TestBuildVersionFallsBackToDev(t *testing.T) {
|
||||||
|
v := buildVersion()
|
||||||
|
if v == "" {
|
||||||
|
t.Fatalf("buildVersion 不應為空")
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(v, "()") {
|
||||||
|
t.Errorf("buildVersion 不應含內部佔位(括號),得到:%q", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRunVersionUsesBuildVersion 確認 version 命令輸出 buildVersion 的結果。
|
||||||
|
func TestRunVersionUsesBuildVersion(t *testing.T) {
|
||||||
|
stdout, _, code := run("version")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("version 應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
want := "teai version " + buildVersion()
|
||||||
|
if !strings.Contains(stdout, want) {
|
||||||
|
t.Errorf("version 輸出應含 %q,得到:%q", want, stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
// workflow_commands.go — gitea.py 工作流命令的 CLI 接線(#6):
|
// workflow_commands.go — gitea.py 工作流命令的 CLI 接線(#6):
|
||||||
// whoami、orgs、members [--has-work]、mine、pulls [--mine|--reviewer] [--repo]、next。
|
// whoami、role、orgs、members [--has-work]、mine、pulls [--mine|--reviewer] [--repo]、next。
|
||||||
//
|
//
|
||||||
// 輸出走 internal/gitea 的 Printer(--output json|table);錯誤經 cli.exitCodeFor
|
// 輸出走 internal/gitea 的 Printer(--output json|table);錯誤經 cli.exitCodeFor
|
||||||
// 映射結束碼(用法 2/API 3)。token 解析選序見 internal/gitea/auth.go。
|
// 映射結束碼(用法 2/API 3)。token 解析選序見 internal/gitea/auth.go。
|
||||||
@@ -20,6 +20,7 @@ func init() {
|
|||||||
commands[c.name] = c
|
commands[c.name] = c
|
||||||
}
|
}
|
||||||
register(&command{name: "whoami", usage: "目前帳號", run: runWhoami})
|
register(&command{name: "whoami", usage: "目前帳號", run: runWhoami})
|
||||||
|
register(&command{name: "role", usage: "目前角色(Supervisor→supervisor,Agents→worker)", run: runRole})
|
||||||
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})
|
||||||
@@ -77,6 +78,29 @@ func runWhoami(env *Env, args []string) error {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runRole:teai role。不在 Supervisor/Agents 團隊時輸出 null(exit 0)。
|
||||||
|
func runRole(env *Env, args []string) error {
|
||||||
|
if len(args) != 0 {
|
||||||
|
return &ErrUsage{Msg: "role 不接受參數"}
|
||||||
|
}
|
||||||
|
s, err := newScannerFunc(env)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
role, err := s.Role()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p := printer(env)
|
||||||
|
if role == "" {
|
||||||
|
return p.PrintNull()
|
||||||
|
}
|
||||||
|
return p.PrintOne(
|
||||||
|
[]gitea.Field{{Name: "role"}},
|
||||||
|
gitea.Values{role},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// runOrgs:teai orgs。
|
// runOrgs:teai orgs。
|
||||||
func runOrgs(env *Env, args []string) error {
|
func runOrgs(env *Env, args []string) error {
|
||||||
if len(args) != 0 {
|
if len(args) != 0 {
|
||||||
|
|||||||
@@ -224,6 +224,71 @@ func TestWiringWhoamiOrgs(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestWiringRoleWorker 驗證 Agents 成員的 role 輸出 worker。
|
||||||
|
func TestWiringRoleWorker(t *testing.T) {
|
||||||
|
newStubEnv(t, newStubData())
|
||||||
|
stdout, _, code := run("role")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("role 應回 0,得到 %d(stdout=%q)", code, stdout)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(stdout) != `{"role":"worker"}` {
|
||||||
|
t.Fatalf("Agents 成員 role 應輸出 worker,得到 %q", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWiringRoleSupervisor 驗證 Supervisor 成員的 role 輸出 supervisor。
|
||||||
|
func TestWiringRoleSupervisor(t *testing.T) {
|
||||||
|
c := newStubData()
|
||||||
|
c.teams["alterminal"] = []workflow.Team{
|
||||||
|
{ID: 1, Name: "Agents"},
|
||||||
|
{ID: 2, Name: "Supervisor"},
|
||||||
|
}
|
||||||
|
c.members[2] = []string{"alex"}
|
||||||
|
newStubEnv(t, c)
|
||||||
|
stdout, _, code := run("role")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("role 應回 0,得到 %d(stdout=%q)", code, stdout)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(stdout) != `{"role":"supervisor"}` {
|
||||||
|
t.Fatalf("Supervisor 成員 role 應輸出 supervisor,得到 %q", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWiringRoleNone 驗證不在任一角色團隊時輸出 null、exit 0。
|
||||||
|
func TestWiringRoleNone(t *testing.T) {
|
||||||
|
c := newStubData()
|
||||||
|
c.currentUser = "outsider"
|
||||||
|
newStubEnv(t, c)
|
||||||
|
stdout, _, code := run("role")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("role 無角色應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(stdout) != "null" {
|
||||||
|
t.Fatalf("role 無角色應輸出 null,得到 %q", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWiringRoleRejectsArgs 驗證 role 不接受參數。
|
||||||
|
func TestWiringRoleRejectsArgs(t *testing.T) {
|
||||||
|
newStubEnv(t, newStubData())
|
||||||
|
_, _, code := run("role", "extra")
|
||||||
|
if code != int(ExitUsage) {
|
||||||
|
t.Fatalf("role extra 應回 ExitUsage(%d),得到 %d", int(ExitUsage), code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWiringRoleTable 驗證 teai role --output table。
|
||||||
|
func TestWiringRoleTable(t *testing.T) {
|
||||||
|
newStubEnv(t, newStubData())
|
||||||
|
stdout, _, code := run("role", "--output", "table")
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("role --output table 應回 0,得到 %d", code)
|
||||||
|
}
|
||||||
|
if !strings.Contains(stdout, "worker") {
|
||||||
|
t.Fatalf("role --output table 應含 worker,得到 %q", stdout)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestWiringVersionRejectsArgs 驗證 version 不接受參數(新剖析語義下仍 exit 2)。
|
// TestWiringVersionRejectsArgs 驗證 version 不接受參數(新剖析語義下仍 exit 2)。
|
||||||
func TestWiringVersionRejectsArgs(t *testing.T) {
|
func TestWiringVersionRejectsArgs(t *testing.T) {
|
||||||
_, _, code := run("version", "--wat")
|
_, _, code := run("version", "--wat")
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"gitea.alterminal.com/alterminal/teai/internal/gitea"
|
"gitea.alterminal.com/alterminal/teai/internal/gitea"
|
||||||
)
|
)
|
||||||
@@ -119,8 +120,10 @@ type Pull struct {
|
|||||||
// pullRef 是 PR 的 head/base 參照。
|
// pullRef 是 PR 的 head/base 參照。
|
||||||
type pullRef struct {
|
type pullRef struct {
|
||||||
Ref string `json:"ref"`
|
Ref string `json:"ref"`
|
||||||
|
SHA string `json:"sha"`
|
||||||
Repo *struct {
|
Repo *struct {
|
||||||
FullName string `json:"full_name"`
|
FullName string `json:"full_name"`
|
||||||
|
CloneURL string `json:"clone_url"`
|
||||||
} `json:"repo"`
|
} `json:"repo"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,8 +168,9 @@ func repoPath(owner, repo string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ListIssues 列出倉庫 issues。state:open|closed|all(預設 open);
|
// ListIssues 列出倉庫 issues。state:open|closed|all(預設 open);
|
||||||
// type=issues 排除 PR(Gitea 的 issues 端點會連 PR 一起回)。
|
// labels 非空時以逗號連接傳給 API 的 labels 參數(Gitea labels 過濾,
|
||||||
func (o *Ops) ListIssues(ctx context.Context, owner, repo, state string) ([]Issue, error) {
|
// 多標籤為 AND 語義);type=issues 排除 PR(Gitea 的 issues 端點會連 PR 一起回)。
|
||||||
|
func (o *Ops) ListIssues(ctx context.Context, owner, repo, state string, labels []string) ([]Issue, error) {
|
||||||
if state == "" {
|
if state == "" {
|
||||||
state = "open"
|
state = "open"
|
||||||
}
|
}
|
||||||
@@ -174,6 +178,9 @@ func (o *Ops) ListIssues(ctx context.Context, owner, repo, state string) ([]Issu
|
|||||||
// open(#33),closed 項目會漏列;all 也不能省略。
|
// open(#33),closed 項目會漏列;all 也不能省略。
|
||||||
extra := url.Values{}
|
extra := url.Values{}
|
||||||
extra.Set("state", state)
|
extra.Set("state", state)
|
||||||
|
if len(labels) > 0 {
|
||||||
|
extra.Set("labels", strings.Join(labels, ","))
|
||||||
|
}
|
||||||
// type=issues:排除 PR(PR 在此端點帶 pull_request 欄位)。
|
// type=issues:排除 PR(PR 在此端點帶 pull_request 欄位)。
|
||||||
extra.Set("type", "issues")
|
extra.Set("type", "issues")
|
||||||
var issues []Issue
|
var issues []Issue
|
||||||
@@ -259,12 +266,93 @@ func (o *Ops) ListPulls(ctx context.Context, owner, repo, state string) ([]Pull,
|
|||||||
|
|
||||||
// GetPull 取得單一 PR。
|
// GetPull 取得單一 PR。
|
||||||
func (o *Ops) GetPull(ctx context.Context, owner, repo string, number int64) (*Pull, error) {
|
func (o *Ops) GetPull(ctx context.Context, owner, repo string, number int64) (*Pull, error) {
|
||||||
var pull Pull
|
var pr Pull
|
||||||
path := repoPath(owner, repo) + "/pulls/" + strconv.FormatInt(number, 10)
|
path := repoPath(owner, repo) + "/pulls/" + strconv.FormatInt(number, 10)
|
||||||
if err := o.Client.GetJSON(ctx, path, &pull); err != nil {
|
if err := o.Client.GetJSON(ctx, path, &pr); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &pull, nil
|
return &pr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Review 是 pull request 審核的精簡欄位。
|
||||||
|
type Review struct {
|
||||||
|
ID int64 `json:"ID"`
|
||||||
|
Number int64 `json:"number"`
|
||||||
|
State string `json:"state"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
Submitted string `json:"submitted_at"`
|
||||||
|
User *User `json:"user"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Author 回傳審核者帳號。
|
||||||
|
func (r *Review) Author() string { return r.User.Name() }
|
||||||
|
|
||||||
|
// ApprovePull 核准 PR(POST /repos/{owner}/{repo}/pulls/{n}/reviews,event=APPROVED)。
|
||||||
|
// body 是審核意見,可為空。
|
||||||
|
func (o *Ops) ApprovePull(ctx context.Context, owner, repo string, number int64, body string) (*Review, error) {
|
||||||
|
payload := map[string]any{
|
||||||
|
"event": "APPROVED",
|
||||||
|
"body": body,
|
||||||
|
}
|
||||||
|
var review Review
|
||||||
|
path := repoPath(owner, repo) + "/pulls/" + strconv.FormatInt(number, 10) + "/reviews"
|
||||||
|
if err := o.Client.DoJSON(ctx, "POST", path, "", payload, &review); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &review, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClosePull 關閉 PR 不合併(PATCH /repos/{owner}/{repo}/pulls/{n},state=closed)。
|
||||||
|
func (o *Ops) ClosePull(ctx context.Context, owner, repo string, number int64) (*Pull, error) {
|
||||||
|
payload := map[string]any{"state": "closed"}
|
||||||
|
var pr Pull
|
||||||
|
path := repoPath(owner, repo) + "/pulls/" + strconv.FormatInt(number, 10)
|
||||||
|
if err := o.Client.DoJSON(ctx, "PATCH", path, "", payload, &pr); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &pr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HeadInfo 是 PR head 參照的完整資訊(checkout 用:同倉庫分支 or 跨倉庫 clone 網址)。
|
||||||
|
type HeadInfo struct {
|
||||||
|
// Ref 是 head 分支名。
|
||||||
|
Ref string
|
||||||
|
// Repo 是 head 所屬倉庫(owner/name);與目標倉庫相同時為空。
|
||||||
|
Repo string
|
||||||
|
// CloneURL 是 head 倉庫的 https clone 網址;同倉庫時為空。
|
||||||
|
CloneURL string
|
||||||
|
// SHA 是 head commit(暫不使用,保留給未來 reset/rebase 用)。
|
||||||
|
SHA string
|
||||||
|
}
|
||||||
|
|
||||||
|
// PullHeadInfo 取得 PR 的 head 資訊。同倉庫分支 → Repo/CloneURL 為空、只剩 Ref;
|
||||||
|
// 跨倉庫 fork → Ref+Repo+CloneURL 齊備,checkout 改以 clone --branch Ref CloneURL。
|
||||||
|
func (o *Ops) PullHeadInfo(ctx context.Context, owner, repo string, number int64) (*HeadInfo, error) {
|
||||||
|
pr, err := o.GetPull(ctx, owner, repo, number)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
info := &HeadInfo{Ref: pr.HeadRef()}
|
||||||
|
if pr.Head != nil {
|
||||||
|
info.SHA = pr.Head.SHA
|
||||||
|
if pr.Head.Repo != nil {
|
||||||
|
full := pr.Head.Repo.FullName
|
||||||
|
same := full != "" && full == owner+"/"+repo
|
||||||
|
if !same {
|
||||||
|
info.Repo = full
|
||||||
|
info.CloneURL = pr.Head.Repo.CloneURL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// String 依 head 來源輸出人類可讀描述(輸出用)。
|
||||||
|
func (h *HeadInfo) String() string {
|
||||||
|
if h.Repo != "" {
|
||||||
|
return h.Repo + "#" + h.Ref
|
||||||
|
}
|
||||||
|
return h.Ref
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreatePull 建立 PR。
|
// CreatePull 建立 PR。
|
||||||
@@ -382,3 +470,64 @@ func (o *Ops) CallAPIDirect(ctx context.Context, method, path, rawQuery string,
|
|||||||
}
|
}
|
||||||
return o.Client.DoRaw(ctx, method, path, rawQuery, data)
|
return o.Client.DoRaw(ctx, method, path, rawQuery, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- organizations(#45,tea organizations 對等)----
|
||||||
|
|
||||||
|
// Organization 是帳號所屬/可存取組織的精簡欄位
|
||||||
|
// (GET /user/orgs、POST /orgs 回應共用)。name 是帳號名、
|
||||||
|
// full_name 是顯示名稱(如 "Alterminal Co., Ltd."),兩者不同。
|
||||||
|
type Organization struct {
|
||||||
|
UserName string `json:"username"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
FullName string `json:"full_name"`
|
||||||
|
Website string `json:"website"`
|
||||||
|
Location string `json:"location"`
|
||||||
|
Description string `json:"description"`
|
||||||
|
Visibility string `json:"visibility"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Account 回傳組織帳號名:先 username,缺漏時回退 name
|
||||||
|
// (同 workflow.Org.Account 的取值順序)。
|
||||||
|
func (o *Organization) Account() string {
|
||||||
|
if o.UserName != "" {
|
||||||
|
return o.UserName
|
||||||
|
}
|
||||||
|
return o.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListMyOrganizations 列出自己可存取的組織(GET /user/orgs,分頁)。
|
||||||
|
// tea organizations list 的對等端點;teai orgs(工作流)輸出帳號清單,
|
||||||
|
// 本指令輸出完整欄位供日常操作使用。
|
||||||
|
func (o *Ops) ListMyOrganizations(ctx context.Context) ([]Organization, error) {
|
||||||
|
var orgs []Organization
|
||||||
|
if err := o.Client.ListAll(ctx, "/user/orgs", gitea.ListOptions{}, &orgs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return orgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateOrganization 建立組織(POST /orgs)。name 必填;其餘欄位可空。
|
||||||
|
// visibility:public|limited|private(空值交由服務端預設)。
|
||||||
|
func (o *Ops) CreateOrganization(ctx context.Context, name, fullName, description, website, location, visibility string) (*Organization, error) {
|
||||||
|
payload := map[string]any{
|
||||||
|
"username": name,
|
||||||
|
"full_name": fullName,
|
||||||
|
"description": description,
|
||||||
|
"website": website,
|
||||||
|
"location": location,
|
||||||
|
}
|
||||||
|
if visibility != "" {
|
||||||
|
payload["visibility"] = visibility
|
||||||
|
}
|
||||||
|
var org Organization
|
||||||
|
if err := o.Client.DoJSON(ctx, "POST", "/orgs", "", payload, &org); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &org, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteOrganization 刪除組織(DELETE /orgs/{org})。
|
||||||
|
func (o *Ops) DeleteOrganization(ctx context.Context, org string) error {
|
||||||
|
path := "/orgs/" + url.PathEscape(org)
|
||||||
|
return o.Client.DoJSON(ctx, "DELETE", path, "", nil, nil)
|
||||||
|
}
|
||||||
|
|||||||
+28
-29
@@ -1,7 +1,7 @@
|
|||||||
// auth.go — 認證來源的解析與選序。
|
// auth.go — 認證來源的解析與選序。
|
||||||
//
|
//
|
||||||
// 選序(README「全域介面」):--token 旗標 → TEAI_TOKEN 環境變數 →
|
// 選序(README「全域介面」):--token 旗標 → TEAI_TOKEN 環境變數 →
|
||||||
// tea 登入組態(TEA_CONFIG 指定的路徑,或 ~/.config/tea/config.yml)。
|
// teai 登入組態(TEAI_CONFIG 指定的路徑,或 ~/.config/teai/config.yml)。
|
||||||
// token 一律只在記憶體傳遞,不寫入輸出、日誌或錯誤訊息。
|
// token 一律只在記憶體傳遞,不寫入輸出、日誌或錯誤訊息。
|
||||||
package gitea
|
package gitea
|
||||||
|
|
||||||
@@ -23,8 +23,8 @@ const (
|
|||||||
SourceFlag
|
SourceFlag
|
||||||
// SourceEnv 是 TEAI_TOKEN 環境變數。
|
// SourceEnv 是 TEAI_TOKEN 環境變數。
|
||||||
SourceEnv
|
SourceEnv
|
||||||
// SourceTeaConfig 是 tea 登入組態。
|
// SourceConfig 是 teai 登入組態。
|
||||||
SourceTeaConfig
|
SourceConfig
|
||||||
)
|
)
|
||||||
|
|
||||||
// String 回傳來源名稱(診斷用)。
|
// String 回傳來源名稱(診斷用)。
|
||||||
@@ -34,8 +34,8 @@ func (s TokenSource) String() string {
|
|||||||
return "flag"
|
return "flag"
|
||||||
case SourceEnv:
|
case SourceEnv:
|
||||||
return "env"
|
return "env"
|
||||||
case SourceTeaConfig:
|
case SourceConfig:
|
||||||
return "tea-config"
|
return "config"
|
||||||
default:
|
default:
|
||||||
return "none"
|
return "none"
|
||||||
}
|
}
|
||||||
@@ -62,12 +62,12 @@ func osReadFile(path string) ([]byte, error) {
|
|||||||
type AuthOptions struct {
|
type AuthOptions struct {
|
||||||
// FlagToken 是 --token 旗標值;空字串表示未提供。
|
// FlagToken 是 --token 旗標值;空字串表示未提供。
|
||||||
FlagToken string
|
FlagToken string
|
||||||
// SiteURL 是目標站點(用來比對 tea 組態中的 login url)。
|
// SiteURL 是目標站點(用來比對組態中的 login url)。
|
||||||
SiteURL string
|
SiteURL string
|
||||||
// Env 是環境變數查詢;nil 時用 os.LookupEnv。
|
// Env 是環境變數查詢;nil 時用 os.LookupEnv。
|
||||||
Env EnvLookup
|
Env EnvLookup
|
||||||
// ConfigPath 是 tea 組態的明確路徑(TEA_CONFIG 或 --config)。
|
// ConfigPath 是 teai 組態的明確路徑(TEAI_CONFIG 或 --config)。
|
||||||
// 空字串表示用預設 ~/.config/tea/config.yml。
|
// 空字串表示用預設 ~/.config/teai/config.yml。
|
||||||
ConfigPath string
|
ConfigPath string
|
||||||
// Home 是使用者家目錄(展開 ~ 用);空字串表示不展開。
|
// Home 是使用者家目錄(展開 ~ 用);空字串表示不展開。
|
||||||
Home string
|
Home string
|
||||||
@@ -75,7 +75,7 @@ type AuthOptions struct {
|
|||||||
ReadFile ReadFileFunc
|
ReadFile ReadFileFunc
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveToken 依選序解析 token:flag → env(TEAI_TOKEN) → tea 組態。
|
// ResolveToken 依選序解析 token:flag → env(TEAI_TOKEN) → teai 組態。
|
||||||
//
|
//
|
||||||
// 找不到任何 token 時回傳 ("", SourceNone, nil)——查詢公開端點不需要
|
// 找不到任何 token 時回傳 ("", SourceNone, nil)——查詢公開端點不需要
|
||||||
// token,是否為錯由呼叫端依情境決定。組態檔存在但解析失敗(格式錯誤)
|
// token,是否為錯由呼叫端依情境決定。組態檔存在但解析失敗(格式錯誤)
|
||||||
@@ -93,8 +93,8 @@ func ResolveToken(opts AuthOptions) (string, TokenSource, error) {
|
|||||||
}
|
}
|
||||||
path := opts.ConfigPath
|
path := opts.ConfigPath
|
||||||
if path == "" {
|
if path == "" {
|
||||||
// --config 未給時,先看 TEA_CONFIG 環境變數。
|
// --config 未給時,先看 TEAI_CONFIG 環境變數。
|
||||||
if p, ok := env("TEA_CONFIG"); ok && strings.TrimSpace(p) != "" {
|
if p, ok := env("TEAI_CONFIG"); ok && strings.TrimSpace(p) != "" {
|
||||||
path = strings.TrimSpace(p)
|
path = strings.TrimSpace(p)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -110,7 +110,7 @@ func ResolveToken(opts AuthOptions) (string, TokenSource, error) {
|
|||||||
if home == "" {
|
if home == "" {
|
||||||
return "", SourceNone, nil
|
return "", SourceNone, nil
|
||||||
}
|
}
|
||||||
path = filepath.Join(home, ".config", "tea", "config.yml")
|
path = filepath.Join(home, ".config", "teai", "config.yml")
|
||||||
}
|
}
|
||||||
if path == "" {
|
if path == "" {
|
||||||
return "", SourceNone, nil
|
return "", SourceNone, nil
|
||||||
@@ -124,33 +124,32 @@ func ResolveToken(opts AuthOptions) (string, TokenSource, error) {
|
|||||||
// 組態不存在或讀不到:視為沒有這個來源,不是錯誤。
|
// 組態不存在或讀不到:視為沒有這個來源,不是錯誤。
|
||||||
return "", SourceNone, nil
|
return "", SourceNone, nil
|
||||||
}
|
}
|
||||||
login, err := parseTeaConfig(data, opts.SiteURL)
|
login, err := parseConfig(data, opts.SiteURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", SourceNone, fmt.Errorf("gitea: parse tea config %s: %w", path, err)
|
return "", SourceNone, fmt.Errorf("gitea: parse config %s: %w", path, err)
|
||||||
}
|
}
|
||||||
if login.Token == "" {
|
if login.Token == "" {
|
||||||
return "", SourceNone, nil
|
return "", SourceNone, nil
|
||||||
}
|
}
|
||||||
return login.Token, SourceTeaConfig, nil
|
return login.Token, SourceConfig, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// teaLogin 是 tea 組態中一筆登入資料(只取 teai 需要的欄位)。
|
// configLogin 是組態中一筆登入資料(只取解析 token 需要的欄位)。
|
||||||
type teaLogin struct {
|
type configLogin struct {
|
||||||
Name string
|
Name string
|
||||||
URL string
|
URL string
|
||||||
Token string
|
Token string
|
||||||
Default bool
|
Default bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseTeaConfig 從 tea 的 config.yml 內容挑出最匹配 siteURL 的登入:
|
// parseConfig 從 teai 的 config.yml 內容挑出最匹配 siteURL 的登入:
|
||||||
// url 主機相同者優先,其中 default: true 最優,否則取第一筆;
|
// url 主機相同者優先,其中 default: true 最優,否則取第一筆;
|
||||||
// 都不相同時退而取 default: true,再退第一筆。
|
// 都不相同時退而取 default: true,再退第一筆。
|
||||||
//
|
//
|
||||||
// 僅解析 tea 實際寫出的 YAML 子集:頂層 `logins:` 清單,項目為
|
// 僅解析 teai 寫出的 YAML 子集:頂層 `logins:` 清單,項目為
|
||||||
// `key: value` 的平面映射。不處理錨點、多文件、巢狀清單——tea 不會寫出
|
// `key: value` 的平面映射。不處理錨點、多文件、巢狀清單。
|
||||||
// 這些,遇到也不該默默誤讀。
|
func parseConfig(data []byte, siteURL string) (configLogin, error) {
|
||||||
func parseTeaConfig(data []byte, siteURL string) (teaLogin, error) {
|
var logins []configLogin
|
||||||
var logins []teaLogin
|
|
||||||
inLogins := false
|
inLogins := false
|
||||||
cur := -1 // 目前項目在 logins 的索引;-1 表示尚未開始任何項目
|
cur := -1 // 目前項目在 logins 的索引;-1 表示尚未開始任何項目
|
||||||
for lineNo, raw := range strings.Split(string(data), "\n") {
|
for lineNo, raw := range strings.Split(string(data), "\n") {
|
||||||
@@ -171,26 +170,26 @@ func parseTeaConfig(data []byte, siteURL string) (teaLogin, error) {
|
|||||||
}
|
}
|
||||||
if strings.HasPrefix(trimmed, "- ") || trimmed == "-" {
|
if strings.HasPrefix(trimmed, "- ") || trimmed == "-" {
|
||||||
// 新的清單項目;`- name: x` 形式同行帶鍵值。
|
// 新的清單項目;`- name: x` 形式同行帶鍵值。
|
||||||
logins = append(logins, teaLogin{})
|
logins = append(logins, configLogin{})
|
||||||
cur = len(logins) - 1
|
cur = len(logins) - 1
|
||||||
rest := strings.TrimSpace(strings.TrimPrefix(trimmed, "-"))
|
rest := strings.TrimSpace(strings.TrimPrefix(trimmed, "-"))
|
||||||
if rest != "" {
|
if rest != "" {
|
||||||
if err := applyLoginField(&logins[cur], rest, lineNo+1); err != nil {
|
if err := applyLoginField(&logins[cur], rest, lineNo+1); err != nil {
|
||||||
return teaLogin{}, err
|
return configLogin{}, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if cur < 0 {
|
if cur < 0 {
|
||||||
// logins: 底下卻不是清單項目——不是預期的結構。
|
// logins: 底下卻不是清單項目——不是預期的結構。
|
||||||
return teaLogin{}, fmt.Errorf("line %d: expected list item under logins:", lineNo+1)
|
return configLogin{}, fmt.Errorf("line %d: expected list item under logins:", lineNo+1)
|
||||||
}
|
}
|
||||||
if err := applyLoginField(&logins[cur], trimmed, lineNo+1); err != nil {
|
if err := applyLoginField(&logins[cur], trimmed, lineNo+1); err != nil {
|
||||||
return teaLogin{}, err
|
return configLogin{}, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if len(logins) == 0 {
|
if len(logins) == 0 {
|
||||||
return teaLogin{}, nil
|
return configLogin{}, nil
|
||||||
}
|
}
|
||||||
wantHost := hostOf(siteURL)
|
wantHost := hostOf(siteURL)
|
||||||
// 第一輪:主機相符者,default 優先,否則第一筆。
|
// 第一輪:主機相符者,default 優先,否則第一筆。
|
||||||
@@ -219,7 +218,7 @@ func parseTeaConfig(data []byte, siteURL string) (teaLogin, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// applyLoginField 把 `key: value` 套用到 login;value 的引號會剝除。
|
// applyLoginField 把 `key: value` 套用到 login;value 的引號會剝除。
|
||||||
func applyLoginField(l *teaLogin, kv string, lineNo int) error {
|
func applyLoginField(l *configLogin, kv string, lineNo int) error {
|
||||||
key, value, ok := strings.Cut(kv, ":")
|
key, value, ok := strings.Cut(kv, ":")
|
||||||
if !ok {
|
if !ok {
|
||||||
return fmt.Errorf("line %d: expected key: value, got %q", lineNo, kv)
|
return fmt.Errorf("line %d: expected key: value, got %q", lineNo, kv)
|
||||||
|
|||||||
+41
-23
@@ -1,5 +1,5 @@
|
|||||||
// auth_test.go 驗證認證來源選序(--token → TEAI_TOKEN → tea 組態)
|
// auth_test.go 驗證認證來源選序(--token → TEAI_TOKEN → teai 組態)
|
||||||
// 與 tea 組態解析。
|
// 與組態解析。
|
||||||
package gitea
|
package gitea
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -25,7 +25,7 @@ func fakeReadFile(m map[string]string) ReadFileFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const sampleTeaConfig = `logins:
|
const sampleConfig = `logins:
|
||||||
- name: other.example.com
|
- name: other.example.com
|
||||||
url: https://other.example.com
|
url: https://other.example.com
|
||||||
token: other-token
|
token: other-token
|
||||||
@@ -43,7 +43,7 @@ func TestResolveTokenOrdering(t *testing.T) {
|
|||||||
SiteURL: "https://gitea.alterminal.com",
|
SiteURL: "https://gitea.alterminal.com",
|
||||||
Env: fakeEnv(nil),
|
Env: fakeEnv(nil),
|
||||||
ReadFile: fakeReadFile(map[string]string{
|
ReadFile: fakeReadFile(map[string]string{
|
||||||
"/cfg/config.yml": sampleTeaConfig,
|
"/cfg/config.yml": sampleConfig,
|
||||||
}),
|
}),
|
||||||
ConfigPath: "/cfg/config.yml",
|
ConfigPath: "/cfg/config.yml",
|
||||||
}
|
}
|
||||||
@@ -67,11 +67,11 @@ func TestResolveTokenOrdering(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("tea config used when flag and env absent", func(t *testing.T) {
|
t.Run("config used when flag and env absent", func(t *testing.T) {
|
||||||
opts := base
|
opts := base
|
||||||
tok, src, err := ResolveToken(opts)
|
tok, src, err := ResolveToken(opts)
|
||||||
if err != nil || tok != "site-token" || src != SourceTeaConfig {
|
if err != nil || tok != "site-token" || src != SourceConfig {
|
||||||
t.Fatalf("want site-token/tea-config, got %q/%v (err %v)", tok, src, err)
|
t.Fatalf("want site-token/config, got %q/%v (err %v)", tok, src, err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -88,8 +88,8 @@ func TestResolveTokenOrdering(t *testing.T) {
|
|||||||
opts := base
|
opts := base
|
||||||
opts.Env = fakeEnv(map[string]string{"TEAI_TOKEN": " "})
|
opts.Env = fakeEnv(map[string]string{"TEAI_TOKEN": " "})
|
||||||
tok, src, err := ResolveToken(opts)
|
tok, src, err := ResolveToken(opts)
|
||||||
if err != nil || tok != "site-token" || src != SourceTeaConfig {
|
if err != nil || tok != "site-token" || src != SourceConfig {
|
||||||
t.Fatalf("want site-token/tea-config, got %q/%v (err %v)", tok, src, err)
|
t.Fatalf("want site-token/config, got %q/%v (err %v)", tok, src, err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -103,36 +103,54 @@ func TestResolveTokenOrdering(t *testing.T) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("TEA_CONFIG points config path", func(t *testing.T) {
|
t.Run("TEAI_CONFIG points config path", func(t *testing.T) {
|
||||||
opts := base
|
opts := base
|
||||||
opts.ConfigPath = "" // 不用 --config,改用 TEA_CONFIG
|
opts.ConfigPath = "" // 不用 --config,改用 TEAI_CONFIG
|
||||||
opts.Env = fakeEnv(map[string]string{
|
opts.Env = fakeEnv(map[string]string{
|
||||||
"TEA_CONFIG": "/cfg/config.yml",
|
"TEAI_CONFIG": "/cfg/config.yml",
|
||||||
})
|
})
|
||||||
tok, src, err := ResolveToken(opts)
|
tok, src, err := ResolveToken(opts)
|
||||||
if err != nil || tok != "site-token" || src != SourceTeaConfig {
|
if err != nil || tok != "site-token" || src != SourceConfig {
|
||||||
t.Fatalf("want site-token/tea-config via TEA_CONFIG, got %q/%v (err %v)", tok, src, err)
|
t.Fatalf("want site-token/config via TEAI_CONFIG, got %q/%v (err %v)", tok, src, err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("explicit --config beats TEA_CONFIG", func(t *testing.T) {
|
t.Run("explicit --config beats TEAI_CONFIG", func(t *testing.T) {
|
||||||
opts := base // ConfigPath = /cfg/config.yml(有 site-token)
|
opts := base // ConfigPath = /cfg/config.yml(有 site-token)
|
||||||
opts.Env = fakeEnv(map[string]string{
|
opts.Env = fakeEnv(map[string]string{
|
||||||
"TEA_CONFIG": "/cfg/other.yml",
|
"TEAI_CONFIG": "/cfg/other.yml",
|
||||||
})
|
})
|
||||||
read := fakeReadFile(map[string]string{
|
read := fakeReadFile(map[string]string{
|
||||||
"/cfg/config.yml": sampleTeaConfig,
|
"/cfg/config.yml": sampleConfig,
|
||||||
"/cfg/other.yml": "logins:\n - name: x\n url: https://gitea.alterminal.com\n token: other\n default: true\n",
|
"/cfg/other.yml": "logins:\n - name: x\n url: https://gitea.alterminal.com\n token: other\n default: true\n",
|
||||||
})
|
})
|
||||||
opts.ReadFile = read
|
opts.ReadFile = read
|
||||||
tok, src, err := ResolveToken(opts)
|
tok, src, err := ResolveToken(opts)
|
||||||
if err != nil || tok != "site-token" || src != SourceTeaConfig {
|
if err != nil || tok != "site-token" || src != SourceConfig {
|
||||||
t.Fatalf("want site-token from explicit config, got %q/%v (err %v)", tok, src, err)
|
t.Fatalf("want site-token from explicit config, got %q/%v (err %v)", tok, src, err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("TEA_CONFIG is ignored", func(t *testing.T) {
|
||||||
|
opts := AuthOptions{
|
||||||
|
SiteURL: "https://gitea.alterminal.com",
|
||||||
|
Env: fakeEnv(map[string]string{
|
||||||
|
"TEA_CONFIG": "/cfg/config.yml",
|
||||||
|
}),
|
||||||
|
ReadFile: fakeReadFile(map[string]string{
|
||||||
|
"/cfg/config.yml": sampleConfig,
|
||||||
|
"/home/.config/teai/config.yml": "logins:\n - name: x\n url: https://gitea.alterminal.com\n token: teai-token\n default: true\n",
|
||||||
|
}),
|
||||||
|
Home: "/home",
|
||||||
|
}
|
||||||
|
tok, src, err := ResolveToken(opts)
|
||||||
|
if err != nil || tok != "teai-token" || src != SourceConfig {
|
||||||
|
t.Fatalf("want teai-token from teai config, got %q/%v (err %v)", tok, src, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestParseTeaConfigPicksMatchingLogin(t *testing.T) {
|
func TestParseConfigPicksMatchingLogin(t *testing.T) {
|
||||||
t.Run("host match preferred over default", func(t *testing.T) {
|
t.Run("host match preferred over default", func(t *testing.T) {
|
||||||
cfg := `logins:
|
cfg := `logins:
|
||||||
- name: other
|
- name: other
|
||||||
@@ -144,7 +162,7 @@ func TestParseTeaConfigPicksMatchingLogin(t *testing.T) {
|
|||||||
token: right-token
|
token: right-token
|
||||||
default: false
|
default: false
|
||||||
`
|
`
|
||||||
login, err := parseTeaConfig([]byte(cfg), "https://gitea.alterminal.com")
|
login, err := parseConfig([]byte(cfg), "https://gitea.alterminal.com")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("parse error: %v", err)
|
t.Fatalf("parse error: %v", err)
|
||||||
}
|
}
|
||||||
@@ -155,7 +173,7 @@ func TestParseTeaConfigPicksMatchingLogin(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("quoted token unquoted", func(t *testing.T) {
|
t.Run("quoted token unquoted", func(t *testing.T) {
|
||||||
cfg := "logins:\n - name: t\n url: https://gitea.alterminal.com\n token: \"quoted-token\"\n default: true\n"
|
cfg := "logins:\n - name: t\n url: https://gitea.alterminal.com\n token: \"quoted-token\"\n default: true\n"
|
||||||
login, err := parseTeaConfig([]byte(cfg), "https://gitea.alterminal.com")
|
login, err := parseConfig([]byte(cfg), "https://gitea.alterminal.com")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("parse error: %v", err)
|
t.Fatalf("parse error: %v", err)
|
||||||
}
|
}
|
||||||
@@ -166,14 +184,14 @@ func TestParseTeaConfigPicksMatchingLogin(t *testing.T) {
|
|||||||
|
|
||||||
t.Run("malformed login entry errors", func(t *testing.T) {
|
t.Run("malformed login entry errors", func(t *testing.T) {
|
||||||
cfg := "logins:\n - name: t\n url: https://gitea.alterminal.com\n oops\n"
|
cfg := "logins:\n - name: t\n url: https://gitea.alterminal.com\n oops\n"
|
||||||
if _, err := parseTeaConfig([]byte(cfg), ""); err == nil {
|
if _, err := parseConfig([]byte(cfg), ""); err == nil {
|
||||||
t.Fatal("malformed line should error")
|
t.Fatal("malformed line should error")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("no logins yields empty", func(t *testing.T) {
|
t.Run("no logins yields empty", func(t *testing.T) {
|
||||||
cfg := "preferences:\n editor: false\n"
|
cfg := "preferences:\n editor: false\n"
|
||||||
login, err := parseTeaConfig([]byte(cfg), "")
|
login, err := parseConfig([]byte(cfg), "")
|
||||||
if err != nil || login.Token != "" {
|
if err != nil || login.Token != "" {
|
||||||
t.Fatalf("want empty login, got %+v (err %v)", login, err)
|
t.Fatalf("want empty login, got %+v (err %v)", login, err)
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-20
@@ -1,9 +1,8 @@
|
|||||||
// config.go — tea 相容登入組態的讀取與行級編輯。
|
// config.go — teai 登入組態的讀取與行級編輯。
|
||||||
//
|
//
|
||||||
// teai 與 tea 共用同一份組態檔(README 設計原則 5),因此寫入採「行級編輯」:
|
// 組態由 teai 自行管理(README 設計原則 5),不依賴 tea。寫入採「行級編輯」:
|
||||||
// 只修改目標登入項目的所屬行,其餘內容(未知欄位、註解、preferences 區段、
|
// 只修改目標登入項目的所屬行,其餘內容(未知欄位、註解、空行與縮排)逐字
|
||||||
// 空行與縮排)逐字保留,避免改壞 tea 也在使用的檔案。新增項目依 tea 實際
|
// 保留。新增項目只寫 teai 使用的欄位:name/url/token/default/user。
|
||||||
// 寫出的欄位順序輸出,讓檔案外觀與 tea 一致。
|
|
||||||
//
|
//
|
||||||
// token 值只會進出這個套件的資料結構與組態檔本身,永遠不出現在錯誤訊息。
|
// token 值只會進出這個套件的資料結構與組態檔本身,永遠不出現在錯誤訊息。
|
||||||
package gitea
|
package gitea
|
||||||
@@ -18,7 +17,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// LoginEntry 是組態檔中的一筆登入資料(編輯用,含 tea 的 user 欄位)。
|
// LoginEntry 是組態檔中的一筆登入資料(編輯用,含 user 欄位)。
|
||||||
type LoginEntry struct {
|
type LoginEntry struct {
|
||||||
Name string
|
Name string
|
||||||
URL string
|
URL string
|
||||||
@@ -43,7 +42,7 @@ type configDoc struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// parseConfigDoc 掃描組態內容,定位 logins 清單與各項目的行範圍。
|
// parseConfigDoc 掃描組態內容,定位 logins 清單與各項目的行範圍。
|
||||||
// 只認識 tea 實際寫出的格式:頂層 `logins:` 加縮排的 `- key: value` 項目;
|
// 只認識 teai 寫出的格式:頂層 `logins:` 加縮排的 `- key: value` 項目;
|
||||||
// 其餘行原樣保留在 lines 中。
|
// 其餘行原樣保留在 lines 中。
|
||||||
func parseConfigDoc(data []byte) configDoc {
|
func parseConfigDoc(data []byte) configDoc {
|
||||||
doc := configDoc{lines: splitLines(data), loginsHeader: -1, itemIndent: " "}
|
doc := configDoc{lines: splitLines(data), loginsHeader: -1, itemIndent: " "}
|
||||||
@@ -103,7 +102,7 @@ func (d configDoc) findItem(name string) int {
|
|||||||
return -1
|
return -1
|
||||||
}
|
}
|
||||||
|
|
||||||
// fieldIndent 回傳項目內屬性行的縮排(項目縮排 + 兩格,tea 的格式)。
|
// fieldIndent 回傳項目內屬性行的縮排(項目縮排 + 兩格)。
|
||||||
func (d configDoc) fieldIndent() string {
|
func (d configDoc) fieldIndent() string {
|
||||||
return d.itemIndent + " "
|
return d.itemIndent + " "
|
||||||
}
|
}
|
||||||
@@ -168,7 +167,7 @@ func ListLoginsFile(path string) ([]LoginEntry, error) {
|
|||||||
// UpsertLogin 新增或更新名為 e.Name 的登入。
|
// UpsertLogin 新增或更新名為 e.Name 的登入。
|
||||||
//
|
//
|
||||||
// 已存在則就地更新 url/token/user/default(保留其他欄位與行);不存在則
|
// 已存在則就地更新 url/token/user/default(保留其他欄位與行);不存在則
|
||||||
// 依 tea 的欄位順序插入新項目。makeDefault 為 true 時將其設為預設並取消
|
// 依 teai 的欄位順序插入新項目。makeDefault 為 true 時將其設為預設並取消
|
||||||
// 其他登入的預設旗標;新增後若成為唯一登入也自動成為預設。
|
// 其他登入的預設旗標;新增後若成為唯一登入也自動成為預設。
|
||||||
// 回傳新內容與最終生效的項目值。
|
// 回傳新內容與最終生效的項目值。
|
||||||
func UpsertLogin(data []byte, e LoginEntry, makeDefault bool) ([]byte, LoginEntry, error) {
|
func UpsertLogin(data []byte, e LoginEntry, makeDefault bool) ([]byte, LoginEntry, error) {
|
||||||
@@ -326,7 +325,7 @@ func setFieldInItem(lines []string, it loginItemSpan, key, value, fieldIndent st
|
|||||||
return append(out, lines[it.end:]...)
|
return append(out, lines[it.end:]...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// newLoginBlock 產生 tea 格式的新登入項目(欄位順序與 tea 實際寫出的一致)。
|
// newLoginBlock 產生 teai 格式的新登入項目(name/url/token/default/user)。
|
||||||
func newLoginBlock(itemIndent, name, url, token string, isDefault bool, user string) []string {
|
func newLoginBlock(itemIndent, name, url, token string, isDefault bool, user string) []string {
|
||||||
f := itemIndent + " "
|
f := itemIndent + " "
|
||||||
return []string{
|
return []string{
|
||||||
@@ -334,15 +333,7 @@ func newLoginBlock(itemIndent, name, url, token string, isDefault bool, user str
|
|||||||
f + "url: " + yamlScalar(url),
|
f + "url: " + yamlScalar(url),
|
||||||
f + "token: " + yamlScalar(token),
|
f + "token: " + yamlScalar(token),
|
||||||
f + "default: " + strconv.FormatBool(isDefault),
|
f + "default: " + strconv.FormatBool(isDefault),
|
||||||
f + `ssh_host: ""`,
|
|
||||||
f + `ssh_key: ""`,
|
|
||||||
f + "insecure: false",
|
|
||||||
f + `ssh_certificate_principal: ""`,
|
|
||||||
f + "ssh_agent: false",
|
|
||||||
f + `ssh_key_agent_pub: ""`,
|
|
||||||
f + "version_check: false",
|
|
||||||
f + "user: " + yamlScalar(user),
|
f + "user: " + yamlScalar(user),
|
||||||
f + "created: 0",
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -385,9 +376,9 @@ func joinLines(lines []string) []byte {
|
|||||||
return []byte(s)
|
return []byte(s)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SaveTeaConfigFile 把組態內容原子寫入 path:先寫同目錄暫存檔(0600),
|
// SaveConfigFile 把組態內容原子寫入 path:先寫同目錄暫存檔(0600),
|
||||||
// 再 rename 取代,避免半寫入狀態。必要時建立上層目錄(0700)。
|
// 再 rename 取代,避免半寫入狀態。必要時建立上層目錄(0700)。
|
||||||
func SaveTeaConfigFile(path string, data []byte) error {
|
func SaveConfigFile(path string, data []byte) error {
|
||||||
dir := filepath.Dir(path)
|
dir := filepath.Dir(path)
|
||||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
return fmt.Errorf("gitea: create config dir: %w", err)
|
return fmt.Errorf("gitea: create config dir: %w", err)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// config_test.go 驗證 tea 相容組態的行級編輯:新增、更新、設預設、
|
// config_test.go 驗證登入組態的行級編輯:新增、更新、設預設、
|
||||||
// 移除,以及「未知欄位與其他區段逐字保留」的關鍵性質。
|
// 移除,以及「未知欄位與其他區段逐字保留」的關鍵性質。
|
||||||
package gitea
|
package gitea
|
||||||
|
|
||||||
@@ -10,8 +10,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
// realWorldTeaConfig 是 tea 實際寫出的組態(含 ssh_* 等未知欄位與 preferences)。
|
// extraFieldsConfig 含未知欄位與額外區段,用來驗證行級編輯不會改壞不相干內容。
|
||||||
const realWorldTeaConfig = `logins:
|
const extraFieldsConfig = `logins:
|
||||||
- name: alterminal
|
- name: alterminal
|
||||||
url: https://gitea.alterminal.com
|
url: https://gitea.alterminal.com
|
||||||
token: tok-1
|
token: tok-1
|
||||||
@@ -32,7 +32,7 @@ preferences:
|
|||||||
`
|
`
|
||||||
|
|
||||||
func TestListLoginsParsesAllEntries(t *testing.T) {
|
func TestListLoginsParsesAllEntries(t *testing.T) {
|
||||||
logins := ListLogins([]byte(realWorldTeaConfig))
|
logins := ListLogins([]byte(extraFieldsConfig))
|
||||||
if len(logins) != 1 {
|
if len(logins) != 1 {
|
||||||
t.Fatalf("want 1 login, got %d", len(logins))
|
t.Fatalf("want 1 login, got %d", len(logins))
|
||||||
}
|
}
|
||||||
@@ -43,7 +43,7 @@ func TestListLoginsParsesAllEntries(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestUpsertLoginUpdatesExistingPreservesRest(t *testing.T) {
|
func TestUpsertLoginUpdatesExistingPreservesRest(t *testing.T) {
|
||||||
out, final, err := UpsertLogin([]byte(realWorldTeaConfig), LoginEntry{
|
out, final, err := UpsertLogin([]byte(extraFieldsConfig), LoginEntry{
|
||||||
Name: "alterminal", URL: "https://gitea.alterminal.com", Token: "tok-2", User: "ceo",
|
Name: "alterminal", URL: "https://gitea.alterminal.com", Token: "tok-2", User: "ceo",
|
||||||
}, false)
|
}, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -74,7 +74,7 @@ func TestUpsertLoginUpdatesExistingPreservesRest(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestUpsertLoginAppendsNewAndMakesDefault(t *testing.T) {
|
func TestUpsertLoginAppendsNewAndMakesDefault(t *testing.T) {
|
||||||
out, final, err := UpsertLogin([]byte(realWorldTeaConfig), LoginEntry{
|
out, final, err := UpsertLogin([]byte(extraFieldsConfig), LoginEntry{
|
||||||
Name: "second", URL: "https://git.example.com", Token: "tok-b", User: "bob",
|
Name: "second", URL: "https://git.example.com", Token: "tok-b", User: "bob",
|
||||||
}, true)
|
}, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -93,10 +93,15 @@ func TestUpsertLoginAppendsNewAndMakesDefault(t *testing.T) {
|
|||||||
if !final.Default {
|
if !final.Default {
|
||||||
t.Fatalf("final should be default: %+v", final)
|
t.Fatalf("final should be default: %+v", final)
|
||||||
}
|
}
|
||||||
// tea 的欄位順序仍在。
|
// 新項目依 teai 欄位順序附加。
|
||||||
s := string(out)
|
s := string(out)
|
||||||
if !strings.Contains(s, " - name: second\n") {
|
if !strings.Contains(s, " - name: second\n") {
|
||||||
t.Fatalf("new item not appended in tea style:\n%s", s)
|
t.Fatalf("new item not appended:\n%s", s)
|
||||||
|
}
|
||||||
|
for _, ban := range []string{"ssh_", "insecure:", "version_check:", "created:"} {
|
||||||
|
if strings.Contains(s[strings.Index(s, "- name: second"):], ban) {
|
||||||
|
t.Fatalf("new item leaked tea field %q:\n%s", ban, s)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,6 +122,12 @@ func TestUpsertLoginFirstEverLoginCreatesSection(t *testing.T) {
|
|||||||
if !strings.HasPrefix(string(out), "logins:\n") {
|
if !strings.HasPrefix(string(out), "logins:\n") {
|
||||||
t.Fatalf("section not created:\n%s", out)
|
t.Fatalf("section not created:\n%s", out)
|
||||||
}
|
}
|
||||||
|
s := string(out)
|
||||||
|
for _, ban := range []string{"ssh_", "insecure:", "version_check:", "created:", "preferences:"} {
|
||||||
|
if strings.Contains(s, ban) {
|
||||||
|
t.Fatalf("new config leaked tea field %q:\n%s", ban, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestUpsertLoginRejectsBadInput(t *testing.T) {
|
func TestUpsertLoginRejectsBadInput(t *testing.T) {
|
||||||
@@ -158,7 +169,7 @@ func TestSetDefaultLoginSwitchesFlag(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestSetDefaultLoginUnknownNameErrors(t *testing.T) {
|
func TestSetDefaultLoginUnknownNameErrors(t *testing.T) {
|
||||||
if _, err := SetDefaultLogin([]byte(realWorldTeaConfig), "nope"); err == nil {
|
if _, err := SetDefaultLogin([]byte(extraFieldsConfig), "nope"); err == nil {
|
||||||
t.Fatal("unknown name should error")
|
t.Fatal("unknown name should error")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -195,7 +206,7 @@ preferences:
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestRemoveLoginLastOne(t *testing.T) {
|
func TestRemoveLoginLastOne(t *testing.T) {
|
||||||
out, promoted, err := RemoveLogin([]byte(realWorldTeaConfig), "alterminal")
|
out, promoted, err := RemoveLogin([]byte(extraFieldsConfig), "alterminal")
|
||||||
if err != nil || promoted != "" {
|
if err != nil || promoted != "" {
|
||||||
t.Fatalf("want clean removal, promoted=%q err=%v", promoted, err)
|
t.Fatalf("want clean removal, promoted=%q err=%v", promoted, err)
|
||||||
}
|
}
|
||||||
@@ -207,10 +218,10 @@ func TestRemoveLoginLastOne(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSaveTeaConfigFileAtomicAndMode(t *testing.T) {
|
func TestSaveConfigFileAtomicAndMode(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
path := filepath.Join(dir, "tea", "config.yml")
|
path := filepath.Join(dir, "teai", "config.yml")
|
||||||
if err := SaveTeaConfigFile(path, []byte("logins: []\n")); err != nil {
|
if err := SaveConfigFile(path, []byte("logins: []\n")); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
info, err := os.Stat(path)
|
info, err := os.Stat(path)
|
||||||
@@ -221,7 +232,7 @@ func TestSaveTeaConfigFileAtomicAndMode(t *testing.T) {
|
|||||||
t.Fatalf("perm = %v, want 0600", info.Mode().Perm())
|
t.Fatalf("perm = %v, want 0600", info.Mode().Perm())
|
||||||
}
|
}
|
||||||
// 再寫一次(覆蓋既有檔),不留暫存殘檔。
|
// 再寫一次(覆蓋既有檔),不留暫存殘檔。
|
||||||
if err := SaveTeaConfigFile(path, []byte("logins: []\n# v2\n")); err != nil {
|
if err := SaveConfigFile(path, []byte("logins: []\n# v2\n")); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
entries, _ := os.ReadDir(filepath.Dir(path))
|
entries, _ := os.ReadDir(filepath.Dir(path))
|
||||||
|
|||||||
@@ -150,6 +150,19 @@ func (a *APIClient) TryGetIssue(owner, repo string, number int64) (Issue, bool,
|
|||||||
return issue, true, nil
|
return issue, true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IssueTimeline 回傳 issue 的 timeline 事件(Source 面向;對應 gitea.py
|
||||||
|
// _direct_last_activity 拉取的 repos/{o}/{r}/issues/{n}/timeline)。
|
||||||
|
// 分頁由 ListAll 處理(與 gitea.py api_get_list 的 limit=50 逐頁一致)。
|
||||||
|
func (a *APIClient) IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error) {
|
||||||
|
var events []TimelineEvent
|
||||||
|
path := "/repos/" + url.PathEscape(owner) + "/" + url.PathEscape(repo) +
|
||||||
|
"/issues/" + strconv.FormatInt(number, 10) + "/timeline"
|
||||||
|
if err := a.Client.ListAll(context.Background(), path, gitea.ListOptions{}, &events); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return events, nil
|
||||||
|
}
|
||||||
|
|
||||||
// MyOrganizations 委派 ListOrgs(Source 面向)。
|
// MyOrganizations 委派 ListOrgs(Source 面向)。
|
||||||
func (a *APIClient) MyOrganizations() ([]string, error) { return a.ListOrgs() }
|
func (a *APIClient) MyOrganizations() ([]string, error) { return a.ListOrgs() }
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
package workflow
|
package workflow
|
||||||
|
|
||||||
import "sort"
|
import (
|
||||||
|
"regexp"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
// sortComments 依 created_at 字典序穩定排序(ISO8601 字串字典序與時間序一致),
|
// sortComments 依 created_at 字典序穩定排序(ISO8601 字串字典序與時間序一致),
|
||||||
// 對應 gitea.py 各處的 comments.sort(key=created_at)。
|
// 對應 gitea.py 各處的 comments.sort(key=created_at)。
|
||||||
@@ -135,3 +139,65 @@ func LastCommentNotByAssignee(issue *Issue, comments []Comment) bool {
|
|||||||
func IssueNeedsWork(issue *Issue, comments []Comment, members []string) bool {
|
func IssueNeedsWork(issue *Issue, comments []Comment, members []string) bool {
|
||||||
return AssigneeOverlaps(issue, members) && LastCommentNotByAssignee(issue, comments)
|
return AssigneeOverlaps(issue, members) && LastCommentNotByAssignee(issue, comments)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── 交付報告判定(agents #47,同步 gitea.py _is_delivery_report)──────────
|
||||||
|
//
|
||||||
|
// 最後一則 assignee 留言已把工作交棒給發起人/他人確認(逐項查核/驗收
|
||||||
|
// 結果+回報他件或請確認關閉)時,停滯點不在 assignee:stalled 分類由
|
||||||
|
// assignee-idle 改判 waiting-outside,管理者巡邏不再對已交付、待確認的
|
||||||
|
// 處理者觸發自動催促。
|
||||||
|
|
||||||
|
var (
|
||||||
|
// deliveryVerdictRe 對應 gitea.py _DELIVERY_VERDICT_RE:彙總 verdict 語。
|
||||||
|
deliveryVerdictRe = regexp.MustCompile(`(全數|全部|\d+\s*項)通過|項全過|不通過|未通過`)
|
||||||
|
// deliveryHandoffRe 對應 gitea.py _DELIVERY_HANDOFF_RE:交棒訊號。
|
||||||
|
deliveryHandoffRe = regexp.MustCompile(`回報\s*#\d+|關閉\s*#\d+|請[^\n。]{0,40}(確認|關閉)|可由[^\n。]{0,40}關閉|待[^\n。]{0,20}確認`)
|
||||||
|
// completionDefinitionRe 對應 _has_completion_definition:內文「完成定義」
|
||||||
|
// 段落(ATX 標題或行首字樣)。
|
||||||
|
completionDefinitionRe = regexp.MustCompile(`(?m)^#{1,6}\s*完成定義|^完成定義\s*[::]?`)
|
||||||
|
// simpleDeliveryRe 內文有「完成定義」時的簡式交付語。
|
||||||
|
simpleDeliveryRe = regexp.MustCompile(`已完成|已交付|已通過|已全數`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// hasCompletionDefinition 內文是否含「完成定義」段落。
|
||||||
|
func hasCompletionDefinition(body string) bool {
|
||||||
|
return completionDefinitionRe.MatchString(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsDeliveryReport 判定最後一則 assignee 留言是否符合交付報告特徵
|
||||||
|
// (agents #47;gitea.py _is_delivery_report 的同語義實作)。
|
||||||
|
//
|
||||||
|
// 交付報告=「結構訊號」∧「交棒訊號」同時命中:
|
||||||
|
// - 結構訊號:逐項查核/驗收/測試結果、結論、或彙總 verdict 語;內文有
|
||||||
|
// 「完成定義」段落時,簡式交付語(已完成/已交付)也算。
|
||||||
|
// - 交棒訊號:回報/關閉他件(#N)、或請/可由/待他人確認關閉。
|
||||||
|
//
|
||||||
|
// 只命中結構訊號不算:認領/進度/預告式留言(「完成後逐項回報結果至此」)
|
||||||
|
// 沒有交棒對象,仍是 assignee 自己該做——保持 assignee-idle,修正不製造
|
||||||
|
// 「認領後棄置永不被催促」的新死角。
|
||||||
|
func IsDeliveryReport(issueBody string, last *Comment) bool {
|
||||||
|
if last == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
body := last.Body
|
||||||
|
if body == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
structural := false
|
||||||
|
for _, marker := range []string{"查核結果", "驗收結果", "測試結果", "逐項", "結論", "完成定義"} {
|
||||||
|
if strings.Contains(body, marker) {
|
||||||
|
structural = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !structural && deliveryVerdictRe.MatchString(body) {
|
||||||
|
structural = true
|
||||||
|
}
|
||||||
|
if !structural && hasCompletionDefinition(issueBody) && simpleDeliveryRe.MatchString(body) {
|
||||||
|
structural = true
|
||||||
|
}
|
||||||
|
if !structural {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return deliveryHandoffRe.MatchString(body)
|
||||||
|
}
|
||||||
|
|||||||
@@ -143,3 +143,39 @@ func TestFullNameFallbacks(t *testing.T) {
|
|||||||
t.Errorf("全缺 → 空,得到 %q", got)
|
t.Errorf("全缺 → 空,得到 %q", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestIsDeliveryReport(agents #47):交付報告=結構訊號 ∧ 交棒訊號。
|
||||||
|
// 案例與 gitea.py _is_delivery_report 的離線驗證同集(bear#52 實例)。
|
||||||
|
func TestIsDeliveryReport(t *testing.T) {
|
||||||
|
body52 := "## 完成定義\n- 逐項回報查核結果至此 issue;\n- 全數通過 → 回報 #39 並由 #39 assignee 關閉"
|
||||||
|
claim := "認領。我來執行四項驗收查核,完成後逐項回報結果至此。"
|
||||||
|
report := "## 全階段驗收查核結果(#52)\n**結論:四項全數通過。** 逐項如下…\n四項全過,符合「完成定義」。回報 #39:全數驗收通過,可由 @ceo 關閉 #39 與里程碑。"
|
||||||
|
reportFail := "## 查核結果\n結論:第 2 項不通過。已開立修復 issue #60,請 @ceo 確認分配。"
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
issueBody string
|
||||||
|
comment string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"交付報告+回報#39+@ceo 關閉", body52, report, true},
|
||||||
|
{"失敗型交付(開修復 issue+請確認)", body52, reportFail, true},
|
||||||
|
{"認領留言(逐項+回報 但無交棒)", body52, claim, false},
|
||||||
|
{"純進度留言", body52, "進行中,已看完 P1,預計今晚交付。", false},
|
||||||
|
{"已完成但無交棒", body52, "已完成,程式碼都在分支上。", false},
|
||||||
|
{"無完成定義內文+逐項交棒", "一般 issue 內文", "逐項測試結果全數通過,請 @ceo 確認後關閉。", true},
|
||||||
|
{"無完成定義+僅交棒(無結構)", "一般 issue 內文", "請 @ceo 確認後關閉。", false},
|
||||||
|
{"空留言", body52, "", false},
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
var last *Comment
|
||||||
|
if tc.comment != "" {
|
||||||
|
last = &Comment{Body: tc.comment}
|
||||||
|
}
|
||||||
|
if got := IsDeliveryReport(tc.issueBody, last); got != tc.want {
|
||||||
|
t.Errorf("%s:IsDeliveryReport = %v,want %v", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if IsDeliveryReport(body52, nil) {
|
||||||
|
t.Error("nil 最後留言應為 false")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -9,8 +9,17 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AgentsTeamName 是工作流團隊的名稱(AGENTS.md:調度成員由 Agents 團隊決定)。
|
const (
|
||||||
const AgentsTeamName = "Agents"
|
// AgentsTeamName 是工作流團隊的名稱(AGENTS.md:調度成員由 Agents 團隊決定)。
|
||||||
|
AgentsTeamName = "Agents"
|
||||||
|
// SupervisorTeamName 是管理者團隊的名稱;成員角色為 supervisor。
|
||||||
|
SupervisorTeamName = "Supervisor"
|
||||||
|
|
||||||
|
// RoleSupervisor 是 Supervisor 團隊成員的角色值。
|
||||||
|
RoleSupervisor = "supervisor"
|
||||||
|
// RoleWorker 是 Agents 團隊成員的角色值。
|
||||||
|
RoleWorker = "worker"
|
||||||
|
)
|
||||||
|
|
||||||
// Client 抽象 teai 需要的 Gitea API 讀取操作(僅唯讀)。
|
// Client 抽象 teai 需要的 Gitea API 讀取操作(僅唯讀)。
|
||||||
// #5 的 internal/gitea HTTP 用戶端實作此介面;workflow 不依賴 HTTP 細節。
|
// #5 的 internal/gitea HTTP 用戶端實作此介面;workflow 不依賴 HTTP 細節。
|
||||||
@@ -49,7 +58,7 @@ type PullItem struct {
|
|||||||
Pull PullRequest
|
Pull PullRequest
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scanner 在 Client 之上組合出各命令的資料(whoami/orgs/members/mine/pulls/next)。
|
// Scanner 在 Client 之上組合出各命令的資料(whoami/role/orgs/members/mine/pulls/next)。
|
||||||
type Scanner struct {
|
type Scanner struct {
|
||||||
Client Client
|
Client Client
|
||||||
}
|
}
|
||||||
@@ -59,6 +68,63 @@ func (s *Scanner) Whoami() (string, error) {
|
|||||||
return s.Client.CurrentUser()
|
return s.Client.CurrentUser()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Role 依目前帳號所屬團隊回傳角色:Supervisor 團隊為 supervisor,
|
||||||
|
// Agents 團隊為 worker。同時屬於兩者時以 supervisor 為準。
|
||||||
|
// 兩者都不屬於時回空字串(CLI 輸出 null)。
|
||||||
|
func (s *Scanner) Role() (string, error) {
|
||||||
|
username, err := s.Whoami()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
orgs, err := s.Orgs()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
inAgents := false
|
||||||
|
for _, org := range orgs {
|
||||||
|
teams, err := s.Client.ListTeams(org)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
for _, team := range teams {
|
||||||
|
switch team.Name {
|
||||||
|
case SupervisorTeamName, AgentsTeamName:
|
||||||
|
default:
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ok, err := s.usernameInTeam(team.ID, username)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if team.Name == SupervisorTeamName {
|
||||||
|
return RoleSupervisor, nil
|
||||||
|
}
|
||||||
|
inAgents = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if inAgents {
|
||||||
|
return RoleWorker, nil
|
||||||
|
}
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// usernameInTeam 檢查帳號是否為該團隊成員。
|
||||||
|
func (s *Scanner) usernameInTeam(teamID int64, username string) (bool, error) {
|
||||||
|
members, err := s.Client.ListTeamMembers(teamID)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
for _, m := range members {
|
||||||
|
if m == username {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Orgs 回傳目前帳號所屬的組織(去重、排序)。
|
// Orgs 回傳目前帳號所屬的組織(去重、排序)。
|
||||||
func (s *Scanner) Orgs() ([]string, error) {
|
func (s *Scanner) Orgs() ([]string, error) {
|
||||||
names, err := s.Client.ListOrgs()
|
names, err := s.Client.ListOrgs()
|
||||||
@@ -136,7 +202,11 @@ func (s *Scanner) Members(hasWork bool) ([]string, error) {
|
|||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// iterOrgRepos 產出 (org, repoName);空倉庫跳過(沒有內容可掃)。
|
// iterOrgRepos 產出 (org, repoName)。空倉庫(empty)**不**跳過:Gitea 允許
|
||||||
|
// 空倉庫持有 open issue(如「初始化項目」型工作),gitea.py 的
|
||||||
|
// for_all_repositories(list_my_followup_issues/for_all_organizations)
|
||||||
|
// 掃 issue 時不檢查 empty;只有 PR 掃描(iterOpenPulls)、stalled 與
|
||||||
|
// milestone overview 才跳過空倉庫。
|
||||||
func (s *Scanner) iterOrgRepos() ([][2]string, error) {
|
func (s *Scanner) iterOrgRepos() ([][2]string, error) {
|
||||||
orgs, err := s.Orgs()
|
orgs, err := s.Orgs()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -149,7 +219,7 @@ func (s *Scanner) iterOrgRepos() ([][2]string, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
for _, repo := range repos {
|
for _, repo := range repos {
|
||||||
if repo.Name == "" || repo.Empty {
|
if repo.Name == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
out = append(out, [2]string{org, repo.Name})
|
out = append(out, [2]string{org, repo.Name})
|
||||||
|
|||||||
@@ -164,6 +164,51 @@ func TestNextLayerFallbackToIssue(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestNextPicksIssueInEmptyRepo 回歸測試(#43):空倉庫(empty=true)中
|
||||||
|
// 分派給目前帳號的 open issue 應被第三層拾取——gitea.py 的
|
||||||
|
// for_all_repositories 掃 issue 不跳過空倉庫(「初始化項目」型工作)。
|
||||||
|
func TestNextPicksIssueInEmptyRepo(t *testing.T) {
|
||||||
|
s, fc := newTestScanner()
|
||||||
|
fc.repos["alterminal"] = []Repo{
|
||||||
|
{Name: "teai"},
|
||||||
|
{Name: "colony-tick-demo", Empty: true},
|
||||||
|
}
|
||||||
|
fc.issues["alterminal/colony-tick-demo"] = []Issue{
|
||||||
|
{
|
||||||
|
Number: 1, Title: "初始化項目", UpdatedAt: "2026-09-08T00:00:00Z",
|
||||||
|
Assignees: []User{*mkUser("alex")},
|
||||||
|
Repository: &Repository{FullName: "alterminal/colony-tick-demo"},
|
||||||
|
HTMLURL: "https://gitea.alterminal.com/alterminal/colony-tick-demo/issues/1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
work, err := s.Next()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if work == nil || work.Type != "issue" || work.Number != 1 || work.Repo != "alterminal/colony-tick-demo" {
|
||||||
|
t.Errorf("應拾取空倉庫中的 issue #1,得到 %+v", work)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMineIncludesEmptyRepoIssues 回歸測試(#43):mine 同樣不因倉庫為空而漏列。
|
||||||
|
func TestMineIncludesEmptyRepoIssues(t *testing.T) {
|
||||||
|
s, fc := newTestScanner()
|
||||||
|
fc.repos["alterminal"] = []Repo{
|
||||||
|
{Name: "teai"},
|
||||||
|
{Name: "colony-tick-demo", Empty: true},
|
||||||
|
}
|
||||||
|
fc.issues["alterminal/colony-tick-demo"] = []Issue{
|
||||||
|
{Number: 1, Title: "初始化項目", UpdatedAt: "2026-09-08T00:00:00Z", Assignees: []User{*mkUser("alex")}},
|
||||||
|
}
|
||||||
|
issues, err := s.Mine()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(issues) != 1 || issues[0].Num() != 1 {
|
||||||
|
t.Errorf("mine 應列出空倉庫中的 issue #1,得到 %d 件", len(issues))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestNextNone(t *testing.T) {
|
func TestNextNone(t *testing.T) {
|
||||||
s, _ := newTestScanner()
|
s, _ := newTestScanner()
|
||||||
work, err := s.Next()
|
work, err := s.Next()
|
||||||
@@ -243,6 +288,91 @@ func TestErrorPropagation(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRoleWorker(t *testing.T) {
|
||||||
|
s, _ := newTestScanner()
|
||||||
|
got, err := s.Role()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got != RoleWorker {
|
||||||
|
t.Errorf("Agents 團隊成員應為 worker,得到 %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRoleSupervisor(t *testing.T) {
|
||||||
|
s, fc := newTestScanner()
|
||||||
|
fc.teams["alterminal"] = []Team{
|
||||||
|
{ID: 1, Name: "Agents"},
|
||||||
|
{ID: 2, Name: "Supervisor"},
|
||||||
|
}
|
||||||
|
fc.teamMembers[2] = []string{"alex"}
|
||||||
|
got, err := s.Role()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got != RoleSupervisor {
|
||||||
|
t.Errorf("Supervisor 團隊成員應為 supervisor,得到 %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRoleSupervisorTakesPrecedence(t *testing.T) {
|
||||||
|
s, fc := newTestScanner()
|
||||||
|
// alex 同時在 Agents(newTestScanner 預設)與 Supervisor。
|
||||||
|
fc.teams["alterminal"] = []Team{
|
||||||
|
{ID: 1, Name: "Agents"},
|
||||||
|
{ID: 2, Name: "Supervisor"},
|
||||||
|
}
|
||||||
|
fc.teamMembers[2] = []string{"alex", "ceo"}
|
||||||
|
got, err := s.Role()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got != RoleSupervisor {
|
||||||
|
t.Errorf("同時屬於兩者時應為 supervisor,得到 %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRoleNone(t *testing.T) {
|
||||||
|
s, fc := newTestScanner()
|
||||||
|
fc.currentUser = "outsider"
|
||||||
|
got, err := s.Role()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got != "" {
|
||||||
|
t.Errorf("不在 Supervisor/Agents 應回空字串,得到 %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRoleWorkerWhenSupervisorExists(t *testing.T) {
|
||||||
|
s, fc := newTestScanner()
|
||||||
|
fc.teams["alterminal"] = []Team{
|
||||||
|
{ID: 1, Name: "Agents"},
|
||||||
|
{ID: 2, Name: "Supervisor"},
|
||||||
|
}
|
||||||
|
fc.teamMembers[2] = []string{"ceo"}
|
||||||
|
got, err := s.Role()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got != RoleWorker {
|
||||||
|
t.Errorf("只在 Agents、不在 Supervisor 應為 worker,得到 %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRoleErrorPropagation(t *testing.T) {
|
||||||
|
s, fc := newTestScanner()
|
||||||
|
fc.failOn["teams"] = errors.New("boom")
|
||||||
|
if _, err := s.Role(); err == nil {
|
||||||
|
t.Errorf("ListTeams 錯誤應向上傳播")
|
||||||
|
}
|
||||||
|
delete(fc.failOn, "teams")
|
||||||
|
fc.failOn["members"] = errors.New("boom")
|
||||||
|
if _, err := s.Role(); err == nil {
|
||||||
|
t.Errorf("ListTeamMembers 錯誤應向上傳播")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestPullsDefault(t *testing.T) {
|
func TestPullsDefault(t *testing.T) {
|
||||||
s, fc := newTestScanner()
|
s, fc := newTestScanner()
|
||||||
fc.pulls["alterminal/teai"] = []PullRequest{
|
fc.pulls["alterminal/teai"] = []PullRequest{
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
// stalled_entry_test.go — RunStalled/ResolveIssueXrefs 高階入口的單元測試
|
// stalled_entry_test.go — RunStalled/ResolveIssueXrefs 高階入口的單元測試
|
||||||
//(#7 CLI 接線;資料源注入假實作,離線可測)。
|
// (#7 CLI 接線;資料源注入假實作,離線可測)。
|
||||||
package workflow
|
package workflow
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -14,10 +16,22 @@ type fakeStalledSource struct {
|
|||||||
username string
|
username string
|
||||||
// getIssueErr 模擬 GetIssue 失敗(xrefs 的 404 路徑)。
|
// getIssueErr 模擬 GetIssue 失敗(xrefs 的 404 路徑)。
|
||||||
getIssueErr error
|
getIssueErr error
|
||||||
|
// timeline[owner/repo/number]:issue timeline 事件(無則回空清單,
|
||||||
|
// 模擬 API 成功但無事件;timelineErr 模擬拉取失敗)。
|
||||||
|
timeline map[string][]TimelineEvent
|
||||||
|
timelineErr map[string]error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeStalledSource) CurrentUser() (string, error) { return f.username, nil }
|
func (f *fakeStalledSource) CurrentUser() (string, error) { return f.username, nil }
|
||||||
|
|
||||||
|
func (f *fakeStalledSource) IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error) {
|
||||||
|
key := fmt.Sprintf("%s/%s/%d", owner, repo, number)
|
||||||
|
if err := f.timelineErr[key]; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return f.timeline[key], nil
|
||||||
|
}
|
||||||
|
|
||||||
func (f *fakeStalledSource) GetIssue(owner, repo string, number int64) (Issue, error) {
|
func (f *fakeStalledSource) GetIssue(owner, repo string, number int64) (Issue, error) {
|
||||||
if f.getIssueErr != nil {
|
if f.getIssueErr != nil {
|
||||||
return Issue{}, f.getIssueErr
|
return Issue{}, f.getIssueErr
|
||||||
@@ -38,7 +52,7 @@ func (e *notFoundError) Error() string { return "404" }
|
|||||||
func newStalledFixture() *fakeStalledSource {
|
func newStalledFixture() *fakeStalledSource {
|
||||||
return &fakeStalledSource{
|
return &fakeStalledSource{
|
||||||
fakeSource: &fakeSource{
|
fakeSource: &fakeSource{
|
||||||
orgs: []string{"alterminal"},
|
orgs: []string{"alterminal"},
|
||||||
repos: map[string][]Repo{"alterminal": {
|
repos: map[string][]Repo{"alterminal": {
|
||||||
{Name: "agents", HasPullRequests: boolPtr(true)},
|
{Name: "agents", HasPullRequests: boolPtr(true)},
|
||||||
{Name: "teai", HasPullRequests: boolPtr(true)},
|
{Name: "teai", HasPullRequests: boolPtr(true)},
|
||||||
@@ -229,3 +243,92 @@ func TestResolveIssueXrefsEmptyBody(t *testing.T) {
|
|||||||
}
|
}
|
||||||
_ = time.Now // time 僅供 iso/at 使用;保留 import。
|
_ = time.Now // time 僅供 iso/at 使用;保留 import。
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestRunStalledChildXrefRefresh 回歸測試(agents #38、teai #34):
|
||||||
|
// 子項 updated_at 被跨 issue 引用(comment_ref)刷新時,子項有效活動
|
||||||
|
// 應經 directLastActivity 排除引用事件後採計,父追蹤項的停滯時鐘
|
||||||
|
// 不被虛假刷新。
|
||||||
|
func TestRunStalledChildXrefRefresh(t *testing.T) {
|
||||||
|
src := newStalledFixture()
|
||||||
|
// 子項 teai#2:直接活動為 created(-500) 與留言(-90),
|
||||||
|
// updated_at 卻是 -10(他處留言提及刷新)。
|
||||||
|
issue := src.issues["alterminal/teai"][2]
|
||||||
|
issue.UpdatedAt = iso(-10)
|
||||||
|
src.issues["alterminal/teai"][2] = issue
|
||||||
|
// timeline:-10 的刷新是 comment_ref(引用事件,排除),
|
||||||
|
// -90 有直接事件(label)可對應 → 有效活動 -90。
|
||||||
|
src.timeline = map[string][]TimelineEvent{
|
||||||
|
"alterminal/teai/2": {
|
||||||
|
{Type: "label", CreatedAt: iso(-90)},
|
||||||
|
{Type: "comment_ref", CreatedAt: iso(-10)},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
// 門檻 1 小時:父項 last_activity 取子項有效活動 -90 → 停滯 1.5h 列入;
|
||||||
|
// 若誤採被刷新的 -10,父項與子項都不會列入。
|
||||||
|
items, err := RunStalled(src, 1, at(0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("RunStalled: %v", err)
|
||||||
|
}
|
||||||
|
if len(items) != 2 {
|
||||||
|
t.Fatalf("應有兩筆(父追蹤項+子項),得到 %d:%+v", len(items), items)
|
||||||
|
}
|
||||||
|
var parent *Item
|
||||||
|
for i := range items {
|
||||||
|
if items[i].Repo == "alterminal/agents" && items[i].Number == 1 {
|
||||||
|
parent = &items[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if parent == nil {
|
||||||
|
t.Fatalf("找不到 agents#1:%+v", items)
|
||||||
|
}
|
||||||
|
if parent.Reason != "parent-tracking" {
|
||||||
|
t.Fatalf("agents#1 應為 parent-tracking,得到 %s", parent.Reason)
|
||||||
|
}
|
||||||
|
if parent.StalledHours != 1.5 {
|
||||||
|
t.Fatalf("父項停滯應以子項有效活動(-90m → 1.5h)計,得到 %.1f", parent.StalledHours)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRunStalledTimelineAllXrefFallback 回歸測試(agents #40、teai #34):
|
||||||
|
// issue 自身 updated_at 晚於全部已知直接活動、且 timeline 全為引用事件時,
|
||||||
|
// 回退已知直接活動的最晚時刻(不高估活動、不低估停滯);
|
||||||
|
// timeline 拉取失敗則保守沿用 updated_at。
|
||||||
|
func TestRunStalledTimelineAllXrefFallback(t *testing.T) {
|
||||||
|
src := newStalledFixture()
|
||||||
|
setIssueBody(src, "alterminal", "agents", 1, "") // 移除父項引用,teai#2 獨立判定
|
||||||
|
delete(src.comments, "alterminal/teai/2")
|
||||||
|
// agents#1 給一則近期留言,避免本身停滯(10h)干擾本測試的斷言。
|
||||||
|
src.comments["alterminal/agents/1"] = []Comment{
|
||||||
|
{CreatedAt: iso(-10), User: &User{UserName: "alex"}},
|
||||||
|
}
|
||||||
|
// teai#2:僅有 created(-500) 此一已知直接活動,
|
||||||
|
// updated_at -10 完全由他處提及刷新。
|
||||||
|
issue := src.issues["alterminal/teai"][2]
|
||||||
|
issue.UpdatedAt = iso(-10)
|
||||||
|
src.issues["alterminal/teai"][2] = issue
|
||||||
|
// 情境一:timeline 全為引用事件 → 回退 knownMax(created -500)
|
||||||
|
// → 停滯 8.3h,超過預設門檻 4h,列入。
|
||||||
|
src.timeline = map[string][]TimelineEvent{
|
||||||
|
"alterminal/teai/2": {{Type: "issue_ref", CreatedAt: iso(-10)}},
|
||||||
|
}
|
||||||
|
items, err := RunStalled(src, 0, at(0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("RunStalled: %v", err)
|
||||||
|
}
|
||||||
|
if len(items) != 1 || items[0].Number != 2 {
|
||||||
|
t.Fatalf("全引用事件應回退直接活動 → teai#2 停滯 8.3h 列入,得到 %+v", items)
|
||||||
|
}
|
||||||
|
if items[0].StalledHours != 8.3 {
|
||||||
|
t.Fatalf("回退 created(-500) → 停滯應 8.3h,得到 %.1f", items[0].StalledHours)
|
||||||
|
}
|
||||||
|
// 情境二:timeline 拉取失敗 → 保守沿用 updated_at(-10) → 0.2h 未達門檻,不列入。
|
||||||
|
src.timeline = nil
|
||||||
|
src.timelineErr = map[string]error{"alterminal/teai/2": errors.New("boom")}
|
||||||
|
items, err = RunStalled(src, 0, at(0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("RunStalled: %v", err)
|
||||||
|
}
|
||||||
|
if len(items) != 0 {
|
||||||
|
t.Fatalf("timeline 失敗應保守沿用 updated_at → 不列入,得到 %+v", items)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+127
-27
@@ -30,6 +30,11 @@ const (
|
|||||||
NudgeCooldownHours = 24.0
|
NudgeCooldownHours = 24.0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// xrefTimelineTypes 對應 gitea.py 的 XREF_TIMELINE_TYPES:他處留言/issue
|
||||||
|
// 提及本編號時產生的 timeline 引用事件。這類事件會刷新 updated_at,但不是
|
||||||
|
// 本 issue 的直接活動,directLastActivity 會予以排除(agents issue #34)。
|
||||||
|
var xrefTimelineTypes = map[string]bool{"comment_ref": true, "issue_ref": true}
|
||||||
|
|
||||||
// xrefPattern 對應 gitea.py 的 XREF_PATTERN:#N、repo#N、owner/repo#N。
|
// xrefPattern 對應 gitea.py 的 XREF_PATTERN:#N、repo#N、owner/repo#N。
|
||||||
//
|
//
|
||||||
// 前面不得是文數字/底線/斜線(避免切進 alterminal/bear#47 的後半段);
|
// 前面不得是文數字/底線/斜線(避免切進 alterminal/bear#47 的後半段);
|
||||||
@@ -149,6 +154,9 @@ type Source interface {
|
|||||||
IssueComments(owner, repo string, number int64) ([]Comment, error)
|
IssueComments(owner, repo string, number int64) ([]Comment, error)
|
||||||
// TryGetIssue 寬容版單一 issue 查詢:失敗(含 404)回 (零值, false, nil)。
|
// TryGetIssue 寬容版單一 issue 查詢:失敗(含 404)回 (零值, false, nil)。
|
||||||
TryGetIssue(owner, repo string, number int64) (Issue, bool, error)
|
TryGetIssue(owner, repo string, number int64) (Issue, bool, error)
|
||||||
|
// IssueTimeline 回傳 issue 的 timeline 事件(GET /repos/{o}/{r}/issues/{n}/timeline,
|
||||||
|
// 分頁)。directLastActivity 用來排除跨 issue 引用事件(agents issue #34)。
|
||||||
|
IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// iterXrefs 產出文字中的 (prefix, number) 配對(對應 _iter_issue_xrefs)。
|
// iterXrefs 產出文字中的 (prefix, number) 配對(對應 _iter_issue_xrefs)。
|
||||||
@@ -268,8 +276,11 @@ func childActivity(src Source, org, repo string, parent Issue, comments []Commen
|
|||||||
if pcOK && ccOK && !childCreated.After(parentCreated) {
|
if pcOK && ccOK && !childCreated.After(parentCreated) {
|
||||||
continue // 上行引用(父項回指更早或同時的 issue);時間未知則不排除
|
continue // 上行引用(父項回指更早或同時的 issue);時間未知則不排除
|
||||||
}
|
}
|
||||||
|
// 子項的直接活動:created_at、state 變更(closed_at)、留言(agents #32)。
|
||||||
|
// 原始 updated_at 不放入已知活動,另經 directLastActivity 核對後採計
|
||||||
|
//(與 considerIssue/considerPull 對本 issue 自身的處理同構)。
|
||||||
var ms []time.Time
|
var ms []time.Time
|
||||||
if m, ok := parseMoment(child.UpdatedAt); ok {
|
if m, ok := parseMoment(child.CreatedAt); ok {
|
||||||
ms = append(ms, m)
|
ms = append(ms, m)
|
||||||
}
|
}
|
||||||
if m, ok := parseMoment(child.ClosedAt); ok {
|
if m, ok := parseMoment(child.ClosedAt); ok {
|
||||||
@@ -282,6 +293,14 @@ func childActivity(src Source, org, repo string, parent Issue, comments []Commen
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if childUpdated, ok := parseMoment(child.UpdatedAt); ok {
|
||||||
|
// 子項 updated_at 可能被 comment_ref/issue_ref 引用事件刷新
|
||||||
|
//(agents #38):走與本 issue 自身相同的 directLastActivity 排除
|
||||||
|
// 邏輯(同源判定,不漂移);timeline 失敗時保守沿用 updated_at。
|
||||||
|
if d, ok := directLastActivity(src, t.Owner, t.Repo, t.Number, childUpdated, true, ms); ok {
|
||||||
|
ms = append(ms, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
var last *string
|
var last *string
|
||||||
if len(ms) > 0 {
|
if len(ms) > 0 {
|
||||||
latest := maxTime(ms)
|
latest := maxTime(ms)
|
||||||
@@ -302,6 +321,71 @@ func childActivity(src Source, org, repo string, parent Issue, comments []Commen
|
|||||||
return moments, children
|
return moments, children
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TimelineEvent 是 issue timeline 的單一事件(僅取判斷所需欄位;
|
||||||
|
// 對應 gitea.py _direct_last_activity 讀取的 timeline 物件)。
|
||||||
|
type TimelineEvent struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
CreatedAt string `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// directLastActivity 排除跨 issue 引用事件後,本 issue 的最後直接活動時刻
|
||||||
|
// (對應 gitea.py 的 _direct_last_activity;agents issues #34/#38/#40)。
|
||||||
|
//
|
||||||
|
// 他處留言/issue 提及本編號(comment_ref/issue_ref)也會刷新 updated_at,
|
||||||
|
// 直接採用會虛假刷新停滯時鐘(false negative)並低估 stalled_hours。
|
||||||
|
// updated_at 不晚於已知直接活動(留言、created_at、#32 納入的子項活動)時,
|
||||||
|
// updated_at 本身可信,不必多打一次 timeline API;只有 updated_at 晚於全部
|
||||||
|
// 已知活動時才拉 timeline 核對:排除引用類事件後取最晚事件時刻;若最晚的
|
||||||
|
// 都是引用事件(本 issue 無直接活動可對應 updated_at),則回退已知直接活動
|
||||||
|
// 的最晚時刻(agents #40)。timeline 拉取失敗時沿用 updated_at(不中斷掃描、
|
||||||
|
// 寧可少報不誤報缺失活動)。
|
||||||
|
func directLastActivity(src Source, org, repo string, number int64, updatedAt time.Time, hasUpdated bool, known []time.Time) (time.Time, bool) {
|
||||||
|
if !hasUpdated {
|
||||||
|
return time.Time{}, false
|
||||||
|
}
|
||||||
|
var knownMax *time.Time
|
||||||
|
for i := range known {
|
||||||
|
if known[i].IsZero() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if knownMax == nil || known[i].After(*knownMax) {
|
||||||
|
m := known[i]
|
||||||
|
knownMax = &m
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if knownMax == nil || !updatedAt.After(*knownMax) {
|
||||||
|
return updatedAt, true
|
||||||
|
}
|
||||||
|
timeline, err := src.IssueTimeline(org, repo, number)
|
||||||
|
if err != nil {
|
||||||
|
return updatedAt, true
|
||||||
|
}
|
||||||
|
var moments []time.Time
|
||||||
|
for _, e := range timeline {
|
||||||
|
if xrefTimelineTypes[e.Type] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if m, ok := parseMoment(e.CreatedAt); ok {
|
||||||
|
moments = append(moments, m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(moments) == 0 {
|
||||||
|
// timeline 全為引用事件:updated_at 完全由他處提及刷新,本 issue 沒有
|
||||||
|
// 可對應的直接活動。回退已知直接活動的最晚時刻,避免把被刷新的
|
||||||
|
// updated_at 當活動、低估停滯時數(agents #40);連已知活動都沒有時才
|
||||||
|
// 保守沿用 updated_at(不中斷掃描、寧可少報不誤報缺失活動)。
|
||||||
|
if knownMax != nil {
|
||||||
|
return *knownMax, true
|
||||||
|
}
|
||||||
|
return updatedAt, true
|
||||||
|
}
|
||||||
|
latest := maxTime(moments)
|
||||||
|
if latest.Before(updatedAt) {
|
||||||
|
return latest, true
|
||||||
|
}
|
||||||
|
return updatedAt, true
|
||||||
|
}
|
||||||
|
|
||||||
func maxTime(ts []time.Time) time.Time {
|
func maxTime(ts []time.Time) time.Time {
|
||||||
best := ts[0]
|
best := ts[0]
|
||||||
for _, t := range ts[1:] {
|
for _, t := range ts[1:] {
|
||||||
@@ -382,7 +466,7 @@ func ScanStalled(src Source, username string, threshold float64, now time.Time)
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if item, ok := considerPull(pr, comments, username, threshold, now); ok {
|
if item, ok := considerPull(src, org, r.Name, pr, comments, username, threshold, now); ok {
|
||||||
items = append(items, item)
|
items = append(items, item)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -398,19 +482,27 @@ func ScanStalled(src Source, username string, threshold float64, now time.Time)
|
|||||||
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) {
|
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)
|
childMoments, children := childActivity(src, org, repo, issue, comments, myOrgs, orgRepos)
|
||||||
assignees := AssigneeNames(&issue)
|
assignees := AssigneeNames(&issue)
|
||||||
var moments []time.Time
|
// 已知直接活動:留言、created_at、#32 納入的子項活動。
|
||||||
if m, ok := parseMoment(issue.UpdatedAt); ok {
|
var known []time.Time
|
||||||
moments = append(moments, m)
|
|
||||||
}
|
|
||||||
if m, ok := parseMoment(issue.CreatedAt); ok {
|
if m, ok := parseMoment(issue.CreatedAt); ok {
|
||||||
moments = append(moments, m)
|
known = append(known, m)
|
||||||
}
|
}
|
||||||
for _, c := range comments {
|
for _, c := range comments {
|
||||||
if m, ok := parseMoment(c.CreatedAt); ok {
|
if m, ok := parseMoment(c.CreatedAt); ok {
|
||||||
moments = append(moments, m)
|
known = append(known, m)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
moments = append(moments, childMoments...)
|
known = append(known, childMoments...)
|
||||||
|
// 跨 issue 引用(comment_ref/issue_ref)也會刷新 updated_at(agents #34):
|
||||||
|
// updated_at 晚於全部已知直接活動時,先排除引用事件核對後才採用,
|
||||||
|
// 避免停滯時鐘被虛假刷新或低估 stalled_hours。
|
||||||
|
var moments []time.Time
|
||||||
|
if m, ok := parseMoment(issue.UpdatedAt); ok {
|
||||||
|
if d, ok2 := directLastActivity(src, org, repo, issue.issueNumber(), m, ok, known); ok2 {
|
||||||
|
moments = append(moments, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
moments = append(moments, known...)
|
||||||
if len(moments) == 0 {
|
if len(moments) == 0 {
|
||||||
return Item{}, false
|
return Item{}, false
|
||||||
}
|
}
|
||||||
@@ -434,11 +526,21 @@ func considerIssue(src Source, org, repo string, issue Issue, comments []Comment
|
|||||||
case len(assignees) == 0:
|
case len(assignees) == 0:
|
||||||
reason = "no-assignee"
|
reason = "no-assignee"
|
||||||
case lastCommentBy != "" && containsString(assignees, lastCommentBy):
|
case lastCommentBy != "" && containsString(assignees, lastCommentBy):
|
||||||
reason = "assignee-idle"
|
if IsDeliveryReport(issue.Body, last) {
|
||||||
|
// 交付報告待確認(agents #47):assignee 已交付並交棒(回報他件/
|
||||||
|
// 請發起人確認關閉),停滯點在等待外部確認,不是 assignee 停滯。
|
||||||
|
reason = "waiting-outside"
|
||||||
|
} else {
|
||||||
|
reason = "assignee-idle"
|
||||||
|
}
|
||||||
case lastCommentBy == "":
|
case lastCommentBy == "":
|
||||||
reason = "no-commenter"
|
reason = "no-commenter"
|
||||||
}
|
}
|
||||||
if len(children) > 0 && anyOpen(children) {
|
if len(children) > 0 {
|
||||||
|
// 父追蹤項一律標 parent-tracking(agents #44,與 gitea.py 同步):
|
||||||
|
// 有 open 子項在推進時,父項留言閒置屬等待子項;子項全關閉時只剩
|
||||||
|
// 父項收尾(回報驗收並關閉),兩者都不是 assignee 停滯。統一標記
|
||||||
|
// 讓「父項收尾」規則能正確匹配,不退回通用原因(如 assignee-idle)。
|
||||||
reason = "parent-tracking"
|
reason = "parent-tracking"
|
||||||
}
|
}
|
||||||
item := Item{
|
item := Item{
|
||||||
@@ -455,21 +557,28 @@ func considerIssue(src Source, org, repo string, issue Issue, comments []Comment
|
|||||||
}
|
}
|
||||||
|
|
||||||
// considerPull 對單一 PR 套用停滯判定(對應 _consider 的 pull 分支)。
|
// considerPull 對單一 PR 套用停滯判定(對應 _consider 的 pull 分支)。
|
||||||
func considerPull(pr PullRequest, comments []Comment, username string, threshold float64, now time.Time) (Item, bool) {
|
func considerPull(src Source, org, repo string, pr PullRequest, comments []Comment, username string, threshold float64, now time.Time) (Item, bool) {
|
||||||
reviewers := ReviewerNames(&pr)
|
reviewers := ReviewerNames(&pr)
|
||||||
author := pr.Author()
|
author := pr.Author()
|
||||||
var moments []time.Time
|
// 已知直接活動:留言、created_at。
|
||||||
if m, ok := parseMoment(pr.UpdatedAt); ok {
|
var known []time.Time
|
||||||
moments = append(moments, m)
|
|
||||||
}
|
|
||||||
if m, ok := parseMoment(pr.CreatedAt); ok {
|
if m, ok := parseMoment(pr.CreatedAt); ok {
|
||||||
moments = append(moments, m)
|
known = append(known, m)
|
||||||
}
|
}
|
||||||
for _, c := range comments {
|
for _, c := range comments {
|
||||||
if m, ok := parseMoment(c.CreatedAt); ok {
|
if m, ok := parseMoment(c.CreatedAt); ok {
|
||||||
moments = append(moments, m)
|
known = append(known, m)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 跨 issue 引用也會刷新 PR 的 updated_at(agents #34):與 issue 同一道
|
||||||
|
// directLastActivity 排除邏輯(同源判定,不漂移)。
|
||||||
|
var moments []time.Time
|
||||||
|
if m, ok := parseMoment(pr.UpdatedAt); ok {
|
||||||
|
if d, ok2 := directLastActivity(src, org, repo, pr.Number, m, ok, known); ok2 {
|
||||||
|
moments = append(moments, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
moments = append(moments, known...)
|
||||||
if len(moments) == 0 {
|
if len(moments) == 0 {
|
||||||
return Item{}, false
|
return Item{}, false
|
||||||
}
|
}
|
||||||
@@ -507,15 +616,6 @@ func considerPull(pr PullRequest, comments []Comment, username string, threshold
|
|||||||
return item, true
|
return item, true
|
||||||
}
|
}
|
||||||
|
|
||||||
func anyOpen(children []Child) bool {
|
|
||||||
for _, c := range children {
|
|
||||||
if c.State == "open" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// round1 舍入到小數一位(對應 Python round(x, 1))。
|
// round1 舍入到小數一位(對應 Python round(x, 1))。
|
||||||
// 經 strconv 的十進位正確舍入(半偶數),與 Python 的浮點 round 行為一致,
|
// 經 strconv 的十進位正確舍入(半偶數),與 Python 的浮點 round 行為一致,
|
||||||
// 避免 (x*10+0.5) 截斷在 .x5 邊界產生偏差。
|
// 避免 (x*10+0.5) 截斷在 .x5 邊界產生偏差。
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -28,6 +29,8 @@ type fakeSource struct {
|
|||||||
pulls map[string][]PullRequest
|
pulls map[string][]PullRequest
|
||||||
// comments[owner/repo/number]
|
// comments[owner/repo/number]
|
||||||
comments map[string][]Comment
|
comments map[string][]Comment
|
||||||
|
// timelines[owner/repo/number]:issue timeline 事件(nil → 空 timeline)。
|
||||||
|
timelines map[string][]TimelineEvent
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeSource) MyOrganizations() ([]string, error) { return f.orgs, nil }
|
func (f *fakeSource) MyOrganizations() ([]string, error) { return f.orgs, nil }
|
||||||
@@ -39,8 +42,13 @@ func (f *fakeSource) OrganizationRepositories(org string) ([]Repo, error) {
|
|||||||
func (f *fakeSource) OpenIssues(owner, repo string) ([]Issue, error) {
|
func (f *fakeSource) OpenIssues(owner, repo string) ([]Issue, error) {
|
||||||
var out []Issue
|
var out []Issue
|
||||||
for _, i := range f.issues[owner+"/"+repo] {
|
for _, i := range f.issues[owner+"/"+repo] {
|
||||||
|
if i.State == "closed" {
|
||||||
|
continue // 對齊真實 API:OpenIssues 只回 open;closed 條目僅供 TryGetIssue 解引用。
|
||||||
|
}
|
||||||
out = append(out, i)
|
out = append(out, i)
|
||||||
}
|
}
|
||||||
|
// 對齊真實 API:issues 依 id(=number)遞增回傳,消除 map 迭代隨機性。
|
||||||
|
sort.Slice(out, func(a, b int) bool { return out[a].Number < out[b].Number })
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,6 +60,10 @@ func (f *fakeSource) IssueComments(owner, repo string, number int64) ([]Comment,
|
|||||||
return f.comments[fmt.Sprintf("%s/%s/%d", owner, repo, number)], nil
|
return f.comments[fmt.Sprintf("%s/%s/%d", owner, repo, number)], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (f *fakeSource) IssueTimeline(owner, repo string, number int64) ([]TimelineEvent, error) {
|
||||||
|
return f.timelines[fmt.Sprintf("%s/%s/%d", owner, repo, number)], nil
|
||||||
|
}
|
||||||
|
|
||||||
func (f *fakeSource) TryGetIssue(owner, repo string, number int64) (Issue, bool, error) {
|
func (f *fakeSource) TryGetIssue(owner, repo string, number int64) (Issue, bool, error) {
|
||||||
i, ok := f.issues[owner+"/"+repo][number]
|
i, ok := f.issues[owner+"/"+repo][number]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -236,6 +248,46 @@ func TestScanStalledNudgeCooldown(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestScanStalledParentWrapup(teai #47,同步 agents #44):子項全關閉的父追蹤項
|
||||||
|
// 不退回通用原因(assignee-idle),一律標 parent-tracking——「父項收尾」情境。
|
||||||
|
func TestScanStalledParentWrapup(t *testing.T) {
|
||||||
|
now := at(0)
|
||||||
|
// 父項 3 最後留言來自 assignee ceo(舊行為會誤標 assignee-idle);
|
||||||
|
// 唯一子項 7 已關閉,父子最後活動皆 5 小時前。
|
||||||
|
src := &fakeSource{
|
||||||
|
orgs: []string{"alterminal"},
|
||||||
|
repos: map[string][]Repo{"alterminal": repoWith("teai", true)},
|
||||||
|
issues: map[string]map[int64]Issue{
|
||||||
|
"alterminal/teai": {
|
||||||
|
3: {Number: 3, Title: "父", State: "open", Body: "子項:#7", CreatedAt: iso(-700), UpdatedAt: iso(-300), Assignees: []User{{UserName: "ceo"}}, Repository: &Repository{FullName: "alterminal/teai"}},
|
||||||
|
7: {Number: 7, Title: "子", State: "closed", CreatedAt: iso(-650), UpdatedAt: iso(-300), Repository: &Repository{FullName: "alterminal/teai"}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comments: map[string][]Comment{
|
||||||
|
"alterminal/teai/3": {{User: &User{UserName: "ceo"}, CreatedAt: iso(-300)}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ScanStalled: %v", err)
|
||||||
|
}
|
||||||
|
var parent *Item
|
||||||
|
for i := range got {
|
||||||
|
if got[i].Number == 3 {
|
||||||
|
parent = &got[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if parent == nil {
|
||||||
|
t.Fatalf("父項 3 應列入(5h 無活動),got %v", got)
|
||||||
|
}
|
||||||
|
if parent.Reason != "parent-tracking" {
|
||||||
|
t.Errorf("子項全關閉的父項 reason = %q, want parent-tracking", parent.Reason)
|
||||||
|
}
|
||||||
|
if len(parent.ChildActivity) == 0 {
|
||||||
|
t.Errorf("父項 3 應附 child_activity,got %v", parent.ChildActivity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestScanStalledParentTracking 父追蹤項:子項活動計入 last_activity、reason 標記。
|
// TestScanStalledParentTracking 父追蹤項:子項活動計入 last_activity、reason 標記。
|
||||||
func TestScanStalledParentTracking(t *testing.T) {
|
func TestScanStalledParentTracking(t *testing.T) {
|
||||||
now := at(0)
|
now := at(0)
|
||||||
@@ -314,6 +366,13 @@ func TestScanStalledParentTrackingNotChild(t *testing.T) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
// timeline:#47 的 updated_at 對應直接事件(assignees)、#39 對應 label
|
||||||
|
//(agents #34 後 updated_at 需經 timeline 核對才採計;直接事件可對應 → 採用)。
|
||||||
|
// 必須在 ScanStalled 之前設定——掃描當下讀不到的事後修改無效。
|
||||||
|
src.timelines = map[string][]TimelineEvent{
|
||||||
|
"alterminal/teai/47": {{Type: "assignees", CreatedAt: iso(-600)}},
|
||||||
|
"alterminal/teai/39": {{Type: "label", CreatedAt: iso(-60)}},
|
||||||
|
}
|
||||||
got, err := ScanStalled(src, "admin", 4.0, now)
|
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("ScanStalled: %v", err)
|
t.Fatalf("ScanStalled: %v", err)
|
||||||
@@ -515,6 +574,9 @@ func (e errSource) IssueComments(string, string, int64) ([]Comment, error) {
|
|||||||
func (e errSource) TryGetIssue(string, string, int64) (Issue, bool, error) {
|
func (e errSource) TryGetIssue(string, string, int64) (Issue, bool, error) {
|
||||||
return Issue{}, false, errors.New("boom")
|
return Issue{}, false, errors.New("boom")
|
||||||
}
|
}
|
||||||
|
func (e errSource) IssueTimeline(string, string, int64) ([]TimelineEvent, error) {
|
||||||
|
return nil, errors.New("boom")
|
||||||
|
}
|
||||||
|
|
||||||
// TestRound1 round1 十進位舍入到一位小數(與 Python round(x,1) 半偶數一致)。
|
// TestRound1 round1 十進位舍入到一位小數(與 Python round(x,1) 半偶數一致)。
|
||||||
func TestRound1(t *testing.T) {
|
func TestRound1(t *testing.T) {
|
||||||
@@ -533,3 +595,39 @@ func TestRound1(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestScanStalledDeliveryReport(agents #47):assignee 最後留言為交付報告
|
||||||
|
// (結構訊號+交棒訊號)→ waiting-outside,不是 assignee-idle;
|
||||||
|
// 同型認領留言(無交棒)維持 assignee-idle——修正不製造新死角。
|
||||||
|
func TestScanStalledDeliveryReport(t *testing.T) {
|
||||||
|
now := at(0)
|
||||||
|
defBody := "## 完成定義\n- 逐項回報查核結果至此 issue;\n- 全數通過 → 回報 #39 並由 #39 assignee 關閉"
|
||||||
|
src := &fakeSource{
|
||||||
|
orgs: []string{"alterminal"},
|
||||||
|
repos: map[string][]Repo{"alterminal": repoWith("bear", true)},
|
||||||
|
issues: map[string]map[int64]Issue{
|
||||||
|
"alterminal/bear": {
|
||||||
|
5: {Number: 5, Title: "驗收", State: "open", Body: defBody, CreatedAt: iso(-600), UpdatedAt: iso(-300), Assignees: []User{{UserName: "queena"}}, Repository: &Repository{FullName: "alterminal/bear"}},
|
||||||
|
6: {Number: 6, Title: "認領中", State: "open", Body: defBody, CreatedAt: iso(-600), UpdatedAt: iso(-300), Assignees: []User{{UserName: "dan"}}, Repository: &Repository{FullName: "alterminal/bear"}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
comments: map[string][]Comment{
|
||||||
|
"alterminal/bear/5": {{User: &User{UserName: "queena"}, CreatedAt: iso(-300), Body: "## 查核結果\n結論:四項全數通過。回報 #39:可由 @ceo 關閉。"}},
|
||||||
|
"alterminal/bear/6": {{User: &User{UserName: "dan"}, CreatedAt: iso(-300), Body: "認領。完成後逐項回報結果至此。"}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
got, err := ScanStalled(src, "admin", 4.0, now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ScanStalled: %v", err)
|
||||||
|
}
|
||||||
|
byNumber := map[int64]Item{}
|
||||||
|
for _, it := range got {
|
||||||
|
byNumber[it.Number] = it
|
||||||
|
}
|
||||||
|
if it, ok := byNumber[5]; !ok || it.Reason != "waiting-outside" {
|
||||||
|
t.Errorf("issue 5(交付報告)reason 應為 waiting-outside,got %+v", it)
|
||||||
|
}
|
||||||
|
if it, ok := byNumber[6]; !ok || it.Reason != "assignee-idle" {
|
||||||
|
t.Errorf("issue 6(認領留言)reason 應為 assignee-idle,got %+v", it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user