如何为工作区中的所有 crate 提供共享的 Clippy 配置?

dbr*_*dbr 22 rust rust-clippy

我有一个应用程序分成几个箱子。我想拒绝或允许所有箱子中的特定 lint。例如:

#![deny(clippy::print_stdout)]
Run Code Online (Sandbox Code Playgroud)

看来我必须将其添加到每个板条箱中的 lib.rs 中。

Cargo有一张票据允许以某种方式进行配置,但它已经开放了好几年,没有明确的结论。

是否有解决方法可以避免每个板条箱重复这些允许/拒绝/警告行?

我的一个想法是通过在工作区根目录include!创建一个,然后在每个板条箱的 lib.rs 中添加clippy_config.rs

include!("../../clippy_config.rs");
Run Code Online (Sandbox Code Playgroud)

然而这失败了

error: an inner attribute is not permitted in this context
 --> app/src/../../clippy_config.rs:1:1
  |
1 | #![deny(clippy::print_stdout)]
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them.
Run Code Online (Sandbox Code Playgroud)

由于同样的原因,我使用宏的另一个想法也不起作用。

除了编写外部脚本来修改 Rust 文件以自动执行复制之外,是否有一种简单的方法可以做到这一点?(正如描述 Embark Studio 设置的评论中所提到的)。

Mat*_* M. 17

从 Rust 1.74 开始

Rust 和 Clippy lint 可以配置:

  • 在 Cargo.toml 中,请参见下文。
  • 具有属性:#[deny(clippy::print_stdout)].
  • 带标志:-Dclippy::print-stdout.

Cargo.toml可以通过多种方式完成配置。

对于单个板条箱,使用以下[lints]部分

[lints.rust]
unsafe_code = "forbid"

[lints.clippy]
enum_glob_use = "deny"
Run Code Online (Sandbox Code Playgroud)

对于工作区箱,使用[lints]

[workspace]
members = [...]

[workspace.lints.rust]
unsafe_code = "forbid"
Run Code Online (Sandbox Code Playgroud)

然后在工作区中每个希望继承的 crate 中:

[lints]
workspace = true
Run Code Online (Sandbox Code Playgroud)

注意:当用于cargo new在现有工作区中创建新 crate 时,该[lints]部分会自动添加。

什么时候用哪个?

属性最好用于一次性情况。例如,我经常#[allow(clippy::too_many_arguments)]在内部函数上使用,但我不希望在公共 API 函数上使用它。

Cargo.toml最适合项目范围的设置,可容纳开发工作流程CI。例如,我鼓励使用unsafe_ops_in_unsafe_fn = "forbid"这样的每一个不安全操作的安全先决条件都被清楚地记录下来,而不是挥手说“相信我”。

标志最适合用于工作流程特定设置。例如,我会鼓励-Drust::dead-codeCI,但在开发过程中会很痛苦。

之前的版本

(也适用于 Rust 1.74 及以上版本,只是可能不太方便)

Clippy 提供 3 种配置模式:

  • 属性:#[deny(clippy::print_stdout)]
  • 标志:-Dclippy::print-stdout
  • 配置文件:clippy.toml,但仅限于可配置 lint 的子集。

对于跨 crate 的项目范围配置,配置文件如果有效的话是最佳选择。

否则,第二个最佳(hacky)选项是间接使用标志。也就是说,RUSTFLAGS=-Dclippy::print-stdout您可以让 Cargo 执行此操作,并在项目范围内配置 Cargo,而不是在编译器调用之前指定。

在项目的根目录中,创建一个.cargo/config.toml包含以下内容的文件:

[build]
rustflags = ["-Dclippy::print-stdout"]
Run Code Online (Sandbox Code Playgroud)

Cargo 在调用它时会将这个标志传递给 Clippy。

注意:在工作区设置中,.cargo/config.toml从工作区根部调用 Cargo 时,各个 crate 文件夹中的文件夹会被忽略,因此最好将其放在根部.cargo