SHA256
forked from course-team/tjhlp-gitea
initial commit
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
"""同济大学高级语言程序设计课程 Gitea 答疑平台管理工具"""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,24 @@
|
||||
"""CLI 主入口: 注册所有子命令"""
|
||||
|
||||
import typer
|
||||
|
||||
from tjhlp.commands import labels, notify, orgs, repos, setup, stats, users, webhooks
|
||||
|
||||
app = typer.Typer(
|
||||
name="tjhlp",
|
||||
help="同济大学高级语言程序设计课程 Gitea 答疑平台管理工具",
|
||||
no_args_is_help=True,
|
||||
)
|
||||
|
||||
app.add_typer(setup.app, name="setup", help="初始化与环境配置")
|
||||
app.add_typer(users.app, name="users", help="用户管理")
|
||||
app.add_typer(orgs.app, name="orgs", help="组织与团队管理")
|
||||
app.add_typer(repos.app, name="repos", help="仓库管理")
|
||||
app.add_typer(webhooks.app, name="webhooks", help="Webhook 管理")
|
||||
app.add_typer(labels.app, name="labels", help="Label 管理")
|
||||
app.add_typer(stats.app, name="stats", help="Issue 统计")
|
||||
app.add_typer(notify.app, name="notify", help="邮件通知")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app()
|
||||
@@ -0,0 +1,393 @@
|
||||
"""Gitea REST API 客户端封装"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from rich.console import Console
|
||||
|
||||
from tjhlp.config import GiteaConfig
|
||||
from tjhlp.models import (
|
||||
GiteaLabel,
|
||||
GiteaOrg,
|
||||
GiteaRepo,
|
||||
GiteaTeam,
|
||||
GiteaUser,
|
||||
GiteaWebhook,
|
||||
)
|
||||
|
||||
console = Console()
|
||||
|
||||
|
||||
class GiteaClientError(Exception):
|
||||
"""Gitea API 调用异常"""
|
||||
|
||||
def __init__(self, status_code: int, message: str, url: str = ""):
|
||||
self.status_code = status_code
|
||||
self.message = message
|
||||
self.url = url
|
||||
super().__init__(f"[{status_code}] {url}: {message}")
|
||||
|
||||
|
||||
class GiteaClient:
|
||||
"""Gitea REST API 客户端
|
||||
|
||||
自动处理认证、分页和错误。
|
||||
"""
|
||||
|
||||
def __init__(self, config: GiteaConfig) -> None:
|
||||
self.base_url = str(config.url).rstrip("/") + "/api/v1"
|
||||
self._client = httpx.Client(
|
||||
base_url=self.base_url,
|
||||
headers={
|
||||
"Authorization": f"token {config.token.get_secret_value()}",
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
timeout=30.0,
|
||||
)
|
||||
|
||||
def close(self) -> None:
|
||||
self._client.close()
|
||||
|
||||
def __enter__(self) -> GiteaClient:
|
||||
return self
|
||||
|
||||
def __exit__(self, *args: object) -> None:
|
||||
self.close()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 底层请求
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _request(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
json: dict[str, Any] | None = None,
|
||||
params: dict[str, Any] | None = None,
|
||||
) -> httpx.Response:
|
||||
resp = self._client.request(method, path, json=json, params=params)
|
||||
if resp.status_code >= 400:
|
||||
try:
|
||||
detail = resp.json().get("message", resp.text)
|
||||
except Exception:
|
||||
detail = resp.text
|
||||
raise GiteaClientError(resp.status_code, detail, path)
|
||||
return resp
|
||||
|
||||
def _get(self, path: str, **params: Any) -> Any:
|
||||
return self._request("GET", path, params=params or None).json()
|
||||
|
||||
def _post(self, path: str, json: dict[str, Any] | None = None) -> Any:
|
||||
resp = self._request("POST", path, json=json)
|
||||
if resp.status_code == 204:
|
||||
return None
|
||||
return resp.json()
|
||||
|
||||
def _delete(self, path: str) -> None:
|
||||
self._request("DELETE", path)
|
||||
|
||||
def _patch(self, path: str, json: dict[str, Any] | None = None) -> Any:
|
||||
resp = self._request("PATCH", path, json=json)
|
||||
if resp.status_code == 204:
|
||||
return None
|
||||
return resp.json()
|
||||
|
||||
def _put(self, path: str, json: dict[str, Any] | None = None) -> None:
|
||||
self._request("PUT", path, json=json)
|
||||
|
||||
def _get_paginated(self, path: str, limit: int = 50, **params: Any) -> list[Any]:
|
||||
"""自动分页获取所有结果"""
|
||||
results: list[Any] = []
|
||||
page = 1
|
||||
while True:
|
||||
p = {**params, "page": page, "limit": limit}
|
||||
data = self._get(path, **p)
|
||||
if not data:
|
||||
break
|
||||
results.extend(data)
|
||||
if len(data) < limit:
|
||||
break
|
||||
page += 1
|
||||
return results
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 版本
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_version(self) -> str:
|
||||
return self._get("/version")["version"]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 用户管理
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def create_user(
|
||||
self,
|
||||
username: str,
|
||||
password: str,
|
||||
email: str,
|
||||
full_name: str = "",
|
||||
*,
|
||||
must_change_password: bool = True,
|
||||
) -> GiteaUser:
|
||||
data = self._post(
|
||||
"/admin/users",
|
||||
json={
|
||||
"username": username,
|
||||
"password": password,
|
||||
"email": email,
|
||||
"full_name": full_name,
|
||||
"must_change_password": must_change_password,
|
||||
"visibility": "limited",
|
||||
},
|
||||
)
|
||||
return GiteaUser(**data)
|
||||
|
||||
def list_users(self) -> list[GiteaUser]:
|
||||
data = self._get_paginated("/admin/users")
|
||||
return [GiteaUser(**u) for u in data]
|
||||
|
||||
def get_user(self, username: str) -> GiteaUser | None:
|
||||
try:
|
||||
data = self._get(f"/users/{username}")
|
||||
return GiteaUser(**data)
|
||||
except GiteaClientError as e:
|
||||
if e.status_code == 404:
|
||||
return None
|
||||
raise
|
||||
|
||||
def delete_user(self, username: str) -> None:
|
||||
self._delete(f"/admin/users/{username}")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 组织管理
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def create_org(
|
||||
self,
|
||||
name: str,
|
||||
full_name: str = "",
|
||||
description: str = "",
|
||||
*,
|
||||
visibility: str = "public",
|
||||
) -> GiteaOrg:
|
||||
data = self._post(
|
||||
"/orgs",
|
||||
json={
|
||||
"username": name,
|
||||
"full_name": full_name,
|
||||
"description": description,
|
||||
"visibility": visibility,
|
||||
},
|
||||
)
|
||||
return GiteaOrg(**data)
|
||||
|
||||
def get_org(self, name: str) -> GiteaOrg | None:
|
||||
try:
|
||||
data = self._get(f"/orgs/{name}")
|
||||
return GiteaOrg(**data)
|
||||
except GiteaClientError as e:
|
||||
if e.status_code == 404:
|
||||
return None
|
||||
raise
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 团队管理
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def create_team(
|
||||
self,
|
||||
org: str,
|
||||
name: str,
|
||||
*,
|
||||
permission: str = "read",
|
||||
units: list[str] | None = None,
|
||||
can_create_org_repo: bool = False,
|
||||
) -> GiteaTeam:
|
||||
if units is None:
|
||||
units = ["repo.code", "repo.issues"]
|
||||
data = self._post(
|
||||
f"/orgs/{org}/teams",
|
||||
json={
|
||||
"name": name,
|
||||
"permission": permission,
|
||||
"units": units,
|
||||
"can_create_org_repo": can_create_org_repo,
|
||||
},
|
||||
)
|
||||
return GiteaTeam(**data)
|
||||
|
||||
def list_teams(self, org: str) -> list[GiteaTeam]:
|
||||
data = self._get_paginated(f"/orgs/{org}/teams")
|
||||
return [GiteaTeam(**t) for t in data]
|
||||
|
||||
def get_team_by_name(self, org: str, team_name: str) -> GiteaTeam | None:
|
||||
teams = self.list_teams(org)
|
||||
for t in teams:
|
||||
if t.name == team_name:
|
||||
return t
|
||||
return None
|
||||
|
||||
def add_team_member(self, team_id: int, username: str) -> None:
|
||||
self._put(f"/teams/{team_id}/members/{username}")
|
||||
|
||||
def add_team_repo(self, team_id: int, org: str, repo: str) -> None:
|
||||
self._put(f"/teams/{team_id}/repos/{org}/{repo}")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 仓库管理
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def create_org_repo(
|
||||
self,
|
||||
org: str,
|
||||
name: str,
|
||||
*,
|
||||
description: str = "",
|
||||
private: bool = False,
|
||||
auto_init: bool = True,
|
||||
default_branch: str = "main",
|
||||
) -> GiteaRepo:
|
||||
data = self._post(
|
||||
f"/orgs/{org}/repos",
|
||||
json={
|
||||
"name": name,
|
||||
"description": description,
|
||||
"private": private,
|
||||
"auto_init": auto_init,
|
||||
"default_branch": default_branch,
|
||||
},
|
||||
)
|
||||
return GiteaRepo(**data)
|
||||
|
||||
def get_repo(self, owner: str, repo: str) -> GiteaRepo | None:
|
||||
try:
|
||||
data = self._get(f"/repos/{owner}/{repo}")
|
||||
return GiteaRepo(**data)
|
||||
except GiteaClientError as e:
|
||||
if e.status_code == 404:
|
||||
return None
|
||||
raise
|
||||
|
||||
def update_repo(self, owner: str, repo: str, **kwargs: Any) -> GiteaRepo:
|
||||
data = self._patch(f"/repos/{owner}/{repo}", json=kwargs)
|
||||
return GiteaRepo(**data)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 仓库文件操作(用于推送 Issue Templates)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def create_or_update_file(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
filepath: str,
|
||||
content_b64: str,
|
||||
message: str,
|
||||
*,
|
||||
sha: str | None = None,
|
||||
branch: str = "main",
|
||||
) -> dict[str, Any]:
|
||||
"""创建或更新仓库中的文件"""
|
||||
json_body: dict[str, Any] = {
|
||||
"content": content_b64,
|
||||
"message": message,
|
||||
"branch": branch,
|
||||
}
|
||||
if sha:
|
||||
json_body["sha"] = sha
|
||||
return self._request(
|
||||
"PUT" if sha else "POST",
|
||||
f"/repos/{owner}/{repo}/contents/{filepath}",
|
||||
json=json_body,
|
||||
).json()
|
||||
|
||||
def get_file_contents(
|
||||
self, owner: str, repo: str, filepath: str, *, ref: str = "main"
|
||||
) -> dict[str, Any] | None:
|
||||
"""获取文件内容(含 sha)"""
|
||||
try:
|
||||
return self._get(f"/repos/{owner}/{repo}/contents/{filepath}", ref=ref)
|
||||
except GiteaClientError as e:
|
||||
if e.status_code == 404:
|
||||
return None
|
||||
raise
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Label 管理
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def create_label(
|
||||
self, owner: str, repo: str, name: str, color: str, description: str = ""
|
||||
) -> GiteaLabel:
|
||||
data = self._post(
|
||||
f"/repos/{owner}/{repo}/labels",
|
||||
json={"name": name, "color": color, "description": description},
|
||||
)
|
||||
return GiteaLabel(**data)
|
||||
|
||||
def list_labels(self, owner: str, repo: str) -> list[GiteaLabel]:
|
||||
data = self._get_paginated(f"/repos/{owner}/{repo}/labels")
|
||||
return [GiteaLabel(**lbl) for lbl in data]
|
||||
|
||||
def delete_label(self, owner: str, repo: str, label_id: int) -> None:
|
||||
self._delete(f"/repos/{owner}/{repo}/labels/{label_id}")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Webhook 管理
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def create_webhook(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
target_url: str,
|
||||
*,
|
||||
secret: str = "",
|
||||
events: list[str] | None = None,
|
||||
content_type: str = "json",
|
||||
active: bool = True,
|
||||
) -> GiteaWebhook:
|
||||
if events is None:
|
||||
events = ["issues", "issue_comment"]
|
||||
data = self._post(
|
||||
f"/repos/{owner}/{repo}/hooks",
|
||||
json={
|
||||
"type": "gitea",
|
||||
"active": active,
|
||||
"config": {
|
||||
"url": target_url,
|
||||
"content_type": content_type,
|
||||
"secret": secret,
|
||||
},
|
||||
"events": events,
|
||||
},
|
||||
)
|
||||
return GiteaWebhook(**data)
|
||||
|
||||
def list_webhooks(self, owner: str, repo: str) -> list[GiteaWebhook]:
|
||||
data = self._get_paginated(f"/repos/{owner}/{repo}/hooks")
|
||||
return [GiteaWebhook(**w) for w in data]
|
||||
|
||||
def delete_webhook(self, owner: str, repo: str, hook_id: int) -> None:
|
||||
self._delete(f"/repos/{owner}/{repo}/hooks/{hook_id}")
|
||||
|
||||
def test_webhook(self, owner: str, repo: str, hook_id: int) -> None:
|
||||
self._post(f"/repos/{owner}/{repo}/hooks/{hook_id}/tests")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Issue 管理(用于统计)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def list_issues(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
*,
|
||||
state: str = "all",
|
||||
) -> list[dict[str, Any]]:
|
||||
return self._get_paginated(f"/repos/{owner}/{repo}/issues", state=state, type="issues")
|
||||
@@ -0,0 +1,67 @@
|
||||
"""labels 命令: Label 管理"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
|
||||
from tjhlp.client import GiteaClient, GiteaClientError
|
||||
from tjhlp.config import get_gitea_config
|
||||
from tjhlp.utils import parse_repo
|
||||
from tjhlp.utils import sync_labels as _sync_labels
|
||||
|
||||
app = typer.Typer(no_args_is_help=True)
|
||||
console = Console()
|
||||
|
||||
|
||||
@app.command("sync")
|
||||
def sync_labels(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
remove_extra: bool = typer.Option(False, "--remove-extra", help="删除不在预定义集合中的 Label"),
|
||||
) -> None:
|
||||
"""将预定义 Label 同步到指定仓库"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
cfg = get_gitea_config()
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
created = _sync_labels(client, org_name, repo_name, cfg)
|
||||
console.print(f" 新增 {created} 个 Label")
|
||||
|
||||
if remove_extra:
|
||||
existing_labels = client.list_labels(org_name, repo_name)
|
||||
predefined_names = {lbl.name for lbl in cfg.labels}
|
||||
removed = 0
|
||||
for lbl in existing_labels:
|
||||
if lbl.name not in predefined_names:
|
||||
try:
|
||||
client.delete_label(org_name, repo_name, lbl.id)
|
||||
console.print(f" [red]删除[/red] {lbl.name}")
|
||||
removed += 1
|
||||
except GiteaClientError as e:
|
||||
console.print(f" [red]删除失败[/red] {lbl.name}: {e.message}")
|
||||
console.print(f" 删除 {removed} 个多余 Label")
|
||||
|
||||
|
||||
@app.command("list")
|
||||
def list_labels(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
) -> None:
|
||||
"""列出仓库的所有 Label"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
cfg = get_gitea_config()
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
labels = client.list_labels(org_name, repo_name)
|
||||
if not labels:
|
||||
console.print("没有 Label")
|
||||
return
|
||||
|
||||
table = Table(title=f"{repo} 的 Labels")
|
||||
table.add_column("ID", style="dim")
|
||||
table.add_column("名称")
|
||||
table.add_column("颜色")
|
||||
table.add_column("描述")
|
||||
for lbl in labels:
|
||||
table.add_row(str(lbl.id), lbl.name, lbl.color, lbl.description)
|
||||
console.print(table)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""notify 命令: 通过 SMTP 发送账号凭据邮件"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import smtplib
|
||||
import ssl
|
||||
import time
|
||||
from email.mime.text import MIMEText
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.panel import Panel
|
||||
|
||||
from tjhlp.config import get_gitea_config, get_smtp_config
|
||||
from tjhlp.models import CredentialRecord
|
||||
|
||||
app = typer.Typer(no_args_is_help=True)
|
||||
console = Console()
|
||||
|
||||
|
||||
def _build_email_text(cred: CredentialRecord, gitea_url: str) -> str:
|
||||
"""构建纯文本邮件正文"""
|
||||
return f"""\
|
||||
同济大学高级语言程序设计 - 答疑平台账号
|
||||
{"=" * 40}
|
||||
|
||||
{cred.name}同学/老师, 你好!
|
||||
|
||||
你的课程答疑平台账号已创建, 请使用以下信息登录:
|
||||
|
||||
平台地址: {gitea_url}
|
||||
用户名: {cred.username}
|
||||
初始密码: {cred.password}
|
||||
|
||||
首次登录后请立即修改密码。
|
||||
如有问题, 请联系助教。
|
||||
"""
|
||||
|
||||
|
||||
def _read_credentials_csv(filepath: Path) -> list[CredentialRecord]:
|
||||
"""读取凭据 CSV 文件"""
|
||||
records: list[CredentialRecord] = []
|
||||
with open(filepath, encoding="utf-8-sig") as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
records.append(CredentialRecord.model_validate(row))
|
||||
return records
|
||||
|
||||
|
||||
@app.command("send-credentials")
|
||||
def send_credentials(
|
||||
file: Path = typer.Option(..., "--file", "-f", help="凭据 CSV 文件路径(由 users create 生成)"),
|
||||
dry_run: bool = typer.Option(False, "--dry-run", help="仅预览邮件内容, 不实际发送"),
|
||||
batch_size: int = typer.Option(
|
||||
10, "--batch-size", help="每批发送数量, 批次间暂停 2 秒(避免触发 SMTP 限制)"
|
||||
),
|
||||
) -> None:
|
||||
"""通过 SMTP 向同济邮箱发送账号密码邮件"""
|
||||
if not file.exists():
|
||||
console.print(f"[red]文件不存在: {file}[/red]")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
gitea_cfg = get_gitea_config()
|
||||
credentials = _read_credentials_csv(file)
|
||||
console.print(f"读取到 {len(credentials)} 条凭据记录")
|
||||
|
||||
if dry_run:
|
||||
# 预览第一封邮件
|
||||
if credentials:
|
||||
cred = credentials[0]
|
||||
text = _build_email_text(cred, str(gitea_cfg.url))
|
||||
console.print(Panel(text, title=f"邮件预览 -> {cred.email}", border_style="blue"))
|
||||
console.print(f"\n[yellow]dry-run 模式, 共 {len(credentials)} 封邮件待发送[/yellow]")
|
||||
return
|
||||
|
||||
smtp_cfg = get_smtp_config()
|
||||
from_addr = smtp_cfg.from_addr or smtp_cfg.user
|
||||
|
||||
stats = {"sent": 0, "failed": 0}
|
||||
|
||||
context = ssl.create_default_context()
|
||||
|
||||
try:
|
||||
with smtplib.SMTP_SSL(smtp_cfg.host, smtp_cfg.port, context=context) as server:
|
||||
server.login(smtp_cfg.user, smtp_cfg.password.get_secret_value())
|
||||
console.print(f"[green]已连接 SMTP 服务器 {smtp_cfg.host}[/green]")
|
||||
|
||||
for i, cred in enumerate(credentials, 1):
|
||||
msg = MIMEText(_build_email_text(cred, str(gitea_cfg.url)), "plain", "utf-8")
|
||||
msg["Subject"] = "同济大学高级语言程序设计 - 答疑平台账号信息"
|
||||
msg["From"] = from_addr
|
||||
msg["To"] = cred.email
|
||||
|
||||
try:
|
||||
server.send_message(msg)
|
||||
console.print(
|
||||
f" [{i}/{len(credentials)}] [green]已发送[/green] -> {cred.email}"
|
||||
)
|
||||
stats["sent"] += 1
|
||||
except Exception as e:
|
||||
console.print(
|
||||
f" [{i}/{len(credentials)}] [red]失败[/red] -> {cred.email}: {e}"
|
||||
)
|
||||
stats["failed"] += 1
|
||||
|
||||
# 按 batch_size 暂停, 避免触发 SMTP 速率限制
|
||||
if i % batch_size == 0 and i < len(credentials):
|
||||
console.print(f" [dim]已发送 {i} 封, 暂停 2 秒...[/dim]")
|
||||
time.sleep(2)
|
||||
|
||||
except Exception as e:
|
||||
console.print(f"[red]SMTP 连接失败: {e}[/red]")
|
||||
raise typer.Exit(code=1) from e
|
||||
|
||||
console.print(f"\n完成: 发送 {stats['sent']}, 失败 {stats['failed']}")
|
||||
@@ -0,0 +1,116 @@
|
||||
"""orgs 命令: 组织与团队管理"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
|
||||
from tjhlp.client import GiteaClient, GiteaClientError
|
||||
from tjhlp.config import get_gitea_config
|
||||
from tjhlp.models import MemberRecord
|
||||
|
||||
app = typer.Typer(no_args_is_help=True)
|
||||
console = Console()
|
||||
|
||||
|
||||
@app.command("create")
|
||||
def create_org(
|
||||
name: str = typer.Argument(help="组织名称(如 tjhlp-2025f)"),
|
||||
full_name: str = typer.Option("", "--full-name", help="组织全名"),
|
||||
description: str = typer.Option("课程答疑平台", "--desc", "-d", help="组织描述"),
|
||||
visibility: str = typer.Option("public", "--visibility", help="可见性: public/limited/private"),
|
||||
) -> None:
|
||||
"""创建课程组织"""
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
existing = client.get_org(name)
|
||||
if existing:
|
||||
console.print(f"[yellow]组织 {name} 已存在[/yellow]")
|
||||
return
|
||||
|
||||
org = client.create_org(
|
||||
name,
|
||||
full_name=full_name,
|
||||
description=description,
|
||||
visibility=visibility,
|
||||
)
|
||||
console.print(f"[green]组织 {org.name} 已创建[/green]")
|
||||
|
||||
|
||||
@app.command("create-team")
|
||||
def create_team(
|
||||
org: str = typer.Argument(help="组织名称"),
|
||||
team_name: str = typer.Argument(help="团队名称"),
|
||||
permission: str = typer.Option("read", "--permission", "-p", help="权限: read/write/admin"),
|
||||
) -> None:
|
||||
"""在组织下创建团队"""
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
existing = client.get_team_by_name(org, team_name)
|
||||
if existing:
|
||||
console.print(f"[yellow]团队 {team_name} 已存在[/yellow]")
|
||||
return
|
||||
|
||||
team = client.create_team(org, team_name, permission=permission)
|
||||
console.print(f"[green]团队 {team.name} 已创建(权限: {permission})[/green]")
|
||||
|
||||
|
||||
@app.command("add-members")
|
||||
def add_members(
|
||||
org: str = typer.Option(..., "--org", help="组织名称"),
|
||||
file: Path = typer.Option(..., "--file", "-f", help="成员名单 CSV 文件路径"),
|
||||
) -> None:
|
||||
"""根据 CSV 批量添加成员到组织对应团队(student -> students, ta -> ta)"""
|
||||
if not file.exists():
|
||||
console.print(f"[red]文件不存在: {file}[/red]")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
records: list[MemberRecord] = []
|
||||
with open(file, encoding="utf-8-sig") as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
records.append(MemberRecord.model_validate(row))
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
ta_team = client.get_team_by_name(org, "ta")
|
||||
students_team = client.get_team_by_name(org, "students")
|
||||
|
||||
if not ta_team or not students_team:
|
||||
console.print("[red]未找到 ta 或 students 团队, 请先执行 setup init[/red]")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
stats = {"added": 0, "failed": 0}
|
||||
for member in records:
|
||||
team = ta_team if member.role == "ta" else students_team
|
||||
try:
|
||||
client.add_team_member(team.id, member.username)
|
||||
console.print(f" [green]添加[/green] {member.username} -> {team.name}")
|
||||
stats["added"] += 1
|
||||
except GiteaClientError as e:
|
||||
console.print(f" [red]失败[/red] {member.username}: {e.message}")
|
||||
stats["failed"] += 1
|
||||
|
||||
console.print(f"\n完成: 添加 {stats['added']}, 失败 {stats['failed']}")
|
||||
|
||||
|
||||
@app.command("list-teams")
|
||||
def list_teams(
|
||||
org: str = typer.Argument(help="组织名称"),
|
||||
) -> None:
|
||||
"""列出组织下的所有团队"""
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
teams = client.list_teams(org)
|
||||
table = Table(title=f"组织 {org} 的团队")
|
||||
table.add_column("ID", style="dim")
|
||||
table.add_column("名称")
|
||||
table.add_column("权限")
|
||||
table.add_column("单元")
|
||||
for t in teams:
|
||||
table.add_row(str(t.id), t.name, t.permission, ", ".join(t.units))
|
||||
console.print(table)
|
||||
@@ -0,0 +1,146 @@
|
||||
"""repos 命令: 仓库管理"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
|
||||
from tjhlp.client import GiteaClient, GiteaClientError
|
||||
from tjhlp.config import get_gitea_config
|
||||
from tjhlp.utils import parse_repo, push_templates, sync_labels
|
||||
|
||||
app = typer.Typer(no_args_is_help=True)
|
||||
console = Console()
|
||||
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent.parent
|
||||
_TEMPLATES_DIR = _PROJECT_ROOT / "issue-templates"
|
||||
|
||||
|
||||
@app.command("create")
|
||||
def create_repo(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
description: str = typer.Option("", "--desc", "-d", help="仓库描述"),
|
||||
private: bool = typer.Option(False, "--private", help="是否设为私有"),
|
||||
) -> None:
|
||||
"""在组织下创建仓库"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
existing = client.get_repo(org_name, repo_name)
|
||||
if existing:
|
||||
console.print(f"[yellow]仓库 {repo} 已存在[/yellow]")
|
||||
return
|
||||
|
||||
result = client.create_org_repo(
|
||||
org_name,
|
||||
repo_name,
|
||||
description=description,
|
||||
private=private,
|
||||
auto_init=True,
|
||||
)
|
||||
console.print(f"[green]仓库已创建: {result.html_url}[/green]")
|
||||
|
||||
|
||||
@app.command("create-homework")
|
||||
def create_homework(
|
||||
org: str = typer.Option(..., "--org", help="组织名称"),
|
||||
number: int = typer.Option(..., "--number", "-n", help="作业编号(如 3 对应 hw03)"),
|
||||
description: str = typer.Option("", "--desc", "-d", help="作业描述"),
|
||||
webhook_url: str = typer.Option("", "--webhook-url", help="Webhook 通知地址"),
|
||||
webhook_secret: str = typer.Option("", "--webhook-secret", help="Webhook 密钥"),
|
||||
) -> None:
|
||||
"""创建作业仓库(自动命名 hwXX, 推送作业模板, 同步 Labels, 配置 Webhook)"""
|
||||
repo_name = f"hw{number:02d}"
|
||||
desc = description or f"作业 {number:02d}"
|
||||
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
# 创建仓库
|
||||
existing = client.get_repo(org, repo_name)
|
||||
if existing:
|
||||
console.print(f"[yellow]仓库 {org}/{repo_name} 已存在[/yellow]")
|
||||
else:
|
||||
client.create_org_repo(org, repo_name, description=desc, auto_init=True)
|
||||
console.print(f"[green]仓库 {org}/{repo_name} 已创建[/green]")
|
||||
|
||||
# 推送作业 Issue Templates
|
||||
console.print("\n推送 Issue Templates...")
|
||||
hw_tpl_dir = _TEMPLATES_DIR / "homework"
|
||||
n = push_templates(client, org, repo_name, hw_tpl_dir)
|
||||
console.print(f" 共推送 {n} 个模板文件")
|
||||
|
||||
# 同步 Labels
|
||||
console.print("\n同步 Labels...")
|
||||
created = sync_labels(client, org, repo_name, cfg)
|
||||
console.print(f" 新增 {created} 个 Label")
|
||||
|
||||
# 配置 Webhook
|
||||
if webhook_url:
|
||||
console.print("\n配置 Webhook...")
|
||||
client.create_webhook(
|
||||
org,
|
||||
repo_name,
|
||||
webhook_url,
|
||||
secret=webhook_secret,
|
||||
events=["issues", "issue_comment"],
|
||||
)
|
||||
console.print(f" [green]Webhook -> {webhook_url}[/green]")
|
||||
|
||||
# 添加到团队
|
||||
console.print("\n添加到团队...")
|
||||
for team_name in ("ta", "students"):
|
||||
team = client.get_team_by_name(org, team_name)
|
||||
if team:
|
||||
try:
|
||||
client.add_team_repo(team.id, org, repo_name)
|
||||
console.print(f" [green]{team_name} -> {repo_name}[/green]")
|
||||
except GiteaClientError as e:
|
||||
console.print(f" [yellow]{team_name}: {e.message}[/yellow]")
|
||||
|
||||
console.print(f"\n[bold green]作业仓库 {org}/{repo_name} 配置完成[/bold green]")
|
||||
|
||||
|
||||
@app.command("init-templates")
|
||||
def init_templates(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
template_type: str = typer.Option(
|
||||
"general", "--type", "-t", help="模板类型: general 或 homework"
|
||||
),
|
||||
) -> None:
|
||||
"""将 Issue Templates 推送到指定仓库"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
|
||||
tpl_dir = _TEMPLATES_DIR / template_type
|
||||
if not tpl_dir.exists():
|
||||
console.print(f"[red]模板类型 {template_type} 不存在(路径: {tpl_dir})[/red]")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
n = push_templates(client, org_name, repo_name, tpl_dir)
|
||||
console.print(f"\n共推送 {n} 个模板文件到 {repo}")
|
||||
|
||||
|
||||
@app.command("configure")
|
||||
def configure_repo(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
disable_wiki: bool = typer.Option(True, help="禁用 Wiki"),
|
||||
disable_projects: bool = typer.Option(True, help="禁用 Projects"),
|
||||
disable_packages: bool = typer.Option(True, help="禁用 Packages"),
|
||||
) -> None:
|
||||
"""配置仓库设置(禁用不需要的功能)"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
client.update_repo(
|
||||
org_name,
|
||||
repo_name,
|
||||
has_wiki=not disable_wiki,
|
||||
has_projects=not disable_projects,
|
||||
has_packages=not disable_packages,
|
||||
)
|
||||
console.print(f"[green]仓库 {repo} 配置已更新[/green]")
|
||||
@@ -0,0 +1,141 @@
|
||||
"""setup 命令: 一键初始化课程答疑平台"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
|
||||
from tjhlp.client import GiteaClient, GiteaClientError
|
||||
from tjhlp.config import get_gitea_config
|
||||
from tjhlp.utils import push_templates, sync_labels
|
||||
|
||||
app = typer.Typer(no_args_is_help=True)
|
||||
console = Console()
|
||||
|
||||
# Issue Templates 目录(相对于项目根)
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent.parent
|
||||
_TEMPLATES_DIR = _PROJECT_ROOT / "issue-templates"
|
||||
|
||||
|
||||
@app.command()
|
||||
def init(
|
||||
org: str = typer.Option(..., "--org", help="组织名称(如 tjhlp-2025f)"),
|
||||
semester: str = typer.Option("", "--semester", help="学期标识(如 2025f), 默认从组织名推断"),
|
||||
webhook_url: str = typer.Option("", "--webhook-url", help="Webhook 通知地址"),
|
||||
webhook_secret: str = typer.Option("", "--webhook-secret", help="Webhook 密钥"),
|
||||
) -> None:
|
||||
"""一键初始化课程答疑平台: 创建组织、团队、general 仓库、Labels、Webhook"""
|
||||
cfg = get_gitea_config()
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
# 1. 检查连接
|
||||
version = client.get_version()
|
||||
console.print(f"[green]已连接 Gitea {version}[/green]")
|
||||
|
||||
# 2. 创建组织
|
||||
console.print(f"\n[bold]1. 创建组织 {org}[/bold]")
|
||||
existing_org = client.get_org(org)
|
||||
if existing_org:
|
||||
console.print(" [yellow]组织已存在, 跳过[/yellow]")
|
||||
else:
|
||||
sem = semester or org
|
||||
client.create_org(
|
||||
org,
|
||||
full_name=f"同济大学高级语言程序设计 ({sem})",
|
||||
description="课程答疑平台",
|
||||
visibility="public",
|
||||
)
|
||||
console.print(" [green]已创建[/green]")
|
||||
|
||||
# 3. 创建团队
|
||||
console.print("\n[bold]2. 创建团队[/bold]")
|
||||
for team_name, permission, units in [
|
||||
("ta", "write", ["repo.code", "repo.issues"]),
|
||||
("students", "read", ["repo.code", "repo.issues"]),
|
||||
]:
|
||||
existing_team = client.get_team_by_name(org, team_name)
|
||||
if existing_team:
|
||||
console.print(f" [yellow]{team_name} 团队已存在, 跳过[/yellow]")
|
||||
else:
|
||||
client.create_team(
|
||||
org,
|
||||
team_name,
|
||||
permission=permission,
|
||||
units=units,
|
||||
)
|
||||
console.print(f" [green]{team_name} 团队已创建 (权限: {permission})[/green]")
|
||||
|
||||
# 4. 创建 general 仓库
|
||||
console.print("\n[bold]3. 创建 general 仓库[/bold]")
|
||||
existing_repo = client.get_repo(org, "general")
|
||||
if existing_repo:
|
||||
console.print(" [yellow]general 仓库已存在, 跳过创建[/yellow]")
|
||||
else:
|
||||
client.create_org_repo(
|
||||
org,
|
||||
"general",
|
||||
description="课程答疑 - 一般性问题(课程内容、环境配置等)",
|
||||
private=False,
|
||||
auto_init=True,
|
||||
)
|
||||
console.print(" [green]已创建[/green]")
|
||||
|
||||
# 5. 推送 Issue Templates
|
||||
console.print("\n[bold]4. 推送 Issue Templates 到 general 仓库[/bold]")
|
||||
general_tpl_dir = _TEMPLATES_DIR / "general"
|
||||
if general_tpl_dir.exists():
|
||||
n = push_templates(client, org, "general", general_tpl_dir)
|
||||
console.print(f" 共推送 {n} 个模板文件")
|
||||
else:
|
||||
console.print(f" [red]模板目录不存在: {general_tpl_dir}[/red]")
|
||||
|
||||
# 6. 同步 Labels
|
||||
console.print("\n[bold]5. 同步预定义 Labels[/bold]")
|
||||
created = sync_labels(client, org, "general", cfg)
|
||||
existing_count = len(client.list_labels(org, "general"))
|
||||
console.print(f" 新增 {created} 个 Label, 当前共 {existing_count} 个")
|
||||
|
||||
# 7. 配置 Webhook
|
||||
if webhook_url:
|
||||
console.print("\n[bold]6. 配置 Webhook[/bold]")
|
||||
client.create_webhook(
|
||||
org,
|
||||
"general",
|
||||
webhook_url,
|
||||
secret=webhook_secret,
|
||||
events=["issues", "issue_comment"],
|
||||
)
|
||||
console.print(f" [green]Webhook 已配置 -> {webhook_url}[/green]")
|
||||
else:
|
||||
console.print("\n[bold]6. 跳过 Webhook 配置[/bold](未提供 --webhook-url)")
|
||||
|
||||
# 8. 将仓库添加到团队
|
||||
console.print("\n[bold]7. 将 general 仓库添加到团队[/bold]")
|
||||
for team_name in ("ta", "students"):
|
||||
team = client.get_team_by_name(org, team_name)
|
||||
if team:
|
||||
try:
|
||||
client.add_team_repo(team.id, org, "general")
|
||||
console.print(f" [green]{team_name} -> general[/green]")
|
||||
except GiteaClientError as e:
|
||||
console.print(f" [yellow]{team_name}: {e.message}[/yellow]")
|
||||
|
||||
console.print("\n[bold green]初始化完成![/bold green]")
|
||||
console.print(f"访问 {str(cfg.url).rstrip('/')}/{org}/general 查看仓库")
|
||||
|
||||
|
||||
@app.command()
|
||||
def status() -> None:
|
||||
"""检查 Gitea 实例连接状态"""
|
||||
cfg = get_gitea_config()
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
try:
|
||||
version = client.get_version()
|
||||
console.print(f"[green]Gitea {version} 运行正常[/green]")
|
||||
console.print(f"URL: {cfg.url}")
|
||||
except Exception as e:
|
||||
console.print(f"[red]连接失败: {e}[/red]")
|
||||
raise typer.Exit(code=1) from e
|
||||
@@ -0,0 +1,113 @@
|
||||
"""stats 命令: Issue 统计"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
|
||||
from tjhlp.client import GiteaClient
|
||||
from tjhlp.config import get_gitea_config
|
||||
from tjhlp.utils import compute_issue_stats, parse_repo
|
||||
|
||||
app = typer.Typer(no_args_is_help=True)
|
||||
console = Console()
|
||||
|
||||
|
||||
@app.command("summary")
|
||||
def summary(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
) -> None:
|
||||
"""显示 Issue 统计摘要"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
cfg = get_gitea_config()
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
issues = client.list_issues(org_name, repo_name, state="all")
|
||||
|
||||
if not issues:
|
||||
console.print("暂无 Issue")
|
||||
return
|
||||
|
||||
stats = compute_issue_stats(issues)
|
||||
|
||||
console.print(f"\n[bold]Issue 统计 - {repo}[/bold]\n")
|
||||
|
||||
overview = Table(show_header=False)
|
||||
overview.add_column("指标", style="bold")
|
||||
overview.add_column("数量")
|
||||
overview.add_row("总计", str(stats["total"]))
|
||||
overview.add_row("开启中", f"[green]{stats['open']}[/green]")
|
||||
overview.add_row("已关闭", f"[dim]{stats['closed']}[/dim]")
|
||||
overview.add_row("有回复", str(stats["with_comments"]))
|
||||
overview.add_row("待回复(开启且无回复)", f"[red]{stats['no_reply']}[/red]")
|
||||
console.print(overview)
|
||||
|
||||
if stats["label_counts"]:
|
||||
console.print("\n[bold]按 Label 分布[/bold]")
|
||||
label_table = Table()
|
||||
label_table.add_column("Label")
|
||||
label_table.add_column("数量", justify="right")
|
||||
for name, count in stats["label_counts"].most_common():
|
||||
label_table.add_row(name, str(count))
|
||||
console.print(label_table)
|
||||
|
||||
if stats["user_counts"]:
|
||||
console.print("\n[bold]提问排行 (Top 10)[/bold]")
|
||||
user_table = Table()
|
||||
user_table.add_column("用户")
|
||||
user_table.add_column("提问数", justify="right")
|
||||
for name, count in stats["user_counts"].most_common(10):
|
||||
user_table.add_row(name, str(count))
|
||||
console.print(user_table)
|
||||
|
||||
|
||||
@app.command("export")
|
||||
def export_stats(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
output: Path = typer.Option("issues_export.csv", "--output", "-o", help="导出文件路径"),
|
||||
) -> None:
|
||||
"""导出 Issue 数据到 CSV"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
cfg = get_gitea_config()
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
issues = client.list_issues(org_name, repo_name, state="all")
|
||||
|
||||
if not issues:
|
||||
console.print("暂无 Issue")
|
||||
return
|
||||
|
||||
with open(output, "w", newline="", encoding="utf-8") as f:
|
||||
writer = csv.DictWriter(
|
||||
f,
|
||||
fieldnames=[
|
||||
"number",
|
||||
"title",
|
||||
"state",
|
||||
"user",
|
||||
"labels",
|
||||
"comments",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
],
|
||||
)
|
||||
writer.writeheader()
|
||||
for issue in issues:
|
||||
writer.writerow(
|
||||
{
|
||||
"number": issue.get("number", ""),
|
||||
"title": issue.get("title", ""),
|
||||
"state": issue.get("state", ""),
|
||||
"user": issue.get("user", {}).get("login", ""),
|
||||
"labels": "; ".join(lbl.get("name", "") for lbl in issue.get("labels", [])),
|
||||
"comments": issue.get("comments", 0),
|
||||
"created_at": issue.get("created_at", ""),
|
||||
"updated_at": issue.get("updated_at", ""),
|
||||
}
|
||||
)
|
||||
|
||||
console.print(f"[green]已导出 {len(issues)} 条 Issue 到 {output}[/green]")
|
||||
@@ -0,0 +1,222 @@
|
||||
"""users 命令: 用户管理(批量创建/列出/删除)"""
|
||||
|
||||
import csv
|
||||
import secrets
|
||||
import string
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
|
||||
from tjhlp.client import GiteaClient, GiteaClientError
|
||||
from tjhlp.config import get_gitea_config
|
||||
from tjhlp.models import CredentialRecord, MemberRecord, MemberRole
|
||||
|
||||
app = typer.Typer(no_args_is_help=True)
|
||||
console = Console()
|
||||
|
||||
|
||||
def _generate_password(length: int = 12) -> str:
|
||||
"""生成随机密码: 至少包含大小写字母、数字和特殊字符"""
|
||||
if length < 8:
|
||||
length = 8
|
||||
alphabet = string.ascii_letters + string.digits + "!@#$%&*"
|
||||
while True:
|
||||
password = "".join(secrets.choice(alphabet) for _ in range(length))
|
||||
if (
|
||||
any(c.islower() for c in password)
|
||||
and any(c.isupper() for c in password)
|
||||
and any(c.isdigit() for c in password)
|
||||
and any(c in "!@#$%&*" for c in password)
|
||||
):
|
||||
return password
|
||||
|
||||
|
||||
def _read_members_csv(filepath: Path) -> list[MemberRecord]:
|
||||
"""读取 members CSV 文件"""
|
||||
records: list[MemberRecord] = []
|
||||
with open(filepath, encoding="utf-8-sig") as f:
|
||||
reader = csv.DictReader(f)
|
||||
for row in reader:
|
||||
records.append(MemberRecord.model_validate(row))
|
||||
return records
|
||||
|
||||
|
||||
@app.command("create")
|
||||
def create_users(
|
||||
file: Path = typer.Option(..., "--file", "-f", help="成员名单 CSV 文件路径"),
|
||||
org: str = typer.Option("", "--org", help="自动添加到指定组织的对应团队"),
|
||||
output: Path = typer.Option(None, "--output", "-o", help="凭据输出文件路径(默认自动生成)"),
|
||||
dry_run: bool = typer.Option(False, "--dry-run", help="仅预览, 不实际创建"),
|
||||
) -> None:
|
||||
"""从 CSV 批量创建用户账号, 生成随机密码并输出到凭据文件"""
|
||||
if not file.exists():
|
||||
console.print(f"[red]文件不存在: {file}[/red]")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
members = _read_members_csv(file)
|
||||
console.print(
|
||||
f"读取到 {len(members)} 条记录 "
|
||||
f"(学生: {sum(1 for m in members if m.role == MemberRole.STUDENT)}, "
|
||||
f"助教: {sum(1 for m in members if m.role == MemberRole.TA)})"
|
||||
)
|
||||
|
||||
if dry_run:
|
||||
table = Table(title="预览(dry-run)")
|
||||
table.add_column("ID")
|
||||
table.add_column("姓名")
|
||||
table.add_column("角色")
|
||||
table.add_column("邮箱")
|
||||
for m in members:
|
||||
table.add_row(m.id, m.name, m.role, m.email)
|
||||
console.print(table)
|
||||
return
|
||||
|
||||
credentials: list[CredentialRecord] = []
|
||||
stats = {"created": 0, "skipped": 0, "failed": 0}
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
# 获取团队 ID(如果指定了组织)
|
||||
ta_team = None
|
||||
students_team = None
|
||||
if org:
|
||||
ta_team = client.get_team_by_name(org, "ta")
|
||||
students_team = client.get_team_by_name(org, "students")
|
||||
|
||||
for member in members:
|
||||
# 检查用户是否已存在
|
||||
existing = client.get_user(member.username)
|
||||
if existing:
|
||||
console.print(f" [yellow]跳过[/yellow] {member.username}({member.name})- 已存在")
|
||||
stats["skipped"] += 1
|
||||
continue
|
||||
|
||||
password = _generate_password(cfg.password_length)
|
||||
|
||||
try:
|
||||
client.create_user(
|
||||
username=member.username,
|
||||
password=password,
|
||||
email=member.email,
|
||||
full_name=member.name,
|
||||
must_change_password=True,
|
||||
)
|
||||
console.print(f" [green]创建[/green] {member.username}({member.name})")
|
||||
stats["created"] += 1
|
||||
|
||||
credentials.append(
|
||||
CredentialRecord(
|
||||
id=member.id,
|
||||
name=member.name,
|
||||
role=member.role.value,
|
||||
username=member.username,
|
||||
password=password,
|
||||
email=member.email,
|
||||
)
|
||||
)
|
||||
|
||||
# 添加到团队
|
||||
if org:
|
||||
team = ta_team if member.role == MemberRole.TA else students_team
|
||||
if team:
|
||||
try:
|
||||
client.add_team_member(team.id, member.username)
|
||||
except GiteaClientError as e:
|
||||
console.print(f" [yellow]添加到团队失败: {e.message}[/yellow]")
|
||||
|
||||
except GiteaClientError as e:
|
||||
console.print(f" [red]失败[/red] {member.username}({member.name}): {e.message}")
|
||||
stats["failed"] += 1
|
||||
|
||||
# 写出凭据文件
|
||||
if credentials:
|
||||
if output is None:
|
||||
ts = datetime.now(tz=UTC).strftime("%Y%m%d_%H%M%S")
|
||||
output = Path(f"credentials_{ts}.csv")
|
||||
with open(output, "w", newline="", encoding="utf-8") as f:
|
||||
writer = csv.DictWriter(
|
||||
f,
|
||||
fieldnames=["id", "name", "role", "username", "password", "email"],
|
||||
)
|
||||
writer.writeheader()
|
||||
for cred in credentials:
|
||||
writer.writerow(cred.model_dump())
|
||||
console.print(f"\n凭据已保存到 [bold]{output}[/bold]")
|
||||
|
||||
console.print(
|
||||
f"\n完成: 创建 {stats['created']}, 跳过 {stats['skipped']}, 失败 {stats['failed']}"
|
||||
)
|
||||
|
||||
|
||||
@app.command("list")
|
||||
def list_users() -> None:
|
||||
"""列出 Gitea 上的所有用户"""
|
||||
cfg = get_gitea_config()
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
users = client.list_users()
|
||||
table = Table(title=f"用户列表(共 {len(users)} 个)")
|
||||
table.add_column("ID", style="dim")
|
||||
table.add_column("用户名")
|
||||
table.add_column("姓名")
|
||||
table.add_column("邮箱")
|
||||
table.add_column("管理员")
|
||||
table.add_column("活跃")
|
||||
for u in users:
|
||||
table.add_row(
|
||||
str(u.id),
|
||||
u.login,
|
||||
u.full_name,
|
||||
u.email,
|
||||
"[green]是[/green]" if u.is_admin else "",
|
||||
"[green]是[/green]" if u.active else "[red]否[/red]",
|
||||
)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command("delete")
|
||||
def delete_users(
|
||||
file: Path = typer.Option(..., "--file", "-f", help="成员名单 CSV 文件路径"),
|
||||
confirm: bool = typer.Option(False, "--yes", "-y", help="跳过确认提示"),
|
||||
) -> None:
|
||||
"""根据 CSV 名单批量删除用户(危险操作)"""
|
||||
if not file.exists():
|
||||
console.print(f"[red]文件不存在: {file}[/red]")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
members = _read_members_csv(file)
|
||||
console.print(f"[red bold]即将删除 {len(members)} 个用户![/red bold]")
|
||||
|
||||
if not confirm:
|
||||
typer.confirm("确认删除?此操作不可恢复", abort=True)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
stats = {"deleted": 0, "skipped": 0, "failed": 0}
|
||||
|
||||
with GiteaClient(cfg) as client:
|
||||
for member in members:
|
||||
existing = client.get_user(member.username)
|
||||
if not existing:
|
||||
console.print(f" [yellow]跳过[/yellow] {member.username} - 不存在")
|
||||
stats["skipped"] += 1
|
||||
continue
|
||||
|
||||
if existing.is_admin:
|
||||
console.print(f" [yellow]跳过[/yellow] {member.username} - 管理员账号")
|
||||
stats["skipped"] += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
client.delete_user(member.username)
|
||||
console.print(f" [red]已删除[/red] {member.username}({member.name})")
|
||||
stats["deleted"] += 1
|
||||
except GiteaClientError as e:
|
||||
console.print(f" [red]失败[/red] {member.username}: {e.message}")
|
||||
stats["failed"] += 1
|
||||
|
||||
console.print(
|
||||
f"\n完成: 删除 {stats['deleted']}, 跳过 {stats['skipped']}, 失败 {stats['failed']}"
|
||||
)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""webhooks 命令: Webhook 管理"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
|
||||
from tjhlp.client import GiteaClient
|
||||
from tjhlp.config import get_gitea_config
|
||||
from tjhlp.utils import parse_repo
|
||||
|
||||
app = typer.Typer(no_args_is_help=True)
|
||||
console = Console()
|
||||
|
||||
|
||||
@app.command("create")
|
||||
def create_webhook(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
url: str = typer.Option(..., "--url", help="Webhook 目标 URL"),
|
||||
secret: str = typer.Option("", "--secret", help="Webhook 密钥"),
|
||||
events: str = typer.Option("issues,issue_comment", "--events", help="触发事件, 逗号分隔"),
|
||||
) -> None:
|
||||
"""为仓库创建 Webhook"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
event_list = [e.strip() for e in events.split(",")]
|
||||
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
hook = client.create_webhook(
|
||||
org_name,
|
||||
repo_name,
|
||||
url,
|
||||
secret=secret,
|
||||
events=event_list,
|
||||
)
|
||||
console.print(f"[green]Webhook #{hook.id} 已创建 -> {url}[/green]")
|
||||
console.print(f" 事件: {', '.join(event_list)}")
|
||||
|
||||
|
||||
@app.command("list")
|
||||
def list_webhooks(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
) -> None:
|
||||
"""列出仓库的所有 Webhook"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
hooks = client.list_webhooks(org_name, repo_name)
|
||||
if not hooks:
|
||||
console.print("没有 Webhook")
|
||||
return
|
||||
|
||||
table = Table(title=f"{repo} 的 Webhook")
|
||||
table.add_column("ID", style="dim")
|
||||
table.add_column("类型")
|
||||
table.add_column("URL")
|
||||
table.add_column("事件")
|
||||
table.add_column("状态")
|
||||
for h in hooks:
|
||||
table.add_row(
|
||||
str(h.id),
|
||||
h.type,
|
||||
h.config.get("url", ""),
|
||||
", ".join(h.events),
|
||||
"[green]活跃[/green]" if h.active else "[red]禁用[/red]",
|
||||
)
|
||||
console.print(table)
|
||||
|
||||
|
||||
@app.command("test")
|
||||
def test_webhook(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
hook_id: int = typer.Argument(help="Webhook ID"),
|
||||
) -> None:
|
||||
"""测试指定 Webhook"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
client.test_webhook(org_name, repo_name, hook_id)
|
||||
console.print(f"[green]已向 Webhook #{hook_id} 发送测试请求[/green]")
|
||||
|
||||
|
||||
@app.command("delete")
|
||||
def delete_webhook(
|
||||
repo: str = typer.Argument(help="仓库名称, 格式为 org/repo"),
|
||||
hook_id: int = typer.Argument(help="Webhook ID"),
|
||||
) -> None:
|
||||
"""删除指定 Webhook"""
|
||||
org_name, repo_name = parse_repo(repo)
|
||||
|
||||
cfg = get_gitea_config()
|
||||
with GiteaClient(cfg) as client:
|
||||
client.delete_webhook(org_name, repo_name, hook_id)
|
||||
console.print(f"[red]Webhook #{hook_id} 已删除[/red]")
|
||||
@@ -0,0 +1,105 @@
|
||||
"""配置管理: Dynaconf 加载 + Pydantic 校验"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from dynaconf import Dynaconf
|
||||
from pydantic import AliasGenerator, BaseModel, ConfigDict, HttpUrl, SecretStr, field_validator
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dynaconf 实例(在 scripts/ 目录下查找配置文件)
|
||||
# ---------------------------------------------------------------------------
|
||||
_SCRIPTS_DIR = Path(__file__).resolve().parent.parent.parent
|
||||
|
||||
settings = Dynaconf(
|
||||
envvar_prefix="TJHLP",
|
||||
settings_files=[
|
||||
str(_SCRIPTS_DIR / "settings.toml"),
|
||||
str(_SCRIPTS_DIR / ".secrets.toml"),
|
||||
],
|
||||
environments=True,
|
||||
load_dotenv=True,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pydantic 强类型配置模型
|
||||
# ---------------------------------------------------------------------------
|
||||
class LabelDef(BaseModel):
|
||||
"""预定义 Label"""
|
||||
|
||||
name: str
|
||||
color: str
|
||||
description: str = ""
|
||||
|
||||
@field_validator("color")
|
||||
@classmethod
|
||||
def color_must_be_hex(cls, v: str) -> str:
|
||||
v = v.lstrip("#")
|
||||
if len(v) not in (3, 6) or not all(c in "0123456789abcdefABCDEF" for c in v):
|
||||
raise ValueError(f"无效的颜色值: #{v}")
|
||||
return f"#{v}"
|
||||
|
||||
|
||||
class GiteaConfig(BaseModel):
|
||||
"""Gitea 连接配置"""
|
||||
|
||||
model_config = ConfigDict(
|
||||
alias_generator=AliasGenerator(validation_alias=str.upper),
|
||||
populate_by_name=True,
|
||||
)
|
||||
|
||||
url: HttpUrl
|
||||
token: SecretStr
|
||||
email_domain: str = "tongji.edu.cn"
|
||||
default_org: str = ""
|
||||
password_length: int = 16
|
||||
labels: list[LabelDef] = []
|
||||
|
||||
|
||||
class SmtpConfig(BaseModel):
|
||||
"""SMTP 邮件配置"""
|
||||
|
||||
model_config = ConfigDict(
|
||||
alias_generator=AliasGenerator(validation_alias=str.upper),
|
||||
populate_by_name=True,
|
||||
)
|
||||
|
||||
host: str
|
||||
port: int = 465
|
||||
user: str
|
||||
password: SecretStr
|
||||
from_addr: str = ""
|
||||
|
||||
|
||||
class Config(BaseModel):
|
||||
"""总配置模型"""
|
||||
|
||||
model_config = ConfigDict(
|
||||
alias_generator=AliasGenerator(
|
||||
validation_alias=str.upper,
|
||||
),
|
||||
populate_by_name=True,
|
||||
)
|
||||
|
||||
gitea: GiteaConfig
|
||||
smtp: SmtpConfig | None = None
|
||||
|
||||
|
||||
def get_config() -> Config:
|
||||
"""获取完整配置"""
|
||||
return Config.model_validate(settings.to_dict())
|
||||
|
||||
|
||||
def get_gitea_config() -> GiteaConfig:
|
||||
"""从 Dynaconf 加载并校验 Gitea 配置"""
|
||||
return get_config().gitea
|
||||
|
||||
|
||||
def get_smtp_config() -> SmtpConfig:
|
||||
"""从 Dynaconf 加载并校验 SMTP 配置"""
|
||||
cfg = get_config()
|
||||
if cfg.smtp is None:
|
||||
raise ValueError("SMTP 配置缺失, 请在 .secrets.toml 中配置")
|
||||
return cfg.smtp
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Pydantic 数据模型: 用于 CSV 解析、API 请求/响应"""
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
from pydantic import BaseModel, computed_field
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 枚举
|
||||
# ---------------------------------------------------------------------------
|
||||
class MemberRole(StrEnum):
|
||||
STUDENT = "student"
|
||||
TA = "ta"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# CSV 输入模型
|
||||
# ---------------------------------------------------------------------------
|
||||
class MemberRecord(BaseModel):
|
||||
"""members.csv 中的一行记录"""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
role: MemberRole
|
||||
|
||||
@computed_field
|
||||
@property
|
||||
def email(self) -> str:
|
||||
return f"{self.id}@tongji.edu.cn"
|
||||
|
||||
@computed_field
|
||||
@property
|
||||
def username(self) -> str:
|
||||
return self.id
|
||||
|
||||
|
||||
class CredentialRecord(BaseModel):
|
||||
"""生成的凭据记录(输出到 credentials CSV)"""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
role: str
|
||||
username: str
|
||||
password: str
|
||||
email: str
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Gitea API 响应模型(部分字段)
|
||||
# ---------------------------------------------------------------------------
|
||||
class GiteaUser(BaseModel):
|
||||
id: int
|
||||
login: str
|
||||
full_name: str = ""
|
||||
email: str = ""
|
||||
is_admin: bool = False
|
||||
active: bool = True
|
||||
|
||||
|
||||
class GiteaOrg(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
full_name: str = ""
|
||||
description: str = ""
|
||||
|
||||
|
||||
class GiteaTeam(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
permission: str = ""
|
||||
units: list[str] = []
|
||||
|
||||
|
||||
class GiteaRepo(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
full_name: str = ""
|
||||
description: str = ""
|
||||
private: bool = False
|
||||
html_url: str = ""
|
||||
|
||||
|
||||
class GiteaLabel(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
color: str
|
||||
description: str = ""
|
||||
|
||||
|
||||
class GiteaWebhook(BaseModel):
|
||||
id: int
|
||||
type: str
|
||||
active: bool = True
|
||||
config: dict = {}
|
||||
events: list[str] = []
|
||||
|
||||
|
||||
class GiteaIssue(BaseModel):
|
||||
id: int
|
||||
number: int
|
||||
title: str
|
||||
state: str = ""
|
||||
labels: list[GiteaLabel] = []
|
||||
comments: int = 0
|
||||
created_at: str = ""
|
||||
updated_at: str = ""
|
||||
user: GiteaUser | None = None
|
||||
@@ -0,0 +1,142 @@
|
||||
"""共享工具函数: 仓库名解析、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 推送
|
||||
# ---------------------------------------------------------------------------
|
||||
def push_templates(
|
||||
client: GiteaClient,
|
||||
org: str,
|
||||
repo: str,
|
||||
template_dir: Path,
|
||||
) -> 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}"
|
||||
content_b64 = base64.b64encode(filepath.read_bytes()).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,
|
||||
}
|
||||
Reference in New Issue
Block a user