feat: Default env variables
This commit is contained in:
@@ -437,23 +437,49 @@ impl ToTokens for EnvVars {
|
||||
struct EnvVar {
|
||||
key: Value,
|
||||
value: Value,
|
||||
conditional: bool,
|
||||
}
|
||||
|
||||
impl Parse for EnvVar {
|
||||
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
|
||||
let key = input.parse()?;
|
||||
|
||||
_ = input.parse::<Token![:]>()?;
|
||||
|
||||
let conditional = if input.lookahead1().peek(Token![?]) {
|
||||
input.parse::<Token![?]>()?;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
let value = input.parse()?;
|
||||
|
||||
Ok(Self { key, value })
|
||||
Ok(Self {
|
||||
key,
|
||||
value,
|
||||
conditional,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ToTokens for EnvVar {
|
||||
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
|
||||
let Self { key, value } = self;
|
||||
let Self {
|
||||
key,
|
||||
value,
|
||||
conditional,
|
||||
} = self;
|
||||
|
||||
tokens.extend(quote! { _c.env(#key, #value); });
|
||||
if *conditional {
|
||||
tokens.extend(quote! {
|
||||
if ::std::env::var(#key).ok().is_none() {
|
||||
_c.env(#key, #value);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
tokens.extend(quote! { _c.env(#key, #value); });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,26 @@ mod pipe;
|
||||
/// assert_eq!(format!("{command:?}"), r#"NEW_VAR="new_var" TEST="test" "echo" "test""#);
|
||||
/// ```
|
||||
///
|
||||
/// #### Conditional
|
||||
/// You can have a default value set for an environment variable.
|
||||
///
|
||||
/// ```rust
|
||||
/// # use comlexr_macro::cmd;
|
||||
/// const NEW_VAR: &str = "NEW_VAR";
|
||||
/// std::env::set_var("TEST", "realvalue");
|
||||
///
|
||||
/// let command = cmd!(
|
||||
/// env {
|
||||
/// "TEST":? "test",
|
||||
/// NEW_VAR: "new_var"
|
||||
/// };
|
||||
/// "echo",
|
||||
/// "test",
|
||||
/// );
|
||||
///
|
||||
/// assert_eq!(format!("{command:?}"), r#"NEW_VAR="new_var" "echo" "test""#);
|
||||
/// ```
|
||||
///
|
||||
/// ### Current Directory and Environment Variable Order
|
||||
/// ```
|
||||
/// # use comlexr_macro::cmd;
|
||||
|
||||
Reference in New Issue
Block a user