Compare commits

...

5 Commits

Author SHA1 Message Date
a594517ce1 Update readme 2025-06-22 17:00:32 +02:00
ee6b992c8e Update Doc & Fallback improvement 2025-06-22 16:49:54 +02:00
4369d9209d Change registry name 2025-05-24 09:19:54 +02:00
8dc577c725 Update docs 2025-05-22 19:24:11 +02:00
ca8f4aecb1 Change metadata 2025-05-19 21:55:47 +02:00
7 changed files with 151 additions and 90 deletions

2
Cargo.lock generated
View File

@@ -4,4 +4,4 @@ version = 4
[[package]] [[package]]
name = "merlin_env_helper" name = "merlin_env_helper"
version = "0.1.0" version = "0.4.0"

View File

@@ -1,6 +1,9 @@
[package] [package]
name = "merlin_env_helper" name = "merlin_env_helper"
version = "0.1.0" version = "0.4.0"
edition = "2024" edition = "2024"
publish = ["merlin"]
description = "Utility functions to read environment with fallback and values from a file"
license = "MIT"
repository = "ssh://git@gitea.merlinserver.de:2222/Stefan/merlin_env_helper.git"
[dependencies] [dependencies]

View File

@@ -1 +1,9 @@
# NO Man Sky Wiki # MERLIN ENV HELPER
merlin_env_helper
Helper lib to use environment variables. Like docker with fallback an value maybe in a file.
## History
0.4.0 Better fallback

View File

@@ -21,8 +21,8 @@
//! # Examples //! # Examples
//! //!
//! ```rust //! ```rust
//! use no_man_sky::config::EnvKey; //! use merlin_env_helper::config::EnvKey;
//! use no_man_sky::config::get_env_value; //! use merlin_env_helper::config::get_env_value;
//! let env_key = EnvKey::key("MY_CONFIG_KEY"); //! let env_key = EnvKey::key("MY_CONFIG_KEY");
//! match get_env_value(&env_key) { //! match get_env_value(&env_key) {
//! Ok(value) => println!("Config value: {}", value), //! Ok(value) => println!("Config value: {}", value),
@@ -30,13 +30,17 @@
//! } //! }
//! ``` //! ```
use core::fmt; use core::fmt;
use std::{error::Error, fmt::{Display, Formatter}, io::{self, Read}, path::Path}; use std::{
error::Error,
fmt::{Display, Formatter},
io::{self, Read},
path::Path,
};
use crate::config::types::EnvKey; use crate::config::types::EnvKey;
pub type Result<T, E = ConfigError> = std::result::Result<T, E>; pub type Result<T, E = ConfigError> = std::result::Result<T, E>;
#[derive(Debug)] #[derive(Debug)]
#[non_exhaustive] #[non_exhaustive]
pub struct ConfigError { pub struct ConfigError {
@@ -60,7 +64,6 @@ impl Error for ConfigError {
} }
} }
/// The kind of error that can occur when reading a configuration key. /// The kind of error that can occur when reading a configuration key.
#[derive(Debug)] #[derive(Debug)]
pub enum ConfigErrorKind { pub enum ConfigErrorKind {
@@ -82,17 +85,26 @@ impl Display for ConfigErrorMessage {
} }
} }
impl Error for ConfigErrorMessage { impl Error for ConfigErrorMessage {}
}
/// Retrieves the value of an environment variable or a secure file-based secret.
/// If not specified, a fallback value is returned if one is specified, otherwise an error is returned.
pub fn get_env_value(env_key : &EnvKey) -> Result<String> { pub fn get_env_value(env_key: &EnvKey) -> Result<String> {
if let Some(sec_key) = &env_key.sec_key { if let Some(sec_key) = &env_key.sec_key {
let key = std::env::var(&sec_key); let key = std::env::var(&sec_key);
if let Ok(path_file) = key { if let Ok(path_file) = key {
return read_secure_value(&env_key.key, &path_file); let result = read_secure_value(&env_key.key, &path_file);
if let Ok(value) = result {
return Ok(value);
}
if let Some(fallback) = &env_key.fallback {
return Ok(fallback.to_string());
}
return result;
} }
} }
@@ -102,7 +114,6 @@ pub fn get_env_value(env_key : &EnvKey) -> Result<String> {
fn read_key_value(key: &str, fallback: &Option<String>) -> Result<String> { fn read_key_value(key: &str, fallback: &Option<String>) -> Result<String> {
let env_value = std::env::var(key); let env_value = std::env::var(key);
println!("env_value: {:?}", env_value);
if let Ok(value) = env_value { if let Ok(value) = env_value {
return Ok(value); return Ok(value);
} }
@@ -111,21 +122,16 @@ fn read_key_value(key: &str, fallback: &Option<String>) -> Result<String> {
return Ok(fallback.to_string()); return Ok(fallback.to_string());
} }
Err( Err(ConfigError {
ConfigError { key: key.to_string(),
key: key.to_string(), kind: ConfigErrorKind::NotFound,
kind: ConfigErrorKind::NotFound, })
}
)
} }
fn read_secure_value(key: &str, path_file: &str) -> Result<String> { fn read_secure_value(key: &str, path_file: &str) -> Result<String> {
let path = Path::new(path_file); let path = Path::new(path_file);
let exists = path.try_exists().map_err(|e| -> ConfigError { let exists = path.try_exists().map_err(|e| -> ConfigError {
println!("path.try_exists(): {:?}", e);
ConfigError { ConfigError {
key: format!("{}: {} File not found.", key.to_string(), path_file), key: format!("{}: {} File not found.", key.to_string(), path_file),
kind: ConfigErrorKind::IO(e), kind: ConfigErrorKind::IO(e),
@@ -133,18 +139,15 @@ fn read_secure_value(key: &str, path_file: &str) -> Result<String> {
})?; })?;
if !exists { if !exists {
return Err( return Err(ConfigError {
ConfigError { key: format!("{}: {} File not found.", key.to_string(), path_file),
key: format!("{}: {} File not found.", key.to_string(), path_file), kind: ConfigErrorKind::FileNotFound(ConfigErrorMessage {
kind: ConfigErrorKind::FileNotFound(ConfigErrorMessage { msg: format!("File not found: {}", path_file),
msg: format!("File not found: {}", path_file), }),
}), });
}
);
} }
let file = std::fs::File::open(path).map_err(|e| -> ConfigError { let file = std::fs::File::open(path).map_err(|e| -> ConfigError {
println!("std::fs::File::open(path_file): {:?}", e);
ConfigError { ConfigError {
key: key.to_string(), key: key.to_string(),
kind: ConfigErrorKind::IO(e), kind: ConfigErrorKind::IO(e),
@@ -154,17 +157,18 @@ fn read_secure_value(key: &str, path_file: &str) -> Result<String> {
let mut reader = std::io::BufReader::new(file); let mut reader = std::io::BufReader::new(file);
let mut content = String::new(); let mut content = String::new();
reader.read_to_string(&mut content).map_err(|e| -> ConfigError { reader
ConfigError { .read_to_string(&mut content)
key: key.to_string(), .map_err(|e| -> ConfigError {
kind: ConfigErrorKind::IO(e), ConfigError {
} key: key.to_string(),
})?; kind: ConfigErrorKind::IO(e),
}
})?;
Ok(content) Ok(content)
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -172,26 +176,27 @@ mod tests {
fn clean_up(reset_value: &Option<String>) { fn clean_up(reset_value: &Option<String>) {
if let Some(value) = reset_value { if let Some(value) = reset_value {
unsafe {std::env::set_var("TEST_KEY", value)}; unsafe { std::env::set_var("TEST_KEY", value) };
} else { } else {
unsafe {std::env::remove_var("TEST_KEY")}; unsafe { std::env::remove_var("TEST_KEY") };
} }
} }
fn run_test<T, U>(env_key : &str, test: T, clean_up: U) -> () fn run_test<T, U>(env_key: &str, test: T, clean_up: U) -> ()
where T: FnOnce() -> () + std::panic::UnwindSafe where
, U: FnOnce(&Option<String>) -> () T: FnOnce() -> () + std::panic::UnwindSafe,
U: FnOnce(&Option<String>) -> (),
{ {
let old_value = std::env::var(env_key); let old_value = std::env::var(env_key);
let mut reset_value= None; let mut reset_value = None;
if let Ok(value) = old_value { if let Ok(value) = old_value {
reset_value = Some(value.clone()); reset_value = Some(value.clone());
} }
let result = panic::catch_unwind( || { let result = panic::catch_unwind(|| {
test(); test();
}); });
clean_up(&reset_value); clean_up(&reset_value);
@@ -200,54 +205,60 @@ mod tests {
#[test] #[test]
fn test_get_env_value() { fn test_get_env_value() {
run_test(
run_test("TEST_KEY", || { "TEST_KEY",
let key = "TEST_KEY"; || {
let value = "test_value"; let key = "TEST_KEY";
unsafe {std::env::set_var(key, value)}; let value = "test_value";
let env_key = EnvKey::key(key); unsafe { std::env::set_var(key, value) };
let result = get_env_value(&env_key); let env_key = EnvKey::key(key);
assert_eq!(result.is_ok(), true); let result = get_env_value(&env_key);
assert_eq!(result.unwrap(), value); assert_eq!(result.is_ok(), true);
assert_eq!(result.unwrap(), value);
}, },
clean_up clean_up,
); );
} }
#[test] #[test]
fn test_get_env_value_with_fallback() { fn test_get_env_value_with_fallback() {
run_test("TEST_KEY", || { run_test(
let key = "TEST_KEY"; "TEST_KEY",
let fallback_value = "fallback_value"; || {
let key = "TEST_KEY";
let fallback_value = "fallback_value";
let env_key = EnvKey::key_with_fallback(key, fallback_value); let env_key = EnvKey::key_with_fallback(key, fallback_value);
let result = get_env_value(&env_key); let result = get_env_value(&env_key);
assert_eq!(result.is_ok(), true); assert_eq!(result.is_ok(), true);
assert_eq!(result.unwrap(), fallback_value); assert_eq!(result.unwrap(), fallback_value);
}, },
clean_up); clean_up,
);
} }
#[test] #[test]
fn test_get_env_value_with_secure_key() { fn test_get_env_value_with_secure_key() {
run_test("TEST_KEY", || { run_test(
let key = "TEST_KEY"; "TEST_KEY",
let value = "test_value"; || {
let secure_key = "TEST_KEY_FILE"; let key = "TEST_KEY";
let secure_value = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/test_secret.txt"); let value = "test_value";
let secure_key = "TEST_KEY_FILE";
let secure_value = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("resources/test/test_secret.txt");
unsafe {std::env::set_var(key, value)}; unsafe { std::env::set_var(key, value) };
unsafe {std::env::set_var(secure_key, &secure_value)}; unsafe { std::env::set_var(secure_key, &secure_value) };
assert_eq!(secure_value.try_exists().unwrap(), true); assert_eq!(secure_value.try_exists().unwrap(), true);
let env_key = EnvKey::secure_key(key, secure_key); let env_key = EnvKey::secure_key(key, secure_key);
let result = get_env_value(&env_key); let result = get_env_value(&env_key);
assert_eq!(result.is_ok(), true); assert_eq!(result.is_ok(), true);
assert_eq!(result.unwrap(), "my_secret"); assert_eq!(result.unwrap(), "my_secret");
}, },
clean_up); clean_up,
);
} }
} }

View File

@@ -1,3 +1,12 @@
//! This module serves as the configuration layer for the application.
//!
//! It is divided into submodules:
//! - `env`: Handles environment-specific configuration, such as reading
//! environment variables or setting up runtime parameters.
//! - `types`: Defines shared types and structures used for configuration.
//!
//! The module re-exports items from its submodules for easier access.
pub mod env; pub mod env;
pub mod types; pub mod types;

View File

@@ -1,3 +1,26 @@
/// Represents an environment key with optional secondary key and fallback value.
///
/// This struct is used to define keys for environment variables, with support for
/// optional secondary keys and fallback values.
///
/// # Fields
/// - `key`: The primary key as a `String`.
/// - `sec_key`: An optional secondary key as a `String`.
/// - `fallback`: An optional fallback value as a `String`.
///
/// # Methods
/// - `EnvKey::key(key: &str) -> Self`
/// Creates a new `EnvKey` with the given primary key and no secondary key or fallback value.
///
/// - `EnvKey::key_with_fallback(key: &str, fallback: &str) -> Self`
/// Creates a new `EnvKey` with the given primary key and fallback value, but no secondary key.
///
/// - `EnvKey::secure_key(key: &str, sec_key: &str) -> Self`
/// Creates a new `EnvKey` with the given primary key and secondary key, but no fallback value.
///
/// - `EnvKey::secure_with_fallback(key: &str, sec_key: &str, fallback: &str) -> Self`
/// Creates a new `EnvKey` with the given primary key, secondary key, and fallback value.
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub struct EnvKey { pub struct EnvKey {
pub key: String, pub key: String,

View File

@@ -1 +1,8 @@
/// This module declaration makes the `config` module public, allowing its items to be accessed
/// from outside the current crate. The `pub use config::*;` statement re-exports all public
/// items from the `config` module, making them directly accessible from the root of the crate.
pub mod config; pub mod config;
pub use config::*;