needs_env_var/
lib.rs

1use proc_macro::TokenStream;
2use std::env::var;
3
4
5/// Skip compilation if the environment variable `env_var` is undefined or if its content does not
6/// match the provided value.
7#[proc_macro_attribute]
8pub fn needs_env_var(env_var: TokenStream, input: TokenStream) -> TokenStream {
9    let macro_string = env_var.to_string().replace(" = ", "=");
10    let mut parts = macro_string.split('=');
11
12    let var_str = parts.next().expect("macro needs an environment variable name");
13    let matches  = parts.next();
14
15    let var_content = var(var_str);
16    let exists = var_content.is_ok();
17
18    if !exists || matches.is_some() && matches != var_content.ok().as_deref() {
19        println!("\x1b[93mskipped. environment variable: \"{}\" did not match or was not set.\x1b[0m", var_str);
20        return TokenStream::new();
21    }
22    input
23}