newton_cli/dotenv.rs
1use std::path::Path;
2
3use dotenvy;
4
5/// Initialize environment variables for CLI from .env file in current working directory
6///
7/// This function looks for a `.env` file in the current working directory (where the command is executed).
8/// This works for both development and published binaries.
9///
10/// If `APP_BASE_DIR` environment variable is set, it will look for the .env file in that directory instead.
11///
12/// The .env file is optional - if it doesn't exist, the function silently returns Ok(()).
13///
14/// # Returns
15/// A `Result` containing the environment variables, or an error if the initialization fails.
16/// Errors are typically ignored since .env files are optional.
17pub fn init() -> Result<(), dotenvy::Error> {
18 let base_dir = if let Ok(dir) = std::env::var("APP_BASE_DIR") {
19 dir
20 } else {
21 // Use current working directory for published binaries
22 // This allows users to place .env files where they run the command
23 std::env::current_dir()
24 .map(|p| p.to_string_lossy().to_string())
25 .unwrap_or_else(|_| ".".to_string())
26 };
27
28 let env_file = ".env";
29 let path = format!("{base_dir}/{env_file}");
30
31 tracing::debug!("Attempting to load environment variables from {path}");
32 dotenvy::from_path(Path::new(path.as_str()))
33}