Skip to content

Commit

Permalink
feat: 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 e1a7a74
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions clap_builder/src/builder/arg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2035,9 +2035,23 @@ impl Arg {
#[cfg(feature = "env")]
#[inline]
#[must_use]
pub fn env(mut self, name: impl IntoResettable<OsStr>) -> Self {
pub fn env(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 instead of `.env` 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: impl FnOnce(&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 e1a7a74

Please sign in to comment.