use std::{error::Error, fs::File, io::Write, os::unix::fs::PermissionsExt, path::Path};
use log::debug;
pub(crate) fn vec_to_string(data: Vec<&str>) -> String {
let mut buffer = String::new();
for buf in data {
buffer.push_str(buf);
}
buffer
}
pub(crate) fn create_file(path: &Path, mode: u32, data: &str) -> Result<(), Box<dyn Error>> {
debug!("Creating the file");
let mut file = File::create(path)?;
debug!("Writing the string in the file");
file.write_all(data.as_bytes())?;
debug!("Syncing data on drive");
file.sync_all()?;
debug!("Set file permission");
let mut perms = file.metadata()?.permissions();
perms.set_mode(mode);
file.set_permissions(perms)?;
Ok(())
}
#[cfg(test)]
mod tests {
use std::{error::Error, fs};
use super::{create_file, vec_to_string, Path};
#[test]
fn test_vec_to_string() -> Result<(), Box<dyn Error>> {
let data = vec!["test", "case"];
let buffer = vec_to_string(data);
if buffer.is_empty() {
Err(From::from("Test failed. Shouldn't be empty"))
} else if buffer == "testcase" {
Ok(())
} else {
Err(From::from("Test failed to convert vec to string correctly"))
}
}
#[test]
fn test_create_file() -> Result<(), Box<dyn Error>> {
let path = Path::new("test.txt");
create_file(path, 0o600, "1234")?;
let data = fs::read_to_string(path)?;
if data == "1234" {
Ok(())
} else {
Err(From::from(
"Test failed! file was not create with the right data",
))
}
}
}