Skip to content

Commit 76c779a

Browse files
authored
chore: 使用 Ruff 替代 Black 作为格式化工具 (#102)
1 parent ac72595 commit 76c779a

File tree

14 files changed

+963
-707
lines changed

14 files changed

+963
-707
lines changed

.github/workflows/lint.yml

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,23 @@ on:
1212
workflow_dispatch:
1313

1414
jobs:
15-
black:
16-
runs-on: ubuntu-latest
17-
steps:
18-
- uses: actions/checkout@v3
19-
- uses: psf/black@stable
20-
2115
ruff:
2216
runs-on: ubuntu-latest
2317
steps:
2418
- uses: actions/checkout@v3
25-
- uses: chartboost/ruff-action@v1
19+
20+
- uses: pdm-project/setup-pdm@v3
21+
name: Setup PDM
22+
with:
23+
python-version: 3.9
24+
cache: true
25+
- name: Install dependencies
26+
run: pdm install -G dev -G lint
27+
28+
- run: |
29+
eval $(pdm venv activate)
30+
ruff check --output-format=github .
31+
ruff format --check .
2632
2733
pylint:
2834
runs-on: ubuntu-latest

.github/workflows/test.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ jobs:
1919
cancel-in-progress: true
2020
strategy:
2121
matrix:
22-
python-version: ["3.8", "3.9", "3.10", "3.11"]
22+
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
2323
os: [ubuntu-latest, windows-latest, macos-latest]
2424
fail-fast: false
2525
env:

.pre-commit-config.yaml

Lines changed: 0 additions & 20 deletions
This file was deleted.

CONTRIBUTING.md

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,12 @@
88

99
### 安装依赖
1010

11-
AliceBot 使用 [PDM](https://pdm.fming.dev/) 管理项目的依赖,并使用 [pre-commit](https://pre-commit.com/) 在提交前执行代码审查
11+
AliceBot 使用 [PDM](https://pdm.fming.dev/) 管理项目的依赖。
1212

13-
因此,你需要先根据 [PDM](https://pdm.fming.dev/latest/#installation) 的指引安装 PDM,之后在项目目录中执行以下命令:
13+
因此,你需要先根据 [PDM](https://pdm-project.org/latest/#installation) 的指引安装 PDM,之后在项目目录中执行以下命令:
1414

1515
```shell
1616
pdm install
17-
pre-commit install
1817
```
1918

2019
AliceBot 项目的文档使用 [VitePress](https://vitepress.dev/) 生成,如果你想要贡献 AliceBot 的文档,请额外安装 [pnpm](https://pnpm.io/) 环境,并在项目目录中执行以下命令:
@@ -27,16 +26,15 @@ pnpm install
2726

2827
虽然并非强制,但强烈建议你使用 VSCode 作为编辑器对 AliceBot 项目的代码进行编辑,因为 AliceBot 具有完全的类型注解,VSCode 的 Pylance 插件具有相对较好的静态类型检查效果。
2928

30-
如果你使用 VSCode 作为编辑器,需要安装 **Python****Pylance****isort** 插件,并进行以下配置:
29+
如果你使用 VSCode 作为编辑器,需要安装 **Python****Pylance****Ruff** 插件,并进行以下配置:
3130

3231
```json
3332
{
3433
"[python]": {
3534
"editor.formatOnPaste": false,
36-
"editor.formatOnSaveMode": "file"
37-
},
38-
"python.analysis.diagnosticMode": "workspace",
39-
"python.formatting.provider": "black"
35+
"editor.formatOnSaveMode": "file",
36+
"editor.defaultFormatter": "charliermarsh.ruff"
37+
}
4038
}
4139
```
4240

@@ -50,7 +48,7 @@ pnpm install
5048

5149
AliceBot 的代码风格遵循 [PEP 8](https://www.python.org/dev/peps/pep-0008/) 规范。
5250

53-
AliceBot 使用 [Black](https://github.com/psf/black) 作为格式化工具,并使用 [isort](https://github.com/PyCQA/isort) 确保导入顺序,如果你已经按照上文配置了 VSCodo,那么你应该很容易遵循此规范,否则请在提交前手动执行上述格式化工具。
51+
AliceBot 使用 [Ruff](https://docs.astral.sh/ruff/) 作为格式化工具,如果你已经按照上文配置了 VSCode,那么你应该很容易遵循此规范,否则请在提交前手动执行上述格式化工具。
5452

5553
### 类型注解
5654

alicebot/bot.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@
2727
overload,
2828
)
2929

30-
from pydantic import ValidationError, create_model
30+
from pydantic import (
31+
ValidationError,
32+
create_model, # pyright: ignore[reportUnknownVariableType]
33+
)
3134

3235
from alicebot.adapter import Adapter
3336
from alicebot.config import AdapterConfig, ConfigModel, MainConfig, PluginConfig
@@ -91,8 +94,12 @@ class Bot:
9194
_restart_flag: bool # 重新启动标志
9295
_module_path_finder: ModulePathFinder # 用于查找 plugins 的模块元路径查找器
9396
_raw_config_dict: Dict[str, Any] # 原始配置字典
94-
_adapter_tasks: Set["asyncio.Task[None]"] # 适配器任务集合,用于保持对适配器任务的引用
95-
_handle_event_tasks: Set["asyncio.Task[None]"] # 事件处理任务,用于保持对适配器任务的引用
97+
_adapter_tasks: Set[
98+
"asyncio.Task[None]"
99+
] # 适配器任务集合,用于保持对适配器任务的引用
100+
_handle_event_tasks: Set[
101+
"asyncio.Task[None]"
102+
] # 事件处理任务,用于保持对适配器任务的引用
96103

97104
# 以下属性不会在重启时清除
98105
_config_file: Optional[str] # 配置文件
@@ -102,7 +109,9 @@ class Bot:
102109
_extend_plugins: List[
103110
Union[Type[Plugin[Any, Any, Any]], str, Path]
104111
] # 使用 load_plugins() 方法程序化加载的插件列表
105-
_extend_plugin_dirs: List[Path] # 使用 load_plugins_from_dirs() 方法程序化加载的插件路径列表
112+
_extend_plugin_dirs: List[
113+
Path
114+
] # 使用 load_plugins_from_dirs() 方法程序化加载的插件路径列表
106115
_extend_adapters: List[
107116
Union[Type[Adapter[Any, Any]], str]
108117
] # 使用 load_adapter() 方法程序化加载的适配器列表

alicebot/dependencies.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -119,21 +119,17 @@ async def solve_dependencies(
119119
)
120120
depend_obj = cast(
121121
Union[_T, AsyncContextManager[_T], ContextManager[_T]],
122-
dependent.__new__(dependent), # pyright: ignore[reportGeneralTypeIssues]
122+
dependent.__new__(dependent), # pyright: ignore
123123
)
124124
for key, value in values.items():
125125
setattr(depend_obj, key, value)
126126
depend_obj.__init__() # type: ignore[misc] # pylint: disable=unnecessary-dunder-call
127127

128128
if isinstance(depend_obj, AsyncContextManager):
129-
depend = await stack.enter_async_context(
130-
depend_obj # pyright: ignore[reportUnknownArgumentType]
131-
)
129+
depend = await stack.enter_async_context(depend_obj) # pyright: ignore
132130
elif isinstance(depend_obj, ContextManager):
133-
depend = await stack.enter_async_context(
134-
sync_ctx_manager_wrapper(
135-
depend_obj # pyright: ignore[reportUnknownArgumentType]
136-
)
131+
depend = await stack.enter_async_context( # pyright: ignore
132+
sync_ctx_manager_wrapper(depend_obj)
137133
)
138134
else:
139135
depend = depend_obj
@@ -149,4 +145,4 @@ async def solve_dependencies(
149145
raise TypeError("dependent is not a class or generator function")
150146

151147
dependency_cache[dependent] = depend
152-
return depend
148+
return depend # pyright: ignore

alicebot/event.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,9 @@ async def get(
101101
Raises:
102102
GetEventTimeout: 超过最大事件数或超时。
103103
"""
104-
return await self.adapter.get(
104+
return await self.adapter.get( # pyright: ignore
105105
self.is_same_sender,
106-
event_type=type(self),
106+
event_type=type(self), # pyright: ignore
107107
max_try_times=max_try_times,
108108
timeout=timeout,
109109
)

alicebot/message.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def __get_pydantic_core_schema__(
9292
core_schema.no_info_after_validator_function(
9393
cls,
9494
handler.generate_schema(
95-
List[cls.get_segment_class()] # type: ignore[misc, index]
95+
List[cls.get_segment_class()] # type: ignore[misc]
9696
),
9797
),
9898
]
@@ -459,7 +459,7 @@ def __eq__(self, other: object) -> bool:
459459
是否相等。
460460
"""
461461
return (
462-
type(other) is self.__class__ # pylint: disable=unidiomatic-typecheck
462+
isinstance(other, self.__class__)
463463
and self.type == other.type
464464
and self.data == other.data
465465
)

alicebot/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ async def sync_ctx_manager_wrapper(
229229

230230

231231
def wrap_get_func(
232-
func: Optional[Callable[[EventT], Union[bool, Awaitable[bool]]]]
232+
func: Optional[Callable[[EventT], Union[bool, Awaitable[bool]]]],
233233
) -> Callable[[EventT], Awaitable[bool]]:
234234
"""将 `get()` 函数接受的参数包装为一个异步函数。
235235
@@ -251,7 +251,7 @@ def wrap_get_func(
251251
else: # pragma: no cover
252252

253253
def get_annotations(
254-
obj: Union[Callable[..., object], Type[Any], ModuleType]
254+
obj: Union[Callable[..., object], Type[Any], ModuleType],
255255
) -> Dict[str, Any]:
256256
"""计算一个对象的标注字典。
257257

package.json

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,15 @@
1212
"homepage": "https://docs.alicebot.dev/",
1313
"license": "MIT",
1414
"dependencies": {
15-
"vitepress": "1.0.0-rc.24",
16-
"vue": "^3.3.7"
15+
"vitepress": "1.0.0-rc.31",
16+
"vue": "^3.3.11"
1717
},
1818
"devDependencies": {
19-
"@types/node": "^20.8.9",
19+
"@types/node": "^20.10.4",
2020
"conventional-changelog-cli": "^3.0.0",
2121
"markdownlint-cli2": "^0.8.1",
22-
"prettier": "^3.0.3",
23-
"pyright": "^1.1.333",
22+
"prettier": "^3.1.1",
23+
"pyright": "^1.1.339",
2424
"zhlint": "^0.7.1"
2525
},
2626
"scripts": {

packages/alicebot-adapter-mirai/alicebot/adapter/mirai/event/notice.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
"""通知事件。"""
22
# pyright: reportIncompatibleVariableOverride=false
33

4-
from typing import Literal, Optional
4+
from typing import Any, Dict, Literal, Optional
55

6-
from pydantic import create_model
6+
from pydantic import create_model # pyright: ignore[reportUnknownVariableType]
77

88
from .base import (
99
FriendInfo,
@@ -44,14 +44,15 @@ class FriendInputStatusChangedEvent(FriendEvent):
4444

4545

4646
# 因为 from 是 python 关键字,所以不能直接定义
47+
_temp_dict: Dict[str, Any] = {
48+
"from": (str, ...),
49+
"to": (str, ...),
50+
}
4751
FriendNickChangedEvent = create_model(
4852
"FriendNickChangedEvent",
4953
type=(Literal["FriendNickChangedEvent"], ...),
5054
friend=(FriendInfo, ...),
51-
**{
52-
"from": (str, ...),
53-
"to": (str, ...),
54-
},
55+
**_temp_dict,
5556
__config__=None,
5657
__base__=FriendEvent,
5758
__module__=__name__,

0 commit comments

Comments
 (0)