Skip to main content

rustbasic_core/
dotenvy.rs

1use std::fs;
2use std::env;
3use std::path::{Path, PathBuf};
4
5/// Loads environment variables from a `.env` file in the current directory.
6/// Returns the path to the loaded file on success.
7pub fn dotenv() -> Result<PathBuf, std::io::Error> {
8    let path = Path::new(".env");
9    if !path.exists() {
10        return Err(std::io::Error::new(
11            std::io::ErrorKind::NotFound,
12            "File .env tidak ditemukan",
13        ));
14    }
15
16    let content = fs::read_to_string(path)?;
17    for line in content.lines() {
18        let trimmed = line.trim();
19        // Skip empty lines or comments
20        if trimmed.is_empty() || trimmed.starts_with('#') {
21            continue;
22        }
23
24        if let Some(pos) = trimmed.find('=') {
25            let key = trimmed[..pos].trim();
26            let val = trimmed[pos + 1..].trim();
27
28            // Strip optional quotes around value
29            let clean_val = if (val.starts_with('"') && val.ends_with('"'))
30                || (val.starts_with('\'') && val.ends_with('\''))
31            {
32                if val.len() >= 2 {
33                    &val[1..val.len() - 1]
34                } else {
35                    ""
36                }
37            } else {
38                val
39            };
40
41            unsafe {
42                env::set_var(key, clean_val);
43            }
44        }
45    }
46
47    Ok(path.to_path_buf())
48}