[英]How can I make running a Cargo build script optional?
I have a Rust project that generates a dynamic (cdylib) library. 我有一个Rust项目,它会生成一个动态(cdylib)库。 The project uses a cbindgen build script to create an according C header file, matching the exported functions of the library.
该项目使用cbindgen构建脚本来创建相应的C头文件,以匹配库的导出功能。
Cargo.toml
looks like this: Cargo.toml
看起来像这样:
[package]
name = "example"
version = "0.1.0"
authors = ["Me <me@foo.bar>"]
build = "build.rs"
[lib]
name = "example"
crate-type = ["cdylib"]
[dependencies]
[build-dependencies]
cbindgen = "0.6.2"
Unfortunately RLS (Rust Language Server) doesn't work very well when the build script is active which makes editing in VS Code rather unpleasant. 不幸的是,当构建脚本处于活动状态时,RLS(Rust Language Server)不能很好地工作,这使得在VS Code中进行编辑非常不愉快。 Is there a way to make running the build script optional, having it disabled by default and only manually enable it when requested on the command-line (ie something like
cargo build --release --enable-build-scripts
)? 有没有一种方法可以使运行构建脚本成为可选项,默认情况下将其禁用并仅在命令行要求时才手动启用它(例如,诸如
cargo build --release --enable-build-scripts
)?
You can't conditionally disable build scripts or pass variables to them via cargo build
, but you can make use of environment variables instead. 您不能有条件地禁用构建脚本或通过
cargo build
将变量传递给它们,但可以改用环境变量。
Inside your build.rs
: 在您的
build.rs
内部:
use std::env;
fn main() {
let build_enabled = env::var("BUILD_ENABLED")
.map(|v| v == "1")
.unwrap_or(true); // run by default
if build_enabled {
// do your build
}
}
Build with your build script: 使用您的构建脚本进行构建:
BUILD_ENABLED=1 cargo build
Build without your build script: 在没有构建脚本的情况下进行构建:
BUILD_ENABLED=0 cargo build
To extend the answer from @PeterHall one can use a Cargo "features" section to pass information on to the build script. 要扩展@PeterHall的答案,可以使用Cargo的“功能”部分将信息传递给构建脚本。
Insert the following lines into Cargo.toml
: Cargo.toml
插入Cargo.toml
:
[features]
headers = []
Then check for environment variable CARGO_FEATURE_HEADERS
in build.rs
: 然后检查环境变量
CARGO_FEATURE_HEADERS
在build.rs
:
use std::env;
fn write_headers() {
// call cbindgen ...
}
fn main() {
let headers_enabled = env::var_os("CARGO_FEATURE_HEADERS").is_some();
if headers_enabled {
write_headers();
}
}
To make a release build run cargo build --features=headers --release
. 要进行发布构建,请运行
cargo build --features=headers --release
。
Now this solution still compiles the build script and all cbindgen dependencies when RLS updates its status or when manually running cargo test
. 现在,当RLS更新其状态或手动运行
cargo test
时,此解决方案仍然可以编译构建脚本和所有cbindgen依赖项。 But cbindgen run-time errors do not hamper RLS anymore. 但是cbindgen运行时错误不再妨碍RLS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.