Files
tjhlp-gitea/scripts/src/tjhlp/utils.py
T
admin 68fb567cb3 feat: Issue 模板引导链接改指课程官网, 平台地址改由 public_url 注入
- 两个 config.yaml 的 contact_links 从 example.com 换成真实入口:
  官网《学会提问》/ 课程官网 / 平台提问速查, 让答疑平台与官网互相导流
- 模板支持 {{BASE_URL}}/{{ORG}}/{{REPO}} 占位符, 推送时替换,
  换学期建新组织不用改模板; 未配置时保留占位符并告警而不是推坏链接
- scripts: 新增 gitea.public_url(对外地址, 与 CLI 用的 url 区分),
  utils.web_base_url()/render_template_placeholders() 及单元测试
2026-09-11 17:07:11 +08:00

176 lines
6.0 KiB
Python

"""共享工具函数: 仓库名解析、Issue Template 推送、Label 同步、统计计算"""
from __future__ import annotations
import base64
from collections import Counter
from pathlib import Path
from typing import Any
import typer
from rich.console import Console
from tjhlp.client import GiteaClient, GiteaClientError
from tjhlp.config import GiteaConfig
console = Console()
# ---------------------------------------------------------------------------
# 仓库名解析
# ---------------------------------------------------------------------------
def parse_repo(repo: str) -> tuple[str, str]:
"""将 'org/repo' 格式的字符串解析为 (org, repo) 元组。
格式不正确时打印错误并退出。
"""
parts = repo.split("/")
if len(parts) != 2 or not parts[0] or not parts[1]:
console.print("[red]仓库名称格式应为 org/repo[/red]")
raise typer.Exit(code=1)
return parts[0], parts[1]
# ---------------------------------------------------------------------------
# Issue Template 推送
# ---------------------------------------------------------------------------
# 模板占位符: 让 Issue Template 不必硬编码学期组织名/访问地址
# {{BASE_URL}} -> gitea.public_url(面向同学的地址)
# {{ORG}} / {{REPO}} -> 推送目标
TEMPLATE_PLACEHOLDERS = ("{{BASE_URL}}", "{{ORG}}", "{{REPO}}")
def web_base_url(cfg: GiteaConfig) -> str:
"""面向同学的平台访问地址: 优先 gitea.public_url, 否则退回 gitea.url。"""
return (cfg.public_url or str(cfg.url)).rstrip("/")
def render_template_placeholders(text: str, org: str, repo: str, web_base: str = "") -> str:
"""替换 Issue Template 中的占位符, 返回渲染后的文本。"""
base = (web_base or "").rstrip("/")
if base:
text = text.replace("{{BASE_URL}}", base)
text = text.replace("{{ORG}}", org).replace("{{REPO}}", repo)
left = [p for p in TEMPLATE_PLACEHOLDERS if p in text]
if left:
console.print(
f"[yellow]警告: 模板中仍有未替换的占位符 {', '.join(left)}"
f"(检查 settings.toml 的 gitea.public_url)[/yellow]"
)
return text
def push_templates(
client: GiteaClient,
org: str,
repo: str,
template_dir: Path,
web_base: str = "",
) -> int:
"""将本地 issue template 目录推送到远端仓库, 返回推送的文件数。"""
count = 0
gitea_dir = template_dir / ".gitea" / "ISSUE_TEMPLATE"
if not gitea_dir.exists():
console.print(f"[yellow]模板目录不存在: {gitea_dir}[/yellow]")
return 0
for filepath in sorted(gitea_dir.iterdir()):
if not filepath.is_file():
continue
remote_path = f".gitea/ISSUE_TEMPLATE/{filepath.name}"
text = render_template_placeholders(
filepath.read_text(encoding="utf-8"),
org=org,
repo=repo,
web_base=web_base,
)
content_b64 = base64.b64encode(text.encode("utf-8")).decode()
existing = client.get_file_contents(org, repo, remote_path)
if existing:
sha = existing.get("sha", "")
client.create_or_update_file(
org,
repo,
remote_path,
content_b64,
f"更新 Issue Template: {filepath.name}",
sha=sha,
)
console.print(f" [blue]更新[/blue] {remote_path}")
else:
client.create_or_update_file(
org,
repo,
remote_path,
content_b64,
f"添加 Issue Template: {filepath.name}",
)
console.print(f" [green]创建[/green] {remote_path}")
count += 1
return count
# ---------------------------------------------------------------------------
# Label 同步
# ---------------------------------------------------------------------------
def sync_labels(client: GiteaClient, org: str, repo: str, cfg: GiteaConfig) -> int:
"""将预定义 Label 同步到仓库, 返回新增数量。"""
existing = {lbl.name for lbl in client.list_labels(org, repo)}
created = 0
for lbl_def in cfg.labels:
if lbl_def.name in existing:
continue
try:
client.create_label(org, repo, lbl_def.name, lbl_def.color, lbl_def.description)
created += 1
except GiteaClientError as e:
console.print(f" [red]创建 Label {lbl_def.name} 失败: {e.message}[/red]")
return created
# ---------------------------------------------------------------------------
# Issue 统计计算(纯函数, 无外部依赖)
# ---------------------------------------------------------------------------
def compute_issue_stats(issues: list[dict[str, Any]]) -> dict[str, Any]:
"""从 Issue 列表中计算统计数据。
返回值结构:
{
"total": int,
"open": int,
"closed": int,
"with_comments": int,
"no_reply": int,
"label_counts": Counter,
"user_counts": Counter,
}
"""
total = len(issues)
open_count = sum(1 for i in issues if i.get("state") == "open")
closed_count = sum(1 for i in issues if i.get("state") == "closed")
with_comments = sum(1 for i in issues if i.get("comments", 0) > 0)
no_reply = sum(1 for i in issues if i.get("state") == "open" and i.get("comments", 0) == 0)
label_counter: Counter[str] = Counter()
for issue in issues:
for label in issue.get("labels", []):
label_counter[label.get("name", "unknown")] += 1
user_counter: Counter[str] = Counter()
for issue in issues:
user = issue.get("user")
if user:
user_counter[user.get("login", "unknown")] += 1
return {
"total": total,
"open": open_count,
"closed": closed_count,
"with_comments": with_comments,
"no_reply": no_reply,
"label_counts": label_counter,
"user_counts": user_counter,
}