Compare commits
5 Commits
2e35997243
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
a594517ce1
|
|||
|
ee6b992c8e
|
|||
|
4369d9209d
|
|||
|
8dc577c725
|
|||
|
ca8f4aecb1
|
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -4,4 +4,4 @@ version = 4
|
||||
|
||||
[[package]]
|
||||
name = "merlin_env_helper"
|
||||
version = "0.1.0"
|
||||
version = "0.4.0"
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
[package]
|
||||
name = "merlin_env_helper"
|
||||
version = "0.1.0"
|
||||
version = "0.4.0"
|
||||
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]
|
||||
|
||||
10
README.md
10
README.md
@@ -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
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
//! # Examples
|
||||
//!
|
||||
//! ```rust
|
||||
//! use no_man_sky::config::EnvKey;
|
||||
//! use no_man_sky::config::get_env_value;
|
||||
//! use merlin_env_helper::config::EnvKey;
|
||||
//! use merlin_env_helper::config::get_env_value;
|
||||
//! let env_key = EnvKey::key("MY_CONFIG_KEY");
|
||||
//! match get_env_value(&env_key) {
|
||||
//! Ok(value) => println!("Config value: {}", value),
|
||||
@@ -30,13 +30,17 @@
|
||||
//! }
|
||||
//! ```
|
||||
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;
|
||||
|
||||
pub type Result<T, E = ConfigError> = std::result::Result<T, E>;
|
||||
|
||||
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ConfigError {
|
||||
@@ -60,7 +64,6 @@ impl Error for ConfigError {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// The kind of error that can occur when reading a configuration key.
|
||||
#[derive(Debug)]
|
||||
pub enum ConfigErrorKind {
|
||||
@@ -82,17 +85,26 @@ impl Display for ConfigErrorMessage {
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for ConfigErrorMessage {
|
||||
}
|
||||
impl Error for ConfigErrorMessage {}
|
||||
|
||||
|
||||
|
||||
pub fn get_env_value(env_key : &EnvKey) -> Result<String> {
|
||||
/// 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> {
|
||||
if let Some(sec_key) = &env_key.sec_key {
|
||||
let key = std::env::var(&sec_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> {
|
||||
let env_value = std::env::var(key);
|
||||
|
||||
println!("env_value: {:?}", env_value);
|
||||
if let Ok(value) = env_value {
|
||||
return Ok(value);
|
||||
}
|
||||
@@ -111,21 +122,16 @@ fn read_key_value(key: &str, fallback: &Option<String>) -> Result<String> {
|
||||
return Ok(fallback.to_string());
|
||||
}
|
||||
|
||||
Err(
|
||||
ConfigError {
|
||||
key: key.to_string(),
|
||||
kind: ConfigErrorKind::NotFound,
|
||||
}
|
||||
)
|
||||
Err(ConfigError {
|
||||
key: key.to_string(),
|
||||
kind: ConfigErrorKind::NotFound,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
fn read_secure_value(key: &str, path_file: &str) -> Result<String> {
|
||||
|
||||
let path = Path::new(path_file);
|
||||
|
||||
let exists = path.try_exists().map_err(|e| -> ConfigError {
|
||||
println!("path.try_exists(): {:?}", e);
|
||||
ConfigError {
|
||||
key: format!("{}: {} File not found.", key.to_string(), path_file),
|
||||
kind: ConfigErrorKind::IO(e),
|
||||
@@ -133,18 +139,15 @@ fn read_secure_value(key: &str, path_file: &str) -> Result<String> {
|
||||
})?;
|
||||
|
||||
if !exists {
|
||||
return Err(
|
||||
ConfigError {
|
||||
key: format!("{}: {} File not found.", key.to_string(), path_file),
|
||||
kind: ConfigErrorKind::FileNotFound(ConfigErrorMessage {
|
||||
msg: format!("File not found: {}", path_file),
|
||||
}),
|
||||
}
|
||||
);
|
||||
return Err(ConfigError {
|
||||
key: format!("{}: {} File not found.", key.to_string(), path_file),
|
||||
kind: ConfigErrorKind::FileNotFound(ConfigErrorMessage {
|
||||
msg: format!("File not found: {}", path_file),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
let file = std::fs::File::open(path).map_err(|e| -> ConfigError {
|
||||
println!("std::fs::File::open(path_file): {:?}", e);
|
||||
ConfigError {
|
||||
key: key.to_string(),
|
||||
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 content = String::new();
|
||||
|
||||
reader.read_to_string(&mut content).map_err(|e| -> ConfigError {
|
||||
ConfigError {
|
||||
key: key.to_string(),
|
||||
kind: ConfigErrorKind::IO(e),
|
||||
}
|
||||
})?;
|
||||
reader
|
||||
.read_to_string(&mut content)
|
||||
.map_err(|e| -> ConfigError {
|
||||
ConfigError {
|
||||
key: key.to_string(),
|
||||
kind: ConfigErrorKind::IO(e),
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -172,26 +176,27 @@ mod tests {
|
||||
|
||||
fn clean_up(reset_value: &Option<String>) {
|
||||
if let Some(value) = reset_value {
|
||||
unsafe {std::env::set_var("TEST_KEY", value)};
|
||||
unsafe { std::env::set_var("TEST_KEY", value) };
|
||||
} 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) -> ()
|
||||
where T: FnOnce() -> () + std::panic::UnwindSafe
|
||||
, U: FnOnce(&Option<String>) -> ()
|
||||
fn run_test<T, U>(env_key: &str, test: T, clean_up: U) -> ()
|
||||
where
|
||||
T: FnOnce() -> () + std::panic::UnwindSafe,
|
||||
U: FnOnce(&Option<String>) -> (),
|
||||
{
|
||||
let old_value = std::env::var(env_key);
|
||||
let mut reset_value= None;
|
||||
let old_value = std::env::var(env_key);
|
||||
let mut reset_value = None;
|
||||
|
||||
if let Ok(value) = old_value {
|
||||
reset_value = Some(value.clone());
|
||||
}
|
||||
|
||||
let result = panic::catch_unwind( || {
|
||||
test();
|
||||
});
|
||||
let result = panic::catch_unwind(|| {
|
||||
test();
|
||||
});
|
||||
|
||||
clean_up(&reset_value);
|
||||
|
||||
@@ -200,54 +205,60 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_get_env_value() {
|
||||
|
||||
run_test("TEST_KEY", || {
|
||||
let key = "TEST_KEY";
|
||||
let value = "test_value";
|
||||
unsafe {std::env::set_var(key, value)};
|
||||
let env_key = EnvKey::key(key);
|
||||
let result = get_env_value(&env_key);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
assert_eq!(result.unwrap(), value);
|
||||
|
||||
},
|
||||
clean_up
|
||||
run_test(
|
||||
"TEST_KEY",
|
||||
|| {
|
||||
let key = "TEST_KEY";
|
||||
let value = "test_value";
|
||||
unsafe { std::env::set_var(key, value) };
|
||||
let env_key = EnvKey::key(key);
|
||||
let result = get_env_value(&env_key);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
assert_eq!(result.unwrap(), value);
|
||||
},
|
||||
clean_up,
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_env_value_with_fallback() {
|
||||
run_test("TEST_KEY", || {
|
||||
let key = "TEST_KEY";
|
||||
let fallback_value = "fallback_value";
|
||||
run_test(
|
||||
"TEST_KEY",
|
||||
|| {
|
||||
let key = "TEST_KEY";
|
||||
let fallback_value = "fallback_value";
|
||||
|
||||
let env_key = EnvKey::key_with_fallback(key, fallback_value);
|
||||
let result = get_env_value(&env_key);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
assert_eq!(result.unwrap(), fallback_value);
|
||||
},
|
||||
clean_up);
|
||||
let env_key = EnvKey::key_with_fallback(key, fallback_value);
|
||||
let result = get_env_value(&env_key);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
assert_eq!(result.unwrap(), fallback_value);
|
||||
},
|
||||
clean_up,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_env_value_with_secure_key() {
|
||||
run_test("TEST_KEY", || {
|
||||
let key = "TEST_KEY";
|
||||
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");
|
||||
run_test(
|
||||
"TEST_KEY",
|
||||
|| {
|
||||
let key = "TEST_KEY";
|
||||
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(secure_key, &secure_value)};
|
||||
unsafe { std::env::set_var(key, 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 result = get_env_value(&env_key);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
assert_eq!(result.unwrap(), "my_secret");
|
||||
},
|
||||
clean_up);
|
||||
let env_key = EnvKey::secure_key(key, secure_key);
|
||||
let result = get_env_value(&env_key);
|
||||
assert_eq!(result.is_ok(), true);
|
||||
assert_eq!(result.unwrap(), "my_secret");
|
||||
},
|
||||
clean_up,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 types;
|
||||
|
||||
|
||||
@@ -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)]
|
||||
pub struct EnvKey {
|
||||
pub key: String,
|
||||
|
||||
@@ -1 +1,8 @@
|
||||
pub mod config;
|
||||
|
||||
|
||||
/// 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 use config::*;
|
||||
Reference in New Issue
Block a user