dotenv_proc/
lib.rs

1use std::fs::read_to_string;
2
3use proc_macro::TokenStream;
4use quote::quote;
5
6
7#[proc_macro]
8pub fn dotenv(input: TokenStream) -> TokenStream {
9    // Parse the input
10    let env_variable: syn::LitStr = syn::parse(input).expect("Only pass a single string into the macro!");
11    // Get contents of .env file
12    let dotenv_file_contents = read_to_string(".env").expect(".env file not found");
13    // Find the appropriate line, and split it on spaces
14    let mut line = dotenv_file_contents.lines().filter(|line| line.contains(&env_variable.value())).next().expect(&format!("Environment variable \"{}\" not found", env_variable.value())).split("=");
15    // Ignore the key and equal sign
16    line.next();
17    // Get the value of the env variable
18    let value = line.next().expect("No value found").trim();
19    // Generate it into rust code
20    quote! {
21        #value
22    }.into()
23}
24
25#[proc_macro]
26pub fn dotenv_option(input: TokenStream) -> TokenStream {
27    // Parse the input
28    let env_variable: syn::LitStr = syn::parse(input).expect("Only pass a single string into the macro!");
29    // Get contents of .env file
30    if let Ok(dotenv_file_contents) = read_to_string(".env") {
31        // Find the appropriate line, and split it on spaces
32        if let Some(line) = dotenv_file_contents.lines().filter(|line| line.contains(&env_variable.value())).next() {
33            let mut line = line.split("=");
34            // Ignore the key and equal sign
35            line.next();
36            // Get the value of the env variable
37            if let Some(mut value) = line.next() {
38                value = value.trim();
39                // Generate it into rust code
40                quote! {
41                    Some(#value)
42                }.into()
43            } else {
44                quote! {
45                    None
46                }.into()
47            }
48            
49        } else {
50            quote! {
51                None
52            }.into()
53        }
54        
55    } else {
56        quote! {
57            None
58        }.into()
59    }
60    
61}