Skip to content

Commit

Permalink
🎨 使用 ruff 替代 black 作为格式化程序
Browse files Browse the repository at this point in the history
  • Loading branch information
A-kirami committed Mar 26, 2024
1 parent c246e0a commit b0b5edf
Show file tree
Hide file tree
Showing 17 changed files with 147 additions and 222 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ jobs:
- name: Run Ruff
uses: chartboost/ruff-action@v1
with:
version: 0.0.282
version: 0.3.4
10 changes: 3 additions & 7 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,10 @@ ci:
autoupdate_commit_msg: "⬆️ 自动更新预提交挂钩"
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.282
rev: v0.3.4
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
args: [--fix]
stages: [commit]

- repo: https://github.com/psf/black
rev: 23.7.0
hooks:
- id: black
- id: ruff-format
stages: [commit]
65 changes: 65 additions & 0 deletions .ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
[lint]
select = [
"F", # Pyflakes
"E", # pycodestyle error
"W", # pycodestyle warning
"I", # isort
"UP", # pyupgrade
"ASYNC", # fflake8-async
"S", # flake8-bandit
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"ISC", # flake8-implicit-str-concat
"PIE", # flake8-pie
"T20", # flake8-print
"PYI", # flake8-pyi
"PT", # flake8-pytest-style
"Q", # flake8-quotes
"RSE", # flake8-raise
"RET", # flake8-return
"SLOT", # flake8-slots
"SIM", # flake8-simplify
"TID", # flake8-tidy-imports
"TCH", # flake8-type-checking
"ARG", # flake8-unused-arguments
"PTH", # flake8-use-pathlib
"ERA", # eradicate
"PL", # Pylint
"TRY", # tryceratops
"PERF", # Perflint
# "FURB", # refurb
"RUF", # Ruff-specific rules
]
ignore = [
"E402", # module-import-not-at-top-of-file
"E501", # line-too-long
"B009", # get-attr-with-constant
"B010", # set-attr-with-constant
"PLC0414", # useless-import-alias
"PLR0913", # too-many-arguments
"TRY003", # raise-vanilla-args
"RUF001", # ambiguous-unicode-character-string
"RUF002", # ambiguous-unicode-character-docstring
"RUF003", # ambiguous-unicode-character-comment

# Avoid formatter conflicts, see https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules
"W191", # tab-indentation
"E111", # indentation-with-invalid-multiple
"E114", # indentation-with-invalid-multiple-comment
"E117", # over-indented
"D206", # indent-with-spaces
"D300", # triple-single-quotes
"Q000", # bad-quotes-inline-string
"Q001", # bad-quotes-multiline-string
"Q002", # bad-quotes-docstring
"Q003", # avoidable-escaped-quote
"COM812", # missing-trailing-comma
"COM819", # prohibited-trailing-comma
"ISC001", # single-line-implicit-string-concatenation
"ISC002", # multi-line-implicit-string-concatenation
]
unfixable = [
"F401", # unused-import
"F841", # unused-variable
"ERA001", # commented-out-code
]
6 changes: 2 additions & 4 deletions kirami/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,15 +139,13 @@ def get_asgi() -> Any:


@overload
def get_bot(self_id: str | None = None, raise_error: Literal[True] = True) -> Bot:
...
def get_bot(self_id: str | None = None, raise_error: Literal[True] = True) -> Bot: ...


@overload
def get_bot(
self_id: str | None = None, raise_error: Literal[False] = False
) -> Bot | None:
...
) -> Bot | None: ...


def get_bot(self_id: str | None = None, raise_error: bool = True) -> Bot | None:
Expand Down
4 changes: 1 addition & 3 deletions kirami/config/config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""本模块定义了 KiramiBot 运行所需的配置项"""


from collections.abc import KeysView, Mapping
from datetime import timedelta
from ipaddress import IPv4Address
Expand Down Expand Up @@ -225,8 +224,7 @@ class Config:

if TYPE_CHECKING:

def __getattr__(self, name: str) -> Any:
...
def __getattr__(self, name: str) -> Any: ...


class KiramiConfig(BaseConfig):
Expand Down
Empty file removed kirami/database/models/__init__.py
Empty file.
6 changes: 0 additions & 6 deletions kirami/matcher.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,6 @@ def on_time(
[apscheduler.triggers.cron](https://apscheduler.readthedocs.io/en/3.x/modules/triggers/cron.html#module-apscheduler.triggers.cron)
"""
...

@overload
def on_time(
Expand Down Expand Up @@ -436,7 +435,6 @@ def on_time(
[apscheduler.triggers.interval](https://apscheduler.readthedocs.io/en/3.x/modules/triggers/interval.html#module-apscheduler.triggers.interval)
"""
...

@overload
def on_time(
Expand Down Expand Up @@ -482,7 +480,6 @@ def on_time(
[apscheduler.triggers.date](https://apscheduler.readthedocs.io/en/3.x/modules/triggers/date.html#module-apscheduler.triggers.date)
"""
...

class CommandGroup(BaseCommandGroup):
basecmd: tuple[str, ...] = ...
Expand Down Expand Up @@ -870,7 +867,6 @@ class MatcherGroup(BaseMatcherGroup):
[apscheduler.triggers.cron](https://apscheduler.readthedocs.io/en/3.x/modules/triggers/cron.html#module-apscheduler.triggers.cron)
"""
...
@overload
def on_time(
self,
Expand Down Expand Up @@ -939,7 +935,6 @@ class MatcherGroup(BaseMatcherGroup):
[apscheduler.triggers.interval](https://apscheduler.readthedocs.io/en/3.x/modules/triggers/interval.html#module-apscheduler.triggers.interval)
"""
...
@overload
def on_time(
self,
Expand Down Expand Up @@ -985,4 +980,3 @@ class MatcherGroup(BaseMatcherGroup):
[apscheduler.triggers.date](https://apscheduler.readthedocs.io/en/3.x/modules/triggers/date.html#module-apscheduler.triggers.date)
"""
...
3 changes: 1 addition & 2 deletions kirami/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
class MessageResource(Protocol):
path: Path

def message(self, *args, **kwargs) -> "MessageSegment":
...
def message(self, *args, **kwargs) -> "MessageSegment": ...


def file_handle(
Expand Down
8 changes: 0 additions & 8 deletions kirami/message.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -66,31 +66,27 @@ class Message(BaseMessage):
### 参数
text: 文本内容
"""
...
@classmethod
def face(cls, id_: int) -> Self:
"""表情消息。
### 参数
id_: 表情 ID
"""
...
@classmethod
def at(cls, user_id: int | str) -> Self:
"""@ 某人消息。
### 参数
user_id: 要 @ 的用户 ID
"""
...
@classmethod
def reply(cls, id_: int) -> Self:
"""回复消息。
### 参数
id_: 回复的消息 ID
"""
...
@classmethod
def image(
cls,
Expand All @@ -116,23 +112,20 @@ class Message(BaseMessage):
### 异常
ReadFileError: 读取文件错误,不是一个有效的文件
"""
...
@classmethod
def anonymous(cls, ignore_failure: bool | None = None) -> Self:
"""匿名消息。
### 参数
ignore_failure: 无法匿名时是否继续发送。默认为 None
"""
...
@classmethod
def refer(cls, id_: int) -> Self:
"""合并转发引用消息。
### 参数
id_: 引用的消息 ID
"""
...
@classmethod
def node(cls, user_id: int | str, nickname: str, content: str | Self) -> Self:
"""合并转发节点消息。
Expand All @@ -144,4 +137,3 @@ class Message(BaseMessage):
content: 节点内容
"""
...
2 changes: 1 addition & 1 deletion kirami/service/access.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async def sync(self) -> None:
raise NotImplementedError

class Meta:
bson_encoders = {frozenset: list}
bson_encoders: ClassVar[dict] = {frozenset: list}


class Role(BaseAccess):
Expand Down
14 changes: 10 additions & 4 deletions kirami/service/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ async def event_scope_checker(
"""事件作用域检查"""

async def check_scope(source: Service | Ability, message_type: str) -> None:
if source.scope != "all" and message_type != source.scope:
if source.scope not in ("all", message_type):
raise IgnoredException("事件作用域不一致")

sources = [service, ability]
Expand All @@ -114,7 +114,9 @@ async def enabled_checker(
"""服务开关检查"""
if dissbj := ability.get_disabled_subjects(*subjects):
dissbj_str = ", ".join(repr(s) for s in dissbj)
raise IgnoredException(f'功能"{service.name}#{ability.name}"未启用: {dissbj_str}')
raise IgnoredException(
f'功能"{service.name}#{ability.name}"未启用: {dissbj_str}'
)
if dissbj := service.get_disabled_subjects(*subjects):
dissbj_str = ", ".join(repr(s) for s in dissbj)
raise IgnoredException(f'服务"{service.name}"未启用: {dissbj_str}')
Expand All @@ -127,7 +129,9 @@ async def role_checker(service: D_Service, ability: D_Ability, role: UserRole) -
return
if role.check(service.role.user):
return
raise IgnoredException(f"用户角色权限不足, 服务或功能至少需要{role.name}, 当前为{role.name}")
raise IgnoredException(
f"用户角色权限不足, 服务或功能至少需要{role.name}, 当前为{role.name}"
)


@register_checker
Expand All @@ -142,7 +146,9 @@ async def policy_checker(
return
if service.id in allowed:
return
raise IgnoredException(f"主体策略没有访问服务或功能的许可: {', '.join(repr(s) for s in subjects)}")
raise IgnoredException(
f"主体策略没有访问服务或功能的许可: {', '.join(repr(s) for s in subjects)}"
)


@register_checker
Expand Down
13 changes: 8 additions & 5 deletions kirami/service/limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ def get_scope_key(event: Event, scope: LimitScope = LimitScope.LOCAL) -> str | N
return f"{group_id}_{user_id}" if group_id else user_id


class LimiterInfo(TypedDict): ...


class Limiter(BaseModel, ABC):
scope: LimitScope = PField(default=LimitScope.LOCAL)
"""限制隔离范围"""
Expand All @@ -78,7 +81,7 @@ def check(self, key: str) -> bool:
raise NotImplementedError

@abstractmethod
def get_info(self, key: str) -> dict:
def get_info(self, key: str) -> LimiterInfo:
raise NotImplementedError

def get_prompt(self, key: str, **kwargs) -> str | None:
Expand Down Expand Up @@ -115,7 +118,7 @@ async def sync(self) -> None:
raise NotImplementedError


class CooldownInfo(TypedDict):
class CooldownInfo(LimiterInfo):
target: str
"""冷却对象"""
duration: int | float
Expand All @@ -134,7 +137,7 @@ class Cooldown(PersistLimiter):
)
"""冷却到期时间"""

async def start(self, key: str, duration: int | float = 0) -> None:
async def start(self, key: str, duration: float = 0) -> None:
"""进入冷却时间。
### 参数
Expand Down Expand Up @@ -181,7 +184,7 @@ async def sync(self) -> None:
await self.save()


class QuotaInfo(TypedDict):
class QuotaInfo(LimiterInfo):
target: str
"""配额对象"""
limit: int
Expand Down Expand Up @@ -280,7 +283,7 @@ async def sync(self) -> None:
await self.save()


class LockInfo(TypedDict):
class LockInfo(LimiterInfo):
target: str
"""锁定对象"""
max_count: int
Expand Down
15 changes: 6 additions & 9 deletions kirami/service/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,23 +95,19 @@ def _sort_by_position(item: Service | Ability) -> tuple[int | float, str]:
class ServiceManager:
@overload
@classmethod
def get_correspond(cls, item: Plugin) -> Service:
...
def get_correspond(cls, item: Plugin) -> Service: ...

@overload
@classmethod
def get_correspond(cls, item: Service) -> Plugin:
...
def get_correspond(cls, item: Service) -> Plugin: ...

@overload
@classmethod
def get_correspond(cls, item: type[Matcher]) -> Ability:
...
def get_correspond(cls, item: type[Matcher]) -> Ability: ...

@overload
@classmethod
def get_correspond(cls, item: Ability) -> type[Matcher]:
...
def get_correspond(cls, item: Ability) -> type[Matcher]: ...

@classmethod
def get_correspond(
Expand Down Expand Up @@ -189,7 +185,8 @@ def load_abilities(cls, service: Service) -> list[Ability]:
f"Ability name conflict! Duplicate with existing matcher name: {name}"
)
ability = Ability(
id=f"{service.id}#{name}", **configs.get(name, {"name": name}) # type: ignore
id=f"{service.id}#{name}",
**configs.get(name, {"name": name}), # type: ignore
)
ability.bind(matcher)
abilities[name] = ability
Expand Down
Loading

0 comments on commit b0b5edf

Please sign in to comment.