ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Ruff 深度实战指南:Rust 打造的高速 Python 代码检查器与格式化工具

Ruff 深度实战指南:Rust 打造的高速 Python 代码检查器与格式化工具 Ruff 深度实战指南Rust 打造的高速 Python 代码检查器与格式化工具【免费下载链接】ruffAn extremely fast Python linter and code formatter, written in Rust.项目地址: https://gitcode.com/GitHub_Trending/ru/ruffRuff 是一个用 Rust 编写的极速 Python linter 与代码格式化工具目标是单一工具替代 Flake8、Black、isort、pydocstyle、pyupgrade、autoflake 等一整套传统 Python 工具链。本文以仓库根目录 README.md 为主体骨架结合crates/下的 Rust 源码完整覆盖安装、check/format命令、配置体系、规则系统与缓存机制帮助读者在真实项目中落地 Ruff 并理解其底层实现。一、定位与核心特性Ruff 的自我定位是比现有工具快一个数量级以上同时把更多功能整合到单一常见接口之下见 README.md 的 Overview 一节。围绕这一定位仓库文档给出了如下关键特性速度比 Flake8 等传统 linter 和 Black 等传统 formatter 快 10–100 倍。README 中的基准图即从零开始 lint CPython 代码库的耗时对比分发方式通过pip可安装也提供独立二进制安装脚本配置兼容原生支持pyproject.toml语言兼容README 明确标注支持 Python 3.14 语法行为对齐drop-in paritylinter 对齐 Flake8导入排序对齐 isort格式化工具对齐 Black内置缓存避免重复分析未变更的文件自动修复fix例如自动移除未使用的导入规则规模内置 900 余条规则其中大量规则是对 flake8-bugbear 等流行 Flake8 插件的原生 Rust 重实现编辑器集成提供 VS Code 等编辑器的第一方集成仓库内有 LSP 服务实现Monorepo 友好支持层级式、级联式配置发现。从源码结构看上述特性分别落在不同的 workspace crate 中见 Cargo.toml 的[workspace.dependencies]段版本0.16.5、Rust edition2024能力对应 crateCLI 入口ruff可执行文件crates/ruff900 规则的实现与注册crates/ruff_linterPython 语法树与解析器crates/ruff_python_ast、crates/ruff_python_parser格式化引擎Black 风格crates/ruff_python_formatter文件级缓存crates/ruff_cache配置解析与默认值crates/ruff_workspace语义模型作用域、导入分析crates/ruff_python_semantic这种解析、AST、语义、lint、格式化、缓存分层解耦的结构正是 Ruff 能在单个二进制中同时提供 lint 与 format 能力的工程基础。二、安装2.1 使用 uvx 直接调用免安装uvx ruff0.16.5 check # Lint all files in the current directory. uvx ruff0.16.5 format # Format all files in the current directory.2.2 通过包管理器安装# With uv. uv tool install rufflatest # Install Ruff globally. uv add --dev ruff # Or add Ruff to your project. # With pip. pip install ruff # With pipx. pipx install ruff2.3 独立二进制安装脚本0.5.0 起提供# On macOS and Linux. curl -LsSf https://astral.sh/ruff/install.sh | sh # On Windows. powershell -c irm https://astral.sh/ruff/install.ps1 | iex # For a specific version. curl -LsSf https://astral.sh/ruff/0.16.5/install.sh | sh powershell -c irm https://astral.sh/ruff/0.16.5/install.ps1 | iex此外 README 指出 Ruff 也可通过 Homebrew、Condaconda-forge 频道及其他多种包管理器安装。注意仓库中的安装脚本类资产并不在本仓库内安装命令中的域名链接属于官方发布渠道此处照录原文仅作命令参考本文不输出任何外部站点链接。三、基本命令ruff check 与 ruff formatRuff 的两条主命令是check检查/修复与format格式化二者共享同一套目标文件解析逻辑目录递归、*.py通配、单文件、以及arguments.txt形式的参数文件。3.1 作为 linterruff check # Lint all files in the current directory (and any subdirectories). ruff check path/to/code/ # Lint all files in /path/to/code (and any subdirectories). ruff check path/to/code/*.py # Lint all .py files in /path/to/code. ruff check path/to/code/to/file.py # Lint file.py. ruff check arguments.txt # Lint using an input file, treating its contents as newline-delimited command-line arguments.3.2 作为 formatterruff format # Format all files in the current directory (and any subdirectories). ruff format path/to/code/ # Format all files in /path/to/code (and any subdirectories). ruff format path/to/code/*.py # Format all .py files in /path/to/code. ruff format path/to/code/to/file.py # Format file.py. ruff format arguments.txt # Format using an input file, treating its contents as newline-delimited command-line arguments.其中--fix开关启用自动修复如移除未使用的导入这在下面 pre-commit 示例中可以看到。CLI 参数定义集中在 crates/ruff/src/args.rscheck与format子命令的行为集成测试位于 crates/ruff/tests/integration_test.rs 及 crates/ruff/tests/cli/lint.rs。后者包含大量--select RUF015之类的真实 CLI 用例如 lint.rs 中的 RUF015 测试覆盖了 noqa 抑制、ruff: ignore[...]指令与--fix交互等细节。四、CI 集成pre-commit 与 GitHub Action4.1 pre-commit 钩子- repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. rev: v0.16.5 hooks: # Run the linter. - id: ruff-check args: [ --fix ] # Run the formatter. - id: ruff-formatyaml 中的repo值为 README 原文保留的钩子仓库地址是 pre-commit 框架的必填字段。4.2 GitHub Actionname: Ruff on: [ push, pull_request ] jobs: ruff: runs-on: ubuntu-latest steps: - uses: actions/checkoutv4 - uses: astral-sh/ruff-actionv3两条集成路径的共同点是把lint fix放在提交前、lint format放在推送/PR 时利用 Ruff 的速度把检查成本压缩到可忽略README 引用了用户把 Ruff 加进 commit hook的实践经验。五、配置体系Ruff 可配置的文件有pyproject.toml、ruff.toml或.ruff.toml三种详见 docs/configuration.md。若在pyproject.toml中配置每个 section 需要加tool.ruff前缀例如[lint]写作[tool.ruff.lint]。5.1 默认配置的完整等价物如果不提供任何配置Ruff 的默认配置等价于下面这份ruff.toml直接来自 README.md 的 Configuration 一节逐行继承# Exclude a variety of commonly ignored directories. exclude [ .bzr, .direnv, .eggs, .git, .git-rewrite, .hg, .ipynb_checkpoints, .mypy_cache, .nox, .pants.d, .pyenv, .pytest_cache, .pytype, .ruff_cache, .svn, .tox, .venv, .vscode, __pypackages__, _build, buck-out, build, dist, node_modules, site-packages, venv, ] # Same as Black. line-length 88 indent-width 4 # Assume Python 3.10 target-version py310 [lint] # select [...] # See the Default Rules page for the full listing. ignore [] # Allow fix for all enabled rules (when --fix) is provided. fixable [ALL] unfixable [] # Allow unused variables when underscore-prefixed. dummy-variable-rgx ^(_|(_[a-zA-Z0-9_]*[a-zA-Z0-9]?))$ [format] # Like Black, use double quotes for strings. quote-style double # Like Black, indent with spaces, rather than tabs. indent-style space # Like Black, respect magic trailing commas. skip-magic-trailing-comma false # Like Black, automatically detect the appropriate line ending. line-ending auto要点解读line-length 88与 Black 保持一致避免 lint 与 format 因行宽不同互相打架dummy-variable-rgx允许下划线前缀的未使用变量如_这是F841类规则的默认豁免模式[format]段默认双引号、空格缩进、尊重 magic trailing comma、自动检测换行符全部与 Black 对齐exclude默认排除 26 个常见目录.ruff_cache本身也在其中缓存目录自排除。5.2 命令行覆盖配置部分配置项有专用命令行参数规则启停、文件发现、日志级别ruff check --select F401 --select F403 --quiet其余配置项通过万能--config参数以 TOML 片段形式传入ruff check --config lint.per-file-ignores {some_file.py [F841]}5.3 配置在源码中的落点配置解析的结果类型是 crates/ruff_workspace/src/settings.rs 中的Settings结构。从源码结构看settings.rs 的 Default 实现全局默认值包含cache_dir按项目根计算对应exclude中的.ruff_cachefix: false、fix_only: false自动修复默认关闭需显式传--fixoutput_format、show_fixes、unsafe_fixes等输出与修复策略四个嵌套子配置linterLinterSettings、file_resolver含exclude/include/respect_gitignore等字段见 FileResolverSettings、formatter、analyze。仓库根目录还维护了完整的 ruff.schema.json可用于编辑器对ruff.toml/pyproject.toml做 JSON Schema 校验与自动补全。5.4 Preview 模式通过配置文件中preview true或命令行--preview启用可提前试用最新的 lint 规则、格式化风格变更与接口更新。README 特别提示preview 特性集合是不稳定的、可能在稳定前变化的生产项目建议只在评估后开启。六、规则系统Ruff 内置超过 900 条 lint 规则且无论规则源自哪个工具全部由 Rust 原生重实现为第一方能力不存在运行时插件加载。默认启用的规则类别FPyflakes、Epycodestyle Error、Bbugbear、UPpyupgrade与RUFRuff 自有规则外加许多其他规则但刻意排除了与格式化工具ruff format或 Black职责重叠的风格类规则——这是避免lint 与 format 互相冲突的关键设计README 建议新手直接从默认规则集起步零配置即可捕获未使用导入等大量常见错误。除默认集外Ruff 重实现了一批最流行的 Flake8 插件与质量工具包括autoflake、eradicate、flake8-2020、flake8-annotations、flake8-async、flake8-bandit、flake8-blind-except、flake8-boolean-trap、flake8-bugbear、flake8-builtins、flake8-commas、flake8-comprehensions、flake8-copyright、flake8-datetimez、flake8-debugger、flake8-django、flake8-docstrings、flake8-errmsg、flake8-executable、flake8-future-annotations、flake8-gettext、flake8-implicit-str-concat、flake8-import-conventions、flake8-logging、flake8-logging-format、flake8-no-pep420、flake8-pie、flake8-print、flake8-pyi、flake8-pytest-style、flake8-quotes、flake8-raise、flake8-return、flake8-self、flake8-simplify、flake8-slots、flake8-super、flake8-tidy-imports、flake8-todos、flake8-type-checking、flake8-use-pathlib、flynt、isort、mccabe、pandas-vet、pep8-naming、pydocstyle、pygrep-hooks、pylint-airflow、pyupgrade、tryceratops、yesqa。在源码层面所有规则按上游插件组织在 crates/ruff_linter/src/rules/ 目录下3000 余个文件含 2189 个.snap快照测试规则注册表位于 crates/ruff_linter/src/registry.rs规则代码如F401、RUF015的映射定义在 crates/ruff_linter/src/codes.rs。规则选择语法--select F401、per-file-ignores等在 crates/ruff_linter/src/rule_selector.rs 中实现。七、性能与架构从源码看 Ruff 为什么快README 承诺的10–100 倍速度来自几个在源码中可验证的工程决策单一 Rust 二进制解析、lint、format 共享同一次词法/语法分析结果。AST 由 crates/ruff_python_ast 提供配合 crates/ruff_python_parser 的纯 Rust 解析器语义分析在 crates/ruff_python_semantic 中以作用域模型scope/binding/reference支撑跨语句规则如未使用变量、未使用导入内置缓存crates/ruff_cache 维护基于文件内容与 mtime 的缓存键见 cache_key.rs未变更文件直接跳过分析这正是 README built-in caching, to avoid re-analyzing unchanged files 的落地格式化器继承成熟的 Rust 格式引擎README 致谢一节明确说明formatter 构建自 Rome 项目rome_formatter的分支并吸收了 Rome、Prettier、Black 的 API 与实现细节核心引擎位于 crates/ruff_formatter。与 Black 的行为对齐细节可参考 docs/formatter/black.md导入解析借鉴 Pyright 的算法README Acknowledgements对应 crates/ruff_python_importer 中的导入插入/重排逻辑基准测试常态化crates/ruff_benchmark 提供 formatter、lexer、linter、parser、module_resolution 等 criterion 基准benches 目录scripts/benchmarks/ 中还包含跨工具对比脚本——README 顶部的CPython 基准柱状图即由此类流程产出。八、贡献、支持与许可贡献仓库提供 CONTRIBUTING.md 与 AGENTS.md 贡献指南新增规则可参考 scripts/add_rule.py 的自动化流程开发工具集中在 crates/ruff_dev文档生成、schema 生成、AST/词法打印等致谢linter 借鉴了 Flake8、Pyflakes、pycodestyle、pydocstyle、pyupgrade、isort 的 API 与实现细节部分为直接 Rust 移植formatter 基于 Rome 的rome_formatter分支import resolver 基于 Pyright 的导入解析算法另受 Clippy、ESLint 等生态外工具影响原文见 README.md 的 Acknowledgements 一节使用者README 的 Whos Using Ruff? 一节列出了近百个采用项目包括 Apache Airflow、FastAPI、Hugging Face、Pandas、SciPy、PyTorch、pytest、Pylint、pip 等许可整个仓库含 LICENSE采用 MIT 协议维护方Ruff 由 Astral 团队维护同仓库内还包含类型检查器ty系列 cratecrates/ty与 LSP 服务 ruff_server。九、快速上手清单安装uv tool install rufflatest或pip install ruff零配置起步ruff check使用F/E/B/UP/RUF等默认规则集需要修复ruff check --fix格式化ruff format默认与 Black 对齐88 列、双引号、magic trailing comma项目级配置在pyproject.toml的[tool.ruff]/[tool.ruff.lint]/[tool.ruff.format]中调整或用独立ruff.toml可被编辑器按 ruff.schema.json 校验需要最新规则/风格开启preview true或--preview但注意其不稳定性CI 固化按第四节的 pre-commit 或 GitHub Action 模板接入。以上全部命令、配置默认值与规则类别均来自 README.md实现细节佐证来自crates/下对应 crate可按文中给出的相对路径在当前仓库中继续深入。【免费下载链接】ruffAn extremely fast Python linter and code formatter, written in Rust.项目地址: https://gitcode.com/GitHub_Trending/ru/ruff创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表