Skip to content

Commit

Permalink
add an env_with_source function to Arg
Browse files Browse the repository at this point in the history
This is intended to resolve clap-rs#4607, and also my earlier request
clap-rs#5104 which was closed in favor of clap-rs#4607

This is obviously not as powerful as the plugin system envisioned here
clap-rs#4607 (comment)

but it is simple and might be a useful stopgap until such time as the plugin system exists.

Fixes clap-rs#4607
  • Loading branch information
cbeck88 committed Jul 7, 2024
1 parent 469d847 commit c863229
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion clap_builder/src/builder/arg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2036,8 +2036,18 @@ impl Arg {
#[inline]
#[must_use]
pub fn env(mut self, name: impl IntoResettable<OsStr>) -> Self {
self.env_with_source(name, std::env::var_os)
}

/// Read from `name` environment variable when argument is not present, using `env_source` function instead of `std::env::var_os` to access the environment.
///
/// This is intended to be used for tests which you may want to isolate from the actual environment, or for wasm build targets and such.
#[cfg(feature = "env")]
#[inline]
#[must_use]
pub fn env_with_source(mut self, name: impl IntoResettable<OsStr>, env_source: &fn(&OsStr) -> Option<OsString>) -> Self {
if let Some(name) = name.into_resettable().into_option() {
let value = env::var_os(&name);
let value = env_source(&name);
self.env = Some((name, value));
} else {
self.env = None;
Expand Down

0 comments on commit c863229

Please sign in to comment.