如何使用 clap 派生从环境变量中提取配置值?

dit*_*lav 9 rust clap

我在文档中找不到如何设置它。假设我有

#[derive(Parser, Debug)]
pub struct Opts {
    #[clap(long)]
    dry_run: bool,
}
Run Code Online (Sandbox Code Playgroud)

我需要做什么才能从 APP_DRY_RUN 环境变量获取 dry_run?

Pit*_*taJ 11

您必须启用该env功能:

Cargo.toml

...

clap = { version = "...", features = ["env"] }
Run Code Online (Sandbox Code Playgroud)

然后,您必须添加envclap 派生选项,默认情况下该选项将从 ALLCAPS 重新命名的环境变量中读取:

#[derive(Parser, Debug)]
pub struct Opts {
    #[clap(long, env)]
    dry_run: bool, // --dry-run or DRY_RUN env var
}
Run Code Online (Sandbox Code Playgroud)