use std::env;
use std::fs::File;
use std::io::prelude::Read;
use std::path::PathBuf;
pub fn get_dotenv_file_content() -> Option<String> {
let file_path = match env::var("DOTENV_CONFIG_PATH") {
Ok(env_value) => PathBuf::from(env_value),
Err(_) => env::current_dir().unwrap().join(".env"),
};
match File::open(file_path) {
Ok(mut file) => {
let mut content = String::new();
file.read_to_string(&mut content).ok()?;
Some(content.replace("\r\n", "\n"))
}
Err(..) => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn test_get_dotenv_file_content_by_envvar_path() {
env::set_var("DOTENV_CONFIG_PATH", "../tests/data/.env");
let content = get_dotenv_file_content();
assert!(content.is_some());
let content = content.unwrap();
assert_eq!(content.len(), 2272);
env::remove_var("DOTENV_CONFIG_PATH");
}
#[test]
fn test_get_dotenv_file_content_in_cwd() {
fs::copy("../tests/data/.env", ".env").expect("Failed to copy file");
let content = get_dotenv_file_content();
fs::remove_file(".env").expect("Failed to delete temp file");
assert!(content.is_some());
let content = content.unwrap();
assert_eq!(content.len(), 2272);
}
#[test]
fn test_get_dotenv_file_content_is_none() {
let content = get_dotenv_file_content();
assert!(content.is_none());
}
}