use crate::macro_get_field;
use std::{
env,
fs::{self, File},
io,
path::Path,
};
fn read_file<T, F>(
file_path: &Path,
deserializer: F,
) -> Result<T, Box<dyn std::error::Error>>
where
F: FnOnce(File) -> Result<T, Box<dyn std::error::Error>>,
{
let file = File::open(file_path)?;
deserializer(file)
}
pub fn get_csv_field(
file_path: Option<&str>,
field_index: usize,
) -> Option<Vec<String>> {
file_path.and_then(|file_path| {
let current_dir = env::current_dir().ok()?;
let file_path = Path::new(¤t_dir).join(file_path);
let file = File::open(file_path).ok()?;
let mut rdr = csv::Reader::from_reader(file);
let mut values = Vec::new();
for result in rdr.records() {
let record = result.ok()?;
if let Some(field_value) = record.get(field_index) {
values.push(field_value.to_string());
} else {
return None;
}
}
if values.is_empty() {
None
} else {
Some(values)
}
})
}
macro_get_field!(get_ini_field, serde_ini::from_read);
macro_get_field!(get_json_field, serde_json::from_reader);
macro_get_field!(get_yaml_field, serde_yml::from_reader);
pub fn get_config_field(
file_path: Option<&str>,
file_format: Option<&str>,
field_name: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let file_path = file_path.ok_or("File path is not provided")?;
let format = file_format.ok_or("File format is not provided")?;
match format {
"ini" => get_ini_field(Some(file_path), field_name),
"json" => get_json_field(Some(file_path), field_name),
"yaml" => get_yaml_field(Some(file_path), field_name),
_ => Err(format!(
"Unsupported file format: {}. Supported formats are 'json', 'yaml', and 'ini'.",
format
)
.into()),
}
}
pub fn create_directory(path: &Path) -> io::Result<()> {
fs::create_dir(path).or_else(|e| match e.kind() {
io::ErrorKind::AlreadyExists => Ok(()),
_ => Err(e),
})
}