SHA256
initial commit
This commit is contained in:
@@ -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]")
|
||||
Reference in New Issue
Block a user