Skip to content

Commit

Permalink
style: lint by st1020
Browse files Browse the repository at this point in the history
  • Loading branch information
MarleneJiang committed Sep 2, 2023
1 parent 9351739 commit 5e2e45d
Show file tree
Hide file tree
Showing 10 changed files with 135 additions and 150 deletions.
31 changes: 20 additions & 11 deletions .github/actions_scripts/file.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
"""添加信息:1. 获取对应json文件并解析 2. 查询是否有同名插件,若存在则覆盖,并更新时间 3. 否则添加至最后一行,并附上更新时间 4. 保存至文件."""
"""修改 JSON 文件。
1. 获取对应 JSON 文件并解析。
2. 查询是否有同名插件,若存在则覆盖,并更新时间。
3. 否则添加至最后一行,并附上更新时间。
4. 保存至文件。
"""
from __future__ import annotations

import json
Expand Down Expand Up @@ -28,13 +34,13 @@


def get_json() -> dict[str, Any]:
"""获取对应json文件并解析."""
"""获取对应 JSON 文件并解析。"""
with Path(type_info + "s.json").open(encoding="utf-8") as f:
return json.load(f)


def add_info(json_data: list[dict[str, str]], infos: dict[str, Any]) -> bool:
"""查询是否有同名插件,若存在则覆盖,并更新时间."""
"""查询是否有同名插件若存在则覆盖并更新时间"""
for i in json_data:
if i["name"] == name:
i["module_name"] = infos["module_name"]
Expand All @@ -56,8 +62,7 @@ def save_json(json_data: dict[str, Any]) -> None:
json.dump(json_data, f, ensure_ascii=False, indent=2)


def main() -> None:
"""添加信息:1. 获取对应json文件并解析 2. 查询是否有同名插件,若存在则覆盖,并更新时间 3. 否则添加至最后一行,并附上更新时间 4. 保存至文件."""
if __name__ == "__main__":
# 获取当前UTC时间的时间戳
current_time_utc = time.time()
# 转换为东八区时间
Expand All @@ -83,15 +88,19 @@ def main() -> None:
}
if add_info(data_list, info):
set_action_outputs(
{"result": "success", "output": "插件信息更新成功", "file_json": json.dumps(info)}
{
"result": "success",
"output": "插件信息更新成功",
"file_json": json.dumps(info),
}
)
else:
set_action_outputs(
{"result": "success", "output": "插件信息添加成功", "file_json": json.dumps(info)}
{
"result": "success",
"output": "插件信息添加成功",
"file_json": json.dumps(info),
}
)
json_data[type_info + "s"] = data_list
save_json(json_data)


if __name__ == "__main__":
main()
28 changes: 10 additions & 18 deletions .github/actions_scripts/parse.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
"""信息解析:1. 标题的type解析,如果不符合就报错 2. 提取name、module_name、pypi_name,如果不符合就报错 3. pypi_name在pip网站中检查,不存在则报错."""
"""信息解析。
1. 解析标题的 type,如果不符合就报错。
2. 提取 name、module_name、pypi_name,如果不符合就报错。
3. pypi_name 在 pip 网站中检查,不存在则报错。
"""
from __future__ import annotations

import os
import re
from typing import Any

from utils import Pypi, set_action_outputs
from utils import PyPi, set_action_outputs


def parse_title(title: str) -> dict[str, Any]:
"""Prase Title."""
"""解析标题。"""
pattern = r"\[(plugin|adapter|bot)\]:\s*(.+)"
match = re.match(pattern, title)
if match:
Expand All @@ -18,20 +23,11 @@ def parse_title(title: str) -> dict[str, Any]:
raise ValueError(msg)


def raise_value_error(msg: str) -> None:
"""Raise ValueError."""
raise ValueError(msg)


def main() -> None:
"""信息解析:1. 标题的type解析,如果不符合就报错 2. 提取name、module_name、pypi_name,如果不符合就报错 3. pypi_name在pip网站中检查,不存在则报错."""
if __name__ == "__main__":
title = os.environ["TITLE"]
pypi_name = os.environ["PYPI_NAME"]
try:
pypi = Pypi(pypi_name)
if pypi.check_pypi(pypi_name) is False:
msg = "输入的pypi_name存在问题"
raise_value_error(msg)
PyPi(pypi_name).check_pypi()
parsed = parse_title(title)
set_action_outputs(
{
Expand All @@ -43,7 +39,3 @@ def main() -> None:
)
except ValueError as e:
set_action_outputs({"result": "error", "output": str(e)})


if __name__ == "__main__":
main()
4 changes: 2 additions & 2 deletions .github/actions_scripts/plugin_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""."""
"""用于测试插件的脚本。"""
import sys

from alicebot.bot import Bot
Expand Down Expand Up @@ -39,7 +39,7 @@ def error_or_exception(self: Bot, message: str, exception: Exception) -> None:

@bot.bot_run_hook
async def bot_run_hook(bot: Bot) -> None:
"""在 Bot 启动后直接退出。."""
"""在 Bot 启动后直接退出。"""
if TYPE == "plugin":
bot.should_exit.set()
sys.exit(0)
Expand Down
28 changes: 15 additions & 13 deletions .github/actions_scripts/test.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
"""验证脚本能否正常运行."""
"""验证脚本能否正常运行"""
from __future__ import annotations

import importlib
import os
import subprocess

from utils import Pypi, set_action_outputs
from utils import PyPi, set_action_outputs

PYPI_NAME = os.environ["PYPI_NAME"]
MODULE_NAME = os.environ["MODULE_NAME"]
TYPE = os.environ["TYPE"]


def check_module(module_name: str) -> bool:
"""Check module name."""
import importlib

"""检查 module name。"""
if module_name == "null":
return False
if "-" in module_name:
Expand All @@ -30,17 +29,20 @@ def check_module(module_name: str) -> bool:


def alicebot_test() -> None:
"""验证插件是否能在 alicebot 中正常运行."""
"""验证插件是否能在 AliceBot 中正常运行"""
try:
# 要执行的 Python 脚本路径
python_script_path = ".github/actions_scripts/plugin_test.py"
# 整个命令
command = f"python {python_script_path} {MODULE_NAME} {TYPE}"
result = subprocess.run(
command, timeout=10, check=True, shell=True, capture_output=True) # noqa: S602
f"python {python_script_path} {MODULE_NAME} {TYPE}",
timeout=10,
check=True,
shell=True, # noqa: S602
capture_output=True,
)
if result.returncode != 0:
msg = f"脚本执行失败: {result.stdout}"
raise ValueError(msg) from None
raise ValueError(msg)
except subprocess.TimeoutExpired as e:
msg = f"脚本执行超时: {e.stdout}"
raise ValueError(msg) from e
Expand All @@ -52,18 +54,18 @@ def alicebot_test() -> None:
def get_meta_info() -> None:
"""获取模块的元信息."""
try:
pypi = Pypi(PYPI_NAME)
pypi = PyPi(PYPI_NAME)
data = pypi.get_info()
data["result"] = "success"
data["output"] = "获取module元信息成功"
data["output"] = "获取 module 元信息成功"
set_action_outputs(data)
except ValueError as e:
set_action_outputs({"result": "error", "output": str(e)})


if __name__ == "__main__":
if TYPE != "bot" and (check_module(MODULE_NAME) is False):
set_action_outputs({"result": "error", "output": "输入的module_name存在问题"})
set_action_outputs({"result": "error", "output": "输入的 module_name 存在问题"})
else:
try:
if TYPE != "bot":
Expand Down
74 changes: 34 additions & 40 deletions .github/actions_scripts/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Utility functions for GitHub Actions."""
"""内部使用的实用工具。"""
from __future__ import annotations

import os
Expand All @@ -9,79 +9,73 @@


def set_action_outputs(output_pairs: dict[str, str]) -> None:
"""Sets the GitHub Action outputs, with backwards compatibility for self-hosted runners without a GITHUB_OUTPUT environment file. Keyword arguments: output_pairs - Dictionary of outputs with values."""
"""设置 GitHub Action outputs"""
if "GITHUB_OUTPUT" in os.environ:
with Path(os.environ["GITHUB_OUTPUT"]).open(mode="a") as f:
for key, value in output_pairs.items():
f.write(f"{key}={value}\n")
else:
for key, value in output_pairs.items():
print(f"::set-output name={key}::{value}") # noqa: T201
print(f"::set-output name={key}::{value}")


class Pypi:
"""获取pypi info."""
class PyPi:
"""PyPi 工具类。"""

BASE_URL = "https://pypi.org/pypi"
CODE = 404
name = None
PYPI_BASE_URL = "https://pypi.org/pypi"

def __init__(self, name: str) -> None:
"""Init."""
self.name = name
self.data = self.get_response(name).get("info", {})
"""初始化。"""
self.name: str = name

def get_response(self, name: str) -> dict[str, Any]:
"""Request response from PyPi API."""
target_url = f"{self.BASE_URL}/{name}/json"
target_url = f"{self.PYPI_BASE_URL}/{self.name}/json"
response = requests.get(target_url, timeout=5)
if response.status_code == self.CODE:
msg = "pypi_name检查出错"
if response.status_code != requests.codes.ok:
msg = "pypi_name 检查出错"
raise ValueError(msg)
return response.json()

def get(self, key: str) -> str | None:
"""."""
if self.data == {}:
msg = "module pypi info为空"
res = response.json()
if not isinstance(res, dict) or "info" not in res or not res["info"]:
msg = "请求插件 PyPi 信息失败"
raise ValueError(msg)
return self.data.get(key, None)
self.data: dict[str, Any] = response.json()["info"]

def check_pypi(self, name: str) -> bool:
"""Check module filename for conflict."""
if name == "null":
return False
package_url = self.get("package_url")
if package_url is not None:
module_name = package_url.split("/")[-2]
return name.lower() == module_name.lower()
return False
def check_pypi(self) -> None:
"""检查 pypi_name。"""
msg = "输入的 pypi_name 存在问题"
if self.name == "null":
raise ValueError(msg)
package_url = self.data.get("package_url")
if package_url is None:
raise ValueError(msg)
module_name = package_url.split("/")[-2]
if self.name.lower() != module_name.lower():
raise ValueError(msg)

def get_info(self) -> dict[str, str]:
"""."""
name = self.get("name")
"""获取 PyPi 包信息"""
name = self.data.get("name")
if (name is None) or (name == ""):
msg = "模块名称获取失败"
raise ValueError(msg)
description = self.get("summary")
description = self.data.get("summary")
if (description is None) or (description == ""):
msg = "模块描述获取失败"
raise ValueError(msg)
author = self.get("author")
author = self.data.get("author")
if (author is None) or (author == ""):
email = self.get("author_email")
email = self.data.get("author_email")
if email is not None and "<" in email: # PDM发包问题
author = email.split("<")[0].strip()
else:
msg = "作者信息获取失败"
raise ValueError(msg)
license_info = self.get("license")
license_info = self.data.get("license")
if license_info is None:
license_info = ""
homepage = self.get("home_page")
homepage = self.data.get("home_page")
if homepage is None:
homepage = ""
tags = self.get("keywords")
tags = self.data.get("keywords")
if (tags is None) or (tags == ""):
msg = "标签信息获取失败"
raise ValueError(msg)
Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/templates/validation-failed.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# 自动审核失败
# 自动检查失败

:x: 验证失败,以下是错误原因

> [!IMPORTANT]
>
> {{ .validation_output }}
请修复问题并在本地确认一切正常后,再次触发验证,方法是在评论中输入 `/validate`
2 changes: 1 addition & 1 deletion .github/workflows/templates/validation-succeeded.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 自动审核成功
# 自动检查成功

:white_check_mark: 已验证通过,请等待人工审核。

Expand Down
Loading

0 comments on commit 5e2e45d

Please sign in to comment.