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:
parent
4cb8c266da
commit
28a4371f1d
1 changed files with 40 additions and 4 deletions
44
src/lib.rs
44
src/lib.rs
|
@ -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);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue