1
Fork 0
mirror of https://github.com/Steffo99/micronfig.git synced 2024-11-21 23:54:20 +00:00

Create the library

This commit is contained in:
Steffo 2023-04-27 18:16:49 +00:00 committed by GitHub
parent 4cb8c266da
commit 28a4371f1d
Signed by: github
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,14 +1,50 @@
pub fn add(left: usize, right: usize) -> usize { use std::env;
left + right use std::ffi::OsString;
use std::io::Read;
use std::path::PathBuf;
use std::fs::File;
/// An error that occurred while getting a configuration value.
pub enum GetFileError<TargetType> where TargetType: TryFrom<String> {
CannotReadEnvVar(std::env::VarError),
CannotOpenFile(std::io::Error),
CannotReadFile(std::io::Error),
CannotConvertValue(<TargetType as TryFrom<String>>::Error),
} }
/// The result of an attempt at getting a configuration value.
pub type GetFileResult<TargetType> = Result<TargetType, GetFileError<TargetType>>;
/// Get a configuration value from a file specified in the given environment variable.
///
///
/// # Parameters
///
/// - `name`: the name of the environment variable containing the location of the file containing the configuration value.
/// - `TargetType`: the struct the contents of the file are to be converted into using [`TryFrom`] [`String`].
///
pub fn get_file<TargetType>(name: &str) -> GetFileResult<TargetType> where TargetType: TryFrom<String> {
let path = env::var(name).map_err(GetFileError::CannotReadEnvVar)?;
let path = OsString::from(path);
let path = PathBuf::from(path);
let mut file = File::open(path).map_err(GetFileError::CannotOpenFile)?;
let mut data = String::new();
file.read_to_string(&mut data).map_err(GetFileError::CannotReadFile)?;
let value = TargetType::try_from(data).map_err(GetFileError::CannotConvertValue)?;
Ok(value)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test] #[test]
fn it_works() { fn it_works() {
let result = add(2, 2); todo!()
assert_eq!(result, 4);
} }
} }