500 lines
19 KiB
Python
500 lines
19 KiB
Python
"""
|
||||
|
|
禅道项目管理服务
|
|||
|
|
================
|
|||
|
|
|
|||
|
|
【功能说明】对接禅道项目管理平台(开源版 16.5+ / 18.x),支持创建/查询/更新 Bug 和任务。
|
|||
|
|
对应用户需求:Agent 任务与禅道 Issue 双向同步。
|
|||
|
|
|
|||
|
|
【技术选型理由】
|
|||
|
|
1. 禅道 18.x 开源版提供 REST v1 API(/api.php/v1/*),鉴权用 Bearer Token;
|
|||
|
|
2. Token 通过 POST /api.php/v1/tokens 用账号密码换取,有效期有限(默认约 7 天);
|
|||
|
|
3. 为避免 Token 过期导致调用失败,本模块做「自动登录 + 内存/落盘缓存 + 到期前主动续期 + 401 强制重登」;
|
|||
|
|
4. 未配置凭证时降级为本地记录,不影响主流程。
|
|||
|
|
|
|||
|
|
【实现思路】
|
|||
|
|
- ZentaoService 统一封装鉴权与业务接口;
|
|||
|
|
- _ensure_token():命中缓存直接用;缺失或临期则登录换新 Token 并落盘到 data_root;
|
|||
|
|
- _request():带 Bearer 头请求;401/403 时强制刷新并重试一次;
|
|||
|
|
- create_bug / create_task / search / update_status:对应 v1 的 bugs / tasks 资源;
|
|||
|
|
- 全程不打印密码与完整 Token(日志只打前 6 位做定位)。
|
|||
|
|
|
|||
|
|
【潜在风险与应对】
|
|||
|
|
风险1:接口返回的 expireTime 格式不统一(时间戳 / 秒数 / 日期字符串)。
|
|||
|
|
应对:_parse_expire_time 兼容多种格式;解析不出时按 zentao_token_ttl_seconds 兜底,
|
|||
|
|
并在「剩余不足 5 分钟」时主动续期,宁可早换不突然过期。
|
|||
|
|
风险2:多线程并发首次调用会重复登录。
|
|||
|
|
应对:刷新动作用 threading.Lock 保护,拿到锁后再二次检查缓存。
|
|||
|
|
风险3:账号密码改了导致登录失败。
|
|||
|
|
应对:返回明确报错文案,不抛裸异常;同时保留 ZENTAO_TOKEN 手工令牌兜底。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import json
|
|||
|
|
import logging
|
|||
|
|
import re
|
|||
|
|
import threading
|
|||
|
|
import time
|
|||
|
|
from pathlib import Path
|
|||
|
|
from typing import Any
|
|||
|
|
|
|||
|
|
from app.config.settings import load_settings
|
|||
|
|
|
|||
|
|
logger = logging.getLogger("agent.zentao")
|
|||
|
|
|
|||
|
|
# 剩余有效期低于该阈值(秒)即主动续期,避免长请求撞上过期点
|
|||
|
|
REFRESH_MARGIN_SECONDS = 300
|
|||
|
|
# 登录/业务请求超时
|
|||
|
|
LOGIN_TIMEOUT = 20.0
|
|||
|
|
REQUEST_TIMEOUT = 20.0
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _mask(token: str) -> str:
|
|||
|
|
"""日志用的 Token 脱敏,只露前 6 位。"""
|
|||
|
|
return f"{token[:6]}..." if token else "<empty>"
|
|||
|
|
|
|||
|
|
|
|||
|
|
# 报错信息里需要脱敏的敏感字段(token / 口令);结尾引号可选,兼容被截断的 JSON 片段
|
|||
|
|
_SENSITIVE_KEY_RE = re.compile(
|
|||
|
|
r'("(?:token|apiToken|apikey|access_token|accessToken|password|passwd)"\s*:\s*")([^"]+)("?)',
|
|||
|
|
re.IGNORECASE,
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _redact_body(text: str, limit: int = 300) -> str:
|
|||
|
|
"""错误信息里的响应体脱敏,避免把完整 Token / 口令打进日志。"""
|
|||
|
|
snippet = (text or "")[:limit]
|
|||
|
|
return _SENSITIVE_KEY_RE.sub(lambda m: f"{m.group(1)}{_mask(m.group(2) or '')}{m.group(3)}", snippet)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _parse_expire_time(raw: Any, default_ttl: int) -> float:
|
|||
|
|
"""
|
|||
|
|
把禅道返回的 expireTime 归一成「过期时刻的 unix 时间戳」。
|
|||
|
|
|
|||
|
|
兼容:
|
|||
|
|
1730000000 → unix 秒
|
|||
|
|
1730000000000 → unix 毫秒
|
|||
|
|
604800 → 从现在起 N 秒
|
|||
|
|
"2026-10-30 12:00:00" → 日期字符串
|
|||
|
|
缺失/解析失败 → 现在 + default_ttl
|
|||
|
|
"""
|
|||
|
|
now = time.time()
|
|||
|
|
if raw is None or raw == "":
|
|||
|
|
return now + default_ttl
|
|||
|
|
|
|||
|
|
if isinstance(raw, (int, float)):
|
|||
|
|
val = float(raw)
|
|||
|
|
if val > 1e12: # 毫秒
|
|||
|
|
return val / 1000.0
|
|||
|
|
if val > 1e9: # unix 秒
|
|||
|
|
return val
|
|||
|
|
if val > 0: # 从现在起的秒数
|
|||
|
|
return now + val
|
|||
|
|
return now + default_ttl
|
|||
|
|
|
|||
|
|
if isinstance(raw, str):
|
|||
|
|
s = raw.strip()
|
|||
|
|
if s.isdigit():
|
|||
|
|
return _parse_expire_time(int(s), default_ttl)
|
|||
|
|
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
|||
|
|
try:
|
|||
|
|
import datetime as _dt
|
|||
|
|
|
|||
|
|
return _dt.datetime.strptime(s, fmt).timestamp()
|
|||
|
|
except ValueError:
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
return now + default_ttl
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _extract_token(payload: Any) -> tuple[str, float | None]:
|
|||
|
|
"""
|
|||
|
|
从登录响应里挖出 (token, expireTime)。
|
|||
|
|
兼容裸对象 / status+data 包裹 / token 嵌套等情况。
|
|||
|
|
"""
|
|||
|
|
if not isinstance(payload, dict):
|
|||
|
|
return "", None
|
|||
|
|
|
|||
|
|
token = ""
|
|||
|
|
expire_raw: Any = None
|
|||
|
|
|
|||
|
|
for key in ("token", "apiToken", "apikey", "access_token", "accessToken"):
|
|||
|
|
if isinstance(payload.get(key), str) and payload.get(key):
|
|||
|
|
token = payload[key]
|
|||
|
|
break
|
|||
|
|
|
|||
|
|
for key in ("expireTime", "expire", "expiresAt", "expires_at", "expiry", "expires_in", "expiresIn"):
|
|||
|
|
if key in payload and payload[key] not in (None, ""):
|
|||
|
|
expire_raw = payload[key]
|
|||
|
|
break
|
|||
|
|
|
|||
|
|
if not token:
|
|||
|
|
data = payload.get("data")
|
|||
|
|
if isinstance(data, dict):
|
|||
|
|
token, expire_inner = _extract_token(data)
|
|||
|
|
if expire_raw is None:
|
|||
|
|
expire_raw = expire_inner
|
|||
|
|
elif isinstance(data, str) and data:
|
|||
|
|
token = data
|
|||
|
|
|
|||
|
|
return token, expire_raw
|
|||
|
|
|
|||
|
|
|
|||
|
|
class ZentaoService:
|
|||
|
|
"""禅道项目管理服务(自动管理 Token 生命周期)"""
|
|||
|
|
|
|||
|
|
def __init__(self) -> None:
|
|||
|
|
self._lock = threading.Lock()
|
|||
|
|
self._base_url = ""
|
|||
|
|
self._account = ""
|
|||
|
|
self._password = ""
|
|||
|
|
self._static_token = ""
|
|||
|
|
self._token_ttl = 6 * 24 * 3600
|
|||
|
|
self._cache_path: Path | None = None
|
|||
|
|
|
|||
|
|
self._token = ""
|
|||
|
|
self._expire_at = 0.0
|
|||
|
|
|
|||
|
|
self._load_config()
|
|||
|
|
self._load_token_cache()
|
|||
|
|
|
|||
|
|
# ========== 配置与缓存 ==========
|
|||
|
|
|
|||
|
|
def _load_config(self) -> None:
|
|||
|
|
"""从 .env 加载禅道配置。"""
|
|||
|
|
try:
|
|||
|
|
settings = load_settings()
|
|||
|
|
self._base_url = str(getattr(settings, "zentao_url", "") or "").rstrip("/")
|
|||
|
|
self._account = getattr(settings, "zentao_account", "") or ""
|
|||
|
|
self._password = getattr(settings, "zentao_password", "") or ""
|
|||
|
|
self._static_token = getattr(settings, "zentao_token", "") or ""
|
|||
|
|
self._token_ttl = int(getattr(settings, "zentao_token_ttl_seconds", 6 * 24 * 3600) or 6 * 24 * 3600)
|
|||
|
|
self._cache_path = Path(settings.data_root) / "zentao_token.json"
|
|||
|
|
except Exception: # noqa: BLE001
|
|||
|
|
self._base_url = ""
|
|||
|
|
self._account = ""
|
|||
|
|
self._password = ""
|
|||
|
|
self._static_token = ""
|
|||
|
|
self._cache_path = None
|
|||
|
|
|
|||
|
|
def _load_token_cache(self) -> None:
|
|||
|
|
"""从磁盘恢复上次的 Token,服务重启不必重新登录。"""
|
|||
|
|
path = self._cache_path
|
|||
|
|
if path is None or not path.exists():
|
|||
|
|
return
|
|||
|
|
try:
|
|||
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|||
|
|
if data.get("account") not in (None, self._account):
|
|||
|
|
return # 换账号了,旧缓存作废
|
|||
|
|
token = data.get("token") or ""
|
|||
|
|
expire_at = float(data.get("expire_at") or 0)
|
|||
|
|
if token and expire_at > time.time():
|
|||
|
|
self._token = token
|
|||
|
|
self._expire_at = expire_at
|
|||
|
|
logger.info("禅道 Token 已从缓存恢复,到期时间:%s", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(expire_at)))
|
|||
|
|
except Exception as exc: # noqa: BLE001
|
|||
|
|
logger.warning("禅道 Token 缓存读取失败:%s", exc)
|
|||
|
|
|
|||
|
|
def _save_token_cache(self) -> None:
|
|||
|
|
path = self._cache_path
|
|||
|
|
if path is None:
|
|||
|
|
return
|
|||
|
|
try:
|
|||
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|||
|
|
path.write_text(
|
|||
|
|
json.dumps(
|
|||
|
|
{
|
|||
|
|
"account": self._account,
|
|||
|
|
"token": self._token,
|
|||
|
|
"expire_at": self._expire_at,
|
|||
|
|
},
|
|||
|
|
ensure_ascii=False,
|
|||
|
|
indent=2,
|
|||
|
|
),
|
|||
|
|
encoding="utf-8",
|
|||
|
|
)
|
|||
|
|
except Exception as exc: # noqa: BLE001
|
|||
|
|
logger.warning("禅道 Token 缓存写入失败:%s", exc)
|
|||
|
|
|
|||
|
|
# ========== 对外属性 ==========
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def is_configured(self) -> bool:
|
|||
|
|
"""是否具备可用凭证(账号密码 或 手工 Token)。"""
|
|||
|
|
return bool(self._base_url) and bool(
|
|||
|
|
(self._account and self._password) or self._static_token or self._token
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
@property
|
|||
|
|
def has_login_credential(self) -> bool:
|
|||
|
|
return bool(self._account and self._password)
|
|||
|
|
|
|||
|
|
def token_status(self) -> dict:
|
|||
|
|
"""给外部(健康检查/调试)看的 Token 状态,不含明文 Token。"""
|
|||
|
|
now = time.time()
|
|||
|
|
return {
|
|||
|
|
"base_url": self._base_url,
|
|||
|
|
"mode": "account_password" if self.has_login_credential else ("static_token" if self._static_token else "none"),
|
|||
|
|
"token_masked": _mask(self._token or self._static_token),
|
|||
|
|
"expire_at": self._expire_at or None,
|
|||
|
|
"expire_at_text": (
|
|||
|
|
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self._expire_at)) if self._expire_at else None
|
|||
|
|
),
|
|||
|
|
"seconds_left": max(0, int(self._expire_at - now)) if self._expire_at else None,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
# ========== Token 生命周期 ==========
|
|||
|
|
|
|||
|
|
def refresh_token(self, force: bool = False) -> dict:
|
|||
|
|
"""
|
|||
|
|
刷新 Token。默认只在缺失/临期时刷新;force=True 则无条件重新登录。
|
|||
|
|
返回 {"success": bool, "message": str, ...}
|
|||
|
|
"""
|
|||
|
|
with self._lock:
|
|||
|
|
if not force and self._token and self._expire_at - time.time() > REFRESH_MARGIN_SECONDS:
|
|||
|
|
return {"success": True, "message": "Token 仍有效,无需刷新"}
|
|||
|
|
|
|||
|
|
# 手工 Token 兜底:没有账号密码就只能用它,不存在续期
|
|||
|
|
if not self.has_login_credential:
|
|||
|
|
if self._static_token:
|
|||
|
|
self._token = self._static_token
|
|||
|
|
self._expire_at = time.time() + self._token_ttl
|
|||
|
|
return {"success": True, "message": "使用手工配置的 ZENTAO_TOKEN"}
|
|||
|
|
return {"success": False, "message": "禅道未配置(需在 .env 配置 ZENTAO_ACCOUNT/ZENTAO_PASSWORD 或 ZENTAO_TOKEN)"}
|
|||
|
|
|
|||
|
|
result = self._login()
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
def _login(self) -> dict:
|
|||
|
|
"""调 REST v1 tokens 接口换新 Token。调用方需已持有 self._lock。"""
|
|||
|
|
if not self._base_url:
|
|||
|
|
return {"success": False, "message": "禅道未配置(缺少 ZENTAO_URL)"}
|
|||
|
|
|
|||
|
|
url = f"{self._base_url}/api.php/v1/tokens"
|
|||
|
|
try:
|
|||
|
|
import httpx
|
|||
|
|
|
|||
|
|
resp = httpx.post(
|
|||
|
|
url,
|
|||
|
|
json={"account": self._account, "password": self._password},
|
|||
|
|
timeout=LOGIN_TIMEOUT,
|
|||
|
|
)
|
|||
|
|
except Exception as exc: # noqa: BLE001
|
|||
|
|
return {"success": False, "message": f"禅道登录请求失败:{exc}"}
|
|||
|
|
|
|||
|
|
# 禅道创建 Token 成功时返回 201 Created(REST 资源创建语义),与 _request() 判定保持一致
|
|||
|
|
if resp.status_code not in (200, 201):
|
|||
|
|
return {
|
|||
|
|
"success": False,
|
|||
|
|
"message": f"禅道登录失败 HTTP {resp.status_code}:{_redact_body(resp.text)}",
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
payload = resp.json()
|
|||
|
|
except Exception: # noqa: BLE001
|
|||
|
|
return {"success": False, "message": f"禅道登录响应非 JSON:{_redact_body(resp.text)}"}
|
|||
|
|
|
|||
|
|
token, expire_raw = _extract_token(payload)
|
|||
|
|
if not token:
|
|||
|
|
return {"success": False, "message": f"禅道登录响应缺少 token:{_redact_body(resp.text)}"}
|
|||
|
|
|
|||
|
|
self._token = token
|
|||
|
|
self._expire_at = _parse_expire_time(expire_raw, self._token_ttl)
|
|||
|
|
self._save_token_cache()
|
|||
|
|
|
|||
|
|
logger.info(
|
|||
|
|
"禅道 Token 已刷新(%s),到期时间:%s",
|
|||
|
|
_mask(token),
|
|||
|
|
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self._expire_at)),
|
|||
|
|
)
|
|||
|
|
return {
|
|||
|
|
"success": True,
|
|||
|
|
"message": "Token 已刷新",
|
|||
|
|
"token_masked": _mask(token),
|
|||
|
|
"expire_at_text": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self._expire_at)),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
def _ensure_token(self) -> str:
|
|||
|
|
"""返回可用 Token;缺失或临期则刷新。拿不到返回空串。"""
|
|||
|
|
now = time.time()
|
|||
|
|
if self._token and self._expire_at - now > REFRESH_MARGIN_SECONDS:
|
|||
|
|
return self._token
|
|||
|
|
|
|||
|
|
# 手工 Token 且无账号密码:直接用,不走登录
|
|||
|
|
if self._static_token and not self.has_login_credential:
|
|||
|
|
self._token = self._static_token
|
|||
|
|
if not self._expire_at:
|
|||
|
|
self._expire_at = now + self._token_ttl
|
|||
|
|
return self._token
|
|||
|
|
|
|||
|
|
self.refresh_token()
|
|||
|
|
return self._token
|
|||
|
|
|
|||
|
|
# ========== HTTP 封装 ==========
|
|||
|
|
|
|||
|
|
def _request(
|
|||
|
|
self,
|
|||
|
|
method: str,
|
|||
|
|
path: str,
|
|||
|
|
params: dict | None = None,
|
|||
|
|
json_body: dict | None = None,
|
|||
|
|
retry_on_auth_fail: bool = True,
|
|||
|
|
) -> dict:
|
|||
|
|
"""
|
|||
|
|
带鉴权的禅道 REST 请求。
|
|||
|
|
|
|||
|
|
path 以 / 开头,拼在 {base_url}/api.php/v1 之后,
|
|||
|
|
例如 path="/bugs" → {base_url}/api.php/v1/bugs。
|
|||
|
|
"""
|
|||
|
|
if not self._base_url:
|
|||
|
|
return {"success": False, "status_code": 0, "message": "禅道未配置(缺少 ZENTAO_URL)"}
|
|||
|
|
|
|||
|
|
token = self._ensure_token()
|
|||
|
|
if not token:
|
|||
|
|
return {"success": False, "status_code": 0, "message": "禅道 Token 获取失败,请检查 ZENTAO_ACCOUNT/ZENTAO_PASSWORD"}
|
|||
|
|
|
|||
|
|
url = f"{self._base_url}/api.php/v1{path}"
|
|||
|
|
headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
|
|||
|
|
try:
|
|||
|
|
import httpx
|
|||
|
|
|
|||
|
|
resp = httpx.request(
|
|||
|
|
method.upper(),
|
|||
|
|
url,
|
|||
|
|
params=params,
|
|||
|
|
json=json_body,
|
|||
|
|
headers=headers,
|
|||
|
|
timeout=REQUEST_TIMEOUT,
|
|||
|
|
)
|
|||
|
|
except Exception as exc: # noqa: BLE001
|
|||
|
|
return {"success": False, "status_code": 0, "message": f"禅道调用失败:{exc}"}
|
|||
|
|
|
|||
|
|
# Token 失效:强制重登后重试一次
|
|||
|
|
if resp.status_code in (401, 403) and retry_on_auth_fail and self.has_login_credential:
|
|||
|
|
logger.info("禅道返回 %s,强制刷新 Token 后重试", resp.status_code)
|
|||
|
|
self.refresh_token(force=True)
|
|||
|
|
if self._token:
|
|||
|
|
try:
|
|||
|
|
import httpx
|
|||
|
|
|
|||
|
|
headers["Authorization"] = f"Bearer {self._token}"
|
|||
|
|
resp = httpx.request(
|
|||
|
|
method.upper(),
|
|||
|
|
url,
|
|||
|
|
params=params,
|
|||
|
|
json=json_body,
|
|||
|
|
headers=headers,
|
|||
|
|
timeout=REQUEST_TIMEOUT,
|
|||
|
|
)
|
|||
|
|
except Exception as exc: # noqa: BLE001
|
|||
|
|
return {"success": False, "status_code": 0, "message": f"禅道重试失败:{exc}"}
|
|||
|
|
|
|||
|
|
ok = resp.status_code in (200, 201)
|
|||
|
|
try:
|
|||
|
|
data: Any = resp.json()
|
|||
|
|
except Exception: # noqa: BLE001
|
|||
|
|
data = None
|
|||
|
|
|
|||
|
|
return {
|
|||
|
|
"success": ok,
|
|||
|
|
"status_code": resp.status_code,
|
|||
|
|
"data": data,
|
|||
|
|
# data 解析失败时 raw 会作为错误载荷回传给调用方(可能进日志/接口响应),必须脱敏
|
|||
|
|
"raw": _redact_body(resp.text) if data is None else None,
|
|||
|
|
"message": "" if ok else f"禅道返回 HTTP {resp.status_code}:{_redact_body(resp.text)}",
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
# ========== 业务接口 ==========
|
|||
|
|
|
|||
|
|
def create_bug(self, title: str, description: str = "", project_id: str = "") -> dict:
|
|||
|
|
"""创建禅道 Bug。"""
|
|||
|
|
if not self.is_configured:
|
|||
|
|
return {
|
|||
|
|
"success": False,
|
|||
|
|
"message": "禅道未配置(需在 .env 配置 ZENTAO_ACCOUNT/ZENTAO_PASSWORD)",
|
|||
|
|
"local_record": {"title": title, "description": description, "type": "bug"},
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
body: dict[str, Any] = {
|
|||
|
|
"title": title,
|
|||
|
|
"steps": description or title,
|
|||
|
|
}
|
|||
|
|
if project_id not in ("", None):
|
|||
|
|
body["project"] = int(project_id) if str(project_id).isdigit() else project_id
|
|||
|
|
|
|||
|
|
result = self._request("POST", "/bugs", json_body=body)
|
|||
|
|
return {
|
|||
|
|
"success": result["success"],
|
|||
|
|
"data": result.get("data") if result["success"] else result.get("raw") or result.get("message"),
|
|||
|
|
"message": result.get("message", ""),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
def create_task(self, title: str, description: str = "", project_id: str = "") -> dict:
|
|||
|
|
"""创建禅道任务。"""
|
|||
|
|
if not self.is_configured:
|
|||
|
|
return {
|
|||
|
|
"success": False,
|
|||
|
|
"message": "禅道未配置",
|
|||
|
|
"local_record": {"title": title, "description": description, "type": "task"},
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
body: dict[str, Any] = {
|
|||
|
|
"name": title,
|
|||
|
|
"desc": description or title,
|
|||
|
|
}
|
|||
|
|
if project_id not in ("", None):
|
|||
|
|
body["project"] = int(project_id) if str(project_id).isdigit() else project_id
|
|||
|
|
|
|||
|
|
result = self._request("POST", "/tasks", json_body=body)
|
|||
|
|
return {
|
|||
|
|
"success": result["success"],
|
|||
|
|
"data": result.get("data") if result["success"] else result.get("raw") or result.get("message"),
|
|||
|
|
"message": result.get("message", ""),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
def search(self, keyword: str = "") -> dict:
|
|||
|
|
"""搜索禅道 Issue(Bug 列表,支持关键字过滤)。"""
|
|||
|
|
if not self.is_configured:
|
|||
|
|
return {"success": False, "message": "禅道未配置", "results": []}
|
|||
|
|
|
|||
|
|
params: dict[str, Any] = {"page": 1, "limit": 20}
|
|||
|
|
if keyword:
|
|||
|
|
params["keywords"] = keyword
|
|||
|
|
|
|||
|
|
result = self._request("GET", "/bugs", params=params)
|
|||
|
|
if not result["success"]:
|
|||
|
|
return {"success": False, "message": result.get("message", ""), "results": []}
|
|||
|
|
|
|||
|
|
data = result.get("data")
|
|||
|
|
# v1 常见返回:{"bugs": [...]} 或 [...]
|
|||
|
|
if isinstance(data, dict):
|
|||
|
|
items = data.get("bugs") or data.get("data") or data.get("items") or []
|
|||
|
|
elif isinstance(data, list):
|
|||
|
|
items = data
|
|||
|
|
else:
|
|||
|
|
items = []
|
|||
|
|
return {"success": True, "results": items}
|
|||
|
|
|
|||
|
|
def update_status(self, issue_id: str, status: str = "done") -> dict:
|
|||
|
|
"""更新禅道 Issue(Bug)状态。"""
|
|||
|
|
if not self.is_configured:
|
|||
|
|
return {"success": False, "message": "禅道未配置"}
|
|||
|
|
|
|||
|
|
result = self._request("PUT", f"/bugs/{issue_id}", json_body={"status": status})
|
|||
|
|
return {
|
|||
|
|
"success": result["success"],
|
|||
|
|
"data": result.get("data") if result["success"] else result.get("raw") or result.get("message"),
|
|||
|
|
"message": result.get("message", ""),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
# 全局单例
|
|||
|
|
_service: ZentaoService | None = None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def get_zentao_service() -> ZentaoService:
|
|||
|
|
global _service
|
|||
|
|
if _service is None:
|
|||
|
|
_service = ZentaoService()
|
|||
|
|
return _service
|