use std::{fs, path::Path};
use rustolio_utils::prelude::*;
use crate::Result;
pub fn create(path: &Path, content: &str) -> Result<()> {
if path.exists() {
return Ok(());
}
let parent = path.parent().context("File has no parent")?;
if !fs::exists(parent).context("Failed to check if parent exists")? {
fs::create_dir_all(parent).context("Failed to create parent dir")?;
}
fs::write(path, content).context(format!("Failed to write file: {path:?}"))
}
pub fn remove(path: &Path) -> Result<()> {
fs::remove_dir_all(path).context("Failed to clear tmp dir")
}
pub fn copy(from: &Path, to: &Path) -> Result<()> {
if !fs::exists(from).context("Failed to check if from exists")? {
return Ok(());
}
if !fs::exists(to).context("Failed to check if to exists")? {
fs::create_dir_all(to).context("Failed to create pkg dir")?;
}
fn copy_rec(from: &Path, to: &Path) -> Result<()> {
assert!(
from.exists(),
"Subpaths must exist at this point - was check beforehand"
);
if !from.is_dir() {
if from.file_name().context("Failed to get filename")? == "tw_info" {
return Ok(());
}
fs::copy(from, to).context("Failed to copy file")?;
return Ok(());
}
fs::create_dir_all(to).context("Failed to create to dir")?;
for entry in fs::read_dir(from).context("Failed to read directory - copy")? {
let entry = entry.context("No permission to read entry")?;
let from_path = entry.path();
let to_path = to.join(entry.file_name());
copy_rec(&from_path, &to_path)?;
}
Ok(())
}
copy_rec(from, to)
}
pub fn read_file_from_all_dirs(path: &Path, filename: &str) -> Result<Vec<String>> {
let mut res = Vec::new();
for entry in fs::read_dir(path).context("Failed to read directory - read_all")? {
let entry = entry.context("No permission to read entry")?;
let Ok(content) = fs::read_to_string(entry.path().join(filename)) else {
continue;
};
res.push(content);
}
Ok(res)
}