有没有更简单的方法 运行 clippy 我的构建脚本?

Is there a simpler way to run clippy on my build script?

在 Cargo 项目中,我可以使用以下命令轻松地 运行 clippy 我的 src 代码:

rustup run nightly cargo clippy

但是,如果我使用的是 build script,我也想 运行 快速使用它。例如,如果我的 build.rs 文件如下所示:

fn main() {
    let foo = "Hello, world!";
    println!("{}", foo);
}

我想在 运行 剪辑时看到这个:

warning: use of a blacklisted/placeholder name `foo`, #[warn(blacklisted_name)] on by default
 --> build.rs:2:9
  |
2 |     let foo = "Hello, world!";
  |         ^^^
  |
  = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#blacklisted_name

我能想到的 运行 clippy 在我的构建脚本上的唯一方法是将它复制到 cargo new 临时项目,运行 clippy,在那里进行更改,然后复制回来,但这非常不方便,并且当 build dependencies 等添加到组合中时很快变得不可行。

有没有更简单的方法来使用 clippy 分析我的构建脚本?

有两种使用 Clippy 的方法:cargo clippy 命令和 clippy 编译器插件。 cargo clippy 将构建脚本检测为主项目的依赖项,因此它不会加载编译器插件。

因此,另一种选择是直接使用编译器插件。执行此操作的说明在 clippy's README 中。不过,我们需要进行一些调整才能在构建脚本中使用它。

首先,我们需要添加clippy作为构建依赖:

[build-dependencies]
clippy = { version = "*", optional = true }

[features]
default = []

将其添加到 [dependencies] 将不起作用(结果是 error[E0463]: can't find crate for `clippy`),因为 Cargo 在构建构建脚本时不会将依赖项的路径传递给编译器。

然后,我们需要在 build.rs 的顶部添加:

#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]

最后,我们需要在启用 clippy 功能的情况下进行构建:

$ cargo build --features clippy

如果你想在使用上面的命令时在构建脚本和主项目上都运行 clippy,将相同的clippy依赖添加到[dependencies],然后将 cfg_attr 属性添加到板条箱根(lib.rsmain.rs 等)。