diff --git a/src/lib.rs b/src/lib.rs index 7d12d9a..ea173cc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,14 +1,50 @@ -pub fn add(left: usize, right: usize) -> usize { - left + right +use std::env; +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 where TargetType: TryFrom { + CannotReadEnvVar(std::env::VarError), + CannotOpenFile(std::io::Error), + CannotReadFile(std::io::Error), + CannotConvertValue(>::Error), } +/// The result of an attempt at getting a configuration value. +pub type GetFileResult = Result>; + +/// 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(name: &str) -> GetFileResult where TargetType: TryFrom { + 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)] mod tests { use super::*; #[test] fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); + todo!() } }