Skip to content

Commit

Permalink
refactor: 重构 remove 插件部分函数
Browse files Browse the repository at this point in the history
  • Loading branch information
BigOrangeQWQ committed Oct 29, 2024
1 parent 94e5d12 commit 7262ead
Show file tree
Hide file tree
Showing 10 changed files with 82 additions and 72 deletions.
14 changes: 13 additions & 1 deletion src/plugins/github/depends/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from nonebot.params import Depends

from src.plugins.github.models import GithubHandler, RepoInfo
from src.plugins.github.typing import IssuesEvent, PullRequestEvent
from src.plugins.github.typing import IssuesEvent, LabelsItems, PullRequestEvent
from src.plugins.github.utils import run_shell_command

from .utils import extract_issue_number_from_ref
Expand Down Expand Up @@ -46,6 +46,18 @@ def get_repo_info(event: PullRequestEvent | IssuesEvent) -> RepoInfo:
return RepoInfo(owner=repo.owner.login, repo=repo.name)


def get_name_by_labels(labels: LabelsItems = Depends(get_labels)) -> list[str]:
"""通过标签获取名称"""
label_names: list[str] = []
if not labels:
return label_names

for label in labels:
if label.name:
label_names.append(label.name)
return label_names


async def get_installation_id(
bot: GitHubBot, repo_info: RepoInfo = Depends(get_repo_info)
) -> int:
Expand Down
17 changes: 12 additions & 5 deletions src/plugins/github/plugins/publish/depends.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,23 @@
from nonebot.adapters.github import Bot
from nonebot.params import Depends

from src.plugins.github.depends import get_issue_title, get_labels, get_repo_info
from src.plugins.github.depends import (
get_issue_title,
get_name_by_labels,
get_repo_info,
)
from src.plugins.github.models import RepoInfo
from src.plugins.github.plugins.publish import utils
from src.plugins.github.typing import LabelsItems
from src.providers.validation.models import PublishType


def get_type_by_labels(labels: LabelsItems = Depends(get_labels)) -> PublishType | None:
"""通过标签获取类型"""
return utils.get_type_by_labels(labels)
def get_type_by_labels(
labels: list[str] = Depends(get_name_by_labels),
) -> PublishType | None:
for type in PublishType.members():
if type.value in labels:
return type
return None


def get_type_by_title(title: str = Depends(get_issue_title)) -> PublishType | None:
Expand Down
32 changes: 11 additions & 21 deletions src/plugins/github/plugins/publish/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from src.plugins.github.constants import ISSUE_FIELD_PATTERN, ISSUE_FIELD_TEMPLATE
from src.plugins.github.models import IssueHandler, RepoInfo
from src.plugins.github.models.github import GithubHandler
from src.plugins.github.typing import LabelsItems
from src.plugins.github.typing import PullRequestLabels
from src.plugins.github.utils import commit_message as _commit_message
from src.plugins.github.utils import dump_json, load_json, run_shell_command
from src.providers.models import RegistryUpdatePayload, to_store
Expand All @@ -33,36 +33,26 @@
Issue,
PullRequest,
PullRequestSimple,
PullRequestSimplePropLabelsItems,
)


def get_type_by_labels(
labels: LabelsItems | list["PullRequestSimplePropLabelsItems"],
) -> PublishType | None:
"""通过标签获取类型"""
if not labels:
return None

def get_type_by_labels(labels: PullRequestLabels) -> PublishType | None:
"""通过拉取请求的标签获取发布类型"""
for label in labels:
if isinstance(label, str):
continue
if label.name == PublishType.BOT.value:
return PublishType.BOT
if label.name == PublishType.PLUGIN.value:
return PublishType.PLUGIN
if label.name == PublishType.ADAPTER.value:
return PublishType.ADAPTER
for type in PublishType.members():
if label.name == type.value:
return type
return None


def get_type_by_title(title: str) -> PublishType | None:
"""通过标题获取类型"""
if title.startswith(f"{PublishType.BOT.value}:"):
return PublishType.BOT
if title.startswith(f"{PublishType.PLUGIN.value}:"):
return PublishType.PLUGIN
if title.startswith(f"{PublishType.ADAPTER.value}:"):
return PublishType.ADAPTER
for type in PublishType.members():
if title.startswith(f"{type.value}:"):
return type
return None


def get_type_by_commit_message(message: str) -> PublishType | None:
Expand Down
15 changes: 1 addition & 14 deletions src/plugins/github/plugins/remove/depends.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,6 @@
from nonebot.params import Depends

from src.plugins.github.depends import get_labels
from src.plugins.github.typing import LabelsItems


def get_name_by_labels(labels: LabelsItems = Depends(get_labels)) -> list[str]:
"""通过标签获取名称"""
label_names: list[str] = []
if not labels:
return label_names

for label in labels:
if label.name:
label_names.append(label.name)
return label_names
from src.plugins.github.depends import get_name_by_labels


def check_labels(labels: list[str] | str):
Expand Down
7 changes: 2 additions & 5 deletions src/plugins/github/plugins/remove/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,10 @@ async def render_comment(result: ValidationDict) -> str:
title = f"{result.type}: remove {result.name}"

template = env.get_template("comment.md.jinja")
return await template.render_async(
title=title, valid=result.valid, error=result.errors
)
return await template.render_async(title=title, valid=True, error=[])


async def render_error(exception: PydanticCustomError):
"""将错误转换成评论内容"""
title = "Error"
template = env.get_template("comment.md.jinja")
return await template.render_async(title=title, valid=False, error=exception)
return await template.render_async(title="Error", valid=False, error=exception)
21 changes: 15 additions & 6 deletions src/plugins/github/plugins/remove/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING

from nonebot import logger
from pydantic import BaseModel

from src.plugins.github import plugin_config
from src.plugins.github.depends.utils import extract_issue_number_from_ref
Expand All @@ -11,34 +12,42 @@
load_json,
run_shell_command,
)
from src.providers.validation.models import ValidationDict
from src.providers.validation.models import PublishType

from .constants import COMMIT_MESSAGE_PREFIX, PUBLISH_PATH, REMOVE_LABEL

if TYPE_CHECKING:
from githubkit.rest import PullRequest, PullRequestSimple


def update_file(remove_data: dict[str, Any]):
class RemoveInfo(BaseModel):
type: PublishType
name: str
homepage: str
author_id: int


def update_file(homepage: str):
"""删除对应的包储存在 registry 里的数据"""
logger.info("开始更新文件")

for path in PUBLISH_PATH.values():
data = load_json(path)

# 删除对应的数据
new_data = [item for item in data if item != remove_data]
new_data = [item for item in data if item.get("homepage") != homepage]

if data == new_data:
continue

# 如果数据发生变化则更新文件
dump_json(path, new_data)

logger.info(f"已更新 {path.name} 文件")


async def process_pull_reqeusts(
handler: IssueHandler, result: ValidationDict, branch_name: str, title: str
handler: IssueHandler, result: RemoveInfo, branch_name: str, title: str
):
"""
根据发布信息合法性创建拉取请求
Expand All @@ -48,7 +57,7 @@ async def process_pull_reqeusts(
# 切换分支
run_shell_command(["git", "switch", "-C", branch_name])
# 更新文件并提交更改
update_file(result.store_data)
update_file(result.homepage)
handler.commit_and_push(message, branch_name)
# 创建拉取请求
await handler.create_pull_request(
Expand Down
24 changes: 10 additions & 14 deletions src/plugins/github/plugins/remove/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,25 @@
from nonebot import logger
from pydantic_core import PydanticCustomError

from src.plugins.github.models import AuthorInfo
from src.plugins.github.utils import extract_publish_info_from_issue
from src.providers.validation.models import ValidationDict

from .constants import PUBLISH_PATH, REMOVE_HOMEPAGE_PATTERN
from .utils import load_json
from .utils import RemoveInfo, load_json


async def validate_author_info(issue: Issue) -> ValidationDict:
async def validate_author_info(issue: Issue) -> RemoveInfo:
"""
根据主页链接与作者信息找到对应的包的信息
"""

homepage = extract_publish_info_from_issue(
{"homepage": REMOVE_HOMEPAGE_PATTERN}, issue.body or ""
).get("homepage")
author = issue.user.login if issue.user else ""
author_id = issue.user.id if issue.user else 0
author_id = AuthorInfo.from_issue(issue).author_id

if homepage is None:
raise PydanticCustomError("not_homepage", "主页链接未填写")

for type, path in PUBLISH_PATH.items():
if not path.exists():
Expand All @@ -31,18 +33,12 @@ async def validate_author_info(issue: Issue) -> ValidationDict:
logger.info(f"找到匹配的 {type} 数据 {item}")

# author_id 暂时没有储存到数据里, 所以暂时不校验
if item.get("author") == author or (
item.get("author_id") is not None
and item.get("author_id") == author_id
):
return ValidationDict(
valid=True,
data=item,
if item.get("author_id") == author_id:
return RemoveInfo(
type=type,
name=item.get("name") or item.get("module_name") or "",
author=author,
homepage=homepage,
author_id=author_id,
errors=[],
)
raise PydanticCustomError("author_info", "作者信息不匹配")
raise PydanticCustomError("not_found", "没有包含对应主页链接的包")
14 changes: 11 additions & 3 deletions src/plugins/github/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from githubkit.rest import (
PullRequestPropLabelsItems,
PullRequestSimplePropLabelsItems,
WebhookIssueCommentCreatedPropIssueAllof0PropLabelsItems,
WebhookIssuesEditedPropIssuePropLabelsItems,
WebhookIssuesOpenedPropIssuePropLabelsItems,
Expand All @@ -25,11 +26,18 @@

PullRequestEvent: TypeAlias = PullRequestClosed | PullRequestReviewSubmitted

LabelsItems: TypeAlias = (
list[PullRequestPropLabelsItems]

PullRequestLabels: TypeAlias = (
list[PullRequestSimplePropLabelsItems]
| list[PullRequestPropLabelsItems]
| list[WebhookPullRequestReviewSubmittedPropPullRequestPropLabelsItems]
| Missing[list[WebhookIssuesOpenedPropIssuePropLabelsItems]]
)

IssueLabels: TypeAlias = (
Missing[list[WebhookIssuesOpenedPropIssuePropLabelsItems]]
| Missing[list[WebhookIssuesReopenedPropIssuePropLabelsItems]]
| Missing[list[WebhookIssuesEditedPropIssuePropLabelsItems]]
| list[WebhookIssueCommentCreatedPropIssueAllof0PropLabelsItems]
)

LabelsItems: TypeAlias = PullRequestLabels | IssueLabels
6 changes: 5 additions & 1 deletion src/providers/validation/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import abc
import json
from enum import Enum
from typing import Annotated, Any
from typing import Annotated, Any, Self

from pydantic import (
BaseModel,
Expand Down Expand Up @@ -45,6 +45,10 @@ class PublishType(Enum):
def __str__(self) -> str:
return self.value

@classmethod
def members(cls) -> list[Self]:
return list(cls.__members__.values())


class Tag(BaseModel):
"""标签"""
Expand Down
4 changes: 2 additions & 2 deletions tests/github/remove/process/test_remove_pull_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ async def test_remove_process_pull_request(

mock_subprocess_run = mocker.patch("subprocess.run")

mock_issue = MockIssue(body=generate_issue_body_remove()).as_mock(mocker)
mock_issue = MockIssue(body=generate_issue_body_remove(), number=76).as_mock(mocker)

mock_issues_resp = mocker.MagicMock()
mock_issues_resp.parsed_data = mock_issue
Expand Down Expand Up @@ -137,7 +137,7 @@ async def test_process_remove_pull_request_not_merged(

mock_subprocess_run = mocker.patch("subprocess.run")

mock_issue = MockIssue(body=generate_issue_body_remove()).as_mock(mocker)
mock_issue = MockIssue(body=generate_issue_body_remove(), number=76).as_mock(mocker)
mock_issues_resp = mocker.MagicMock()
mock_issues_resp.parsed_data = mock_issue

Expand Down

0 comments on commit 7262ead

Please sign in to comment.