学习中... 关注他 最近几年 一个用Rust编写的 Ruff 利用 RustPython 的 AST 解析器,实现自己的 AST 遍历、visitor 抽象和 lint 规则逻辑。它目标是比其他工具快几个数量级,同时提供代码检查、 Ruff 可以用来替换 下面简单介绍下用法: 安装和使用安装上非常简单,借助于maturin,Ruff 可以像其他第三方Python包一样通过 pip install ruff 然后就可以使用 Ruff 了: ruff path/to/code/to/check.py ruff path/to/code/ ruff path/to/code/*.py 你还可以在 ruff path/to/code/ --watch 也可以和 pre-commit 一起工作: - repo: https://github.com/charliermarsh/ruff-pre-commit # Ruff version. rev: 'v0.0.198' hooks: - id: ruff # Respect `exclude` and `extend-exclude` settings. args: ["--force-exclude"] 配置Ruff 可以通过 [tool.ruff] line-length = 88 # Enable Pyflakes `E` and `F` codes by default. select = ["E", "F"] ignore = [] # Exclude a variety of commonly ignored directories. exclude = [ ".bzr", ".direnv", ".eggs", ".git", ".hg", ".mypy_cache", ".nox", ".pants.d", ".ruff_cache", ".svn", ".tox", ".venv", "__pypackages__", "_build", "buck-out", "build", "dist", "node_modules", "venv", ] per-file-ignores = {} # Allow unused variables when underscore-prefixed. dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" # Assume Python 3.10. target-version = "py310" [tool.ruff.mccabe] # Unlike Flake8, default to a complexity level of 10. max-complexity = 10 当然也可以自定义配置。例如,下面将配置Ruff 为:
[tool.ruff] # Enable Pyflakes and pycodestyle rules. select = ["E", "F"] # Never enforce `E501` (line length violations). ignore = ["E501"] # Never try to fix `F401` (unused imports). unfixable = ["F401"] # Ignore `E402` (import violations) in all `__init__.py` files, and in `path/to/file.py`. [tool.ruff.per-file-ignores] "__init__.py" = ["E402"] "path/to/file.py" = ["E402"] Ruff 模仿了 Flake8 的错误代码系统,其中每个错误代码由一个 # Enable Pyflakes and pycodestyle rules. select = ["E", "F"] # Never enforce `E501` (line length violations). ignore = ["E501"] # Always autofix, but never try to fix `F401` (unused imports). fix = true unfixable = ["F401"] # Ignore `E402` (import violations) in all `__init__.py` files, and in `path/to/file.py`. [per-file-ignores] "__init__.py" = ["E402"] "path/to/file.py" = ["E402"] 也可以通过命令行提供一些常见的配置设置: ruff path/to/code/ --select F401 --select F403 类似于 ESLint, Ruff 支持分层配置,Python文件以距离它“最近的”的 # Extend the `pyproject.toml` file in the parent directory. extend = "../pyproject.toml" # But use a different line length. line-length = 100 上述规则同样适用于 # Ignore F841.x = 1 # noqa: F841# Ignore E741 and F841.i = 1 # noqa: E741, F841# Ignore _all_ errors.x = 1 # noqa 当前支持的规则参见:https://github.com/charliermarsh/ruff#supported-rules 编辑器集成VS Codevscode提供了 Ruff VS Code extension,可以直接在插件管理中安装使用,它支持 PyCharm(外部工具)Ruff 可以在 PyCharm 中作为 Ruff可以作为一个可运行的 PyCharm(插件)在 IntelliJ 插件市场也能找到非官方维护的 Ruff 插件,相比 其他Vim/Github Actions等配置方法可以查阅官方文档。 其他Ruff 可以和Python另一个明星项目 - 格式化工具black 一起使用,只需要 Ruff 第一个版本发布在2022年8月30日,可以说是一个非常新的项目,虽然作者迭代的非常积极(目前版本为 相信不久的将来能看到功能更完善、支持更多的规则、更好用的 Ruff。 |
|